def rip_video(index, drive, output):
    log.info('ripping video from "{}" to "{}"...'.format(drive, output))

    try:
        dest = Path(output)
        dest.mkdir(exist_ok=True, parents=True)
    except IOError:
        log.critical("Unable to make directory `{}`.".format(output))
        sys.exit(1)

    cmd = 'makemkvcon -r mkv disc:{} all {}'.format(
        re.sub("[^0-9]", "", index), output)
    p = Popen(shlex.split(cmd),
              shell=False,
              stdout=PIPE,
              universal_newlines=True)

    while True:
        output = p.stdout.readline()
        if p.poll() is not None:
            break
        if output:
            log.info(output.strip())

    log.info('Exit status: {}'.format(p.poll()))

    try:
        log.info("Ejecting `{}`".format(drive))
        d = cdio.Device(drive)
        d.eject_media()
    except cdio.DriverUnsupportedError:
        log.warning("Eject not supported for `{}`".format(drive))
    except cdio.DeviceException:
        log.warning("Eject of CD-ROM drive `{}` failed".format(drive))
Exemple #2
0
 def test_cdda(self):
     """Test functioning CD-DA"""
     global testdir
     device = cdio.Device()
     cuefile = os.path.join(testdir, "cdda.cue")
     device.open(cuefile)
     result = device.get_disc_mode()
     self.assertEqual(result, 'CD-DA', 'get_disc_mode')
     self.assertEqual(device.get_mcn(), '0000010271955', 'get_mcn')
     self.assertRaises(cdio.DriverUnsupportedError, device.get_last_session)
     # self.assertRaises(IOError, device.get_joliet_level)
     result = device.get_num_tracks()
     self.assertEqual(result, 1, 'get_num_tracks')
     disc_last_lsn = device.get_disc_last_lsn()
     self.assertEqual(disc_last_lsn, 302, 'get_disc_last_lsn')
     t = device.get_last_track()
     self.assertEqual(t.track, 1, 'get_last_track')
     self.assertEqual(t.get_last_lsn(), 301, '(track) get_last_lsn')
     self.assertEqual(
         device.get_track_for_lsn(t.get_last_lsn()).track, t.track)
     t = device.get_first_track()
     self.assertEqual(t.track, 1, 'get_first_track')
     self.assertEqual(t.get_format(), 'audio', 'get_track_format')
     device.close()
     return
Exemple #3
0
 def test_exceptions(self):
     """Test that various routines raise proper exceptions"""
     self.device = cdio.Device()
     # No CD or or CD image has been set yet. So these fail
     try:
         lsn = self.device.get_disc_last_lsn()
     except IOError:
         self.assertEqual(True, True, "get_last_lsn() IO Error")
     except cdio.DriverError:
         self.assertEqual(True, True, "get_last_lsn() DriverError")
     else:
         self.assertTrue(False, "get_last_lsn() should raise error")
     self.assertRaises(IOError, self.device.get_disc_mode)
     try:
         track = self.device.get_num_tracks()
     except IOError:
         self.assertEqual(True, True, "get_num_tracks() IO Error")
     except cdio.DriverError:
         self.assertEqual(True, True, "get_num_tracks() DriverError")
     except cdio.TrackError:
         self.assertEqual(True, True, "get_num_tracks() TrackError")
     else:
         self.assertTrue(False, "get_last_lsn() should raise error")
     self.assertRaises(IOError, self.device.get_driver_name)
     self.assertRaises(cdio.DriverUninitError,
                       self.device.get_media_changed)
     self.assertRaises(IOError, self.device.open, "***Invalid device***")
     return
Exemple #4
0
def getDeviceInfo(path):
    try:
        import cdio
    except ImportError:
        return None
    device = cdio.Device(path)
    _, vendor, model, release = device.get_hwinfo()

    return vendor, model, release
Exemple #5
0
 def test_device_default(self):
     """Test getting default device"""
     result1 = cdio.get_default_device_driver(pycdio.DRIVER_DEVICE)
     result2 = cdio.get_default_device_driver()
     self.assertEqual(result1, result2,
                      "get_default_device with/out parameters")
     self.device = cdio.Device()
     result2 = pycdio.get_device()
     if result1 is not None:
         self.assertEqual(result1[0], result2)
         # Now try getting device using driver that we got back
         try:
             device = cdio.Device(driver_id=result1[1])
             result1 = device.get_device()
             self.assertEqual(result1, result2,
                              "get_default_device using driver name")
         except:
             pass
     return
Exemple #6
0
    def test_get_set(self):
        """Test getting and setting CDText"""
        tocpath = os.path.join(os.path.dirname(__file__), "cdtext.toc")
        device = cdio.Device(tocpath, pycdio.DRIVER_CDRDAO)

        text = device.get_cdtext()
        self.assertEquals(text.get(pycdio.CDTEXT_FIELD_PERFORMER, 0), "Performer")
        self.assertEquals(text.get(pycdio.CDTEXT_FIELD_TITLE, 0), "CD Title")
        self.assertEquals(text.get(pycdio.CDTEXT_FIELD_DISCID, 0), "XY12345")

        self.assertEquals(text.get(pycdio.CDTEXT_FIELD_PERFORMER, 1), "Performer")
        self.assertEquals(text.get(pycdio.CDTEXT_FIELD_TITLE, 1), "Track Title")
Exemple #7
0
 def test_read(self):
     """Test functioning of read routines"""
     global testdir
     cuefile = os.path.join(testdir, "isofs-m1.cue")
     device = cdio.Device(source=cuefile)
     # Read the ISO Primary Volume descriptor
     blocks, data = device.read_sectors(16, pycdio.READ_MODE_M1F1)
     self.assertEqual(data[1:6], 'CD001')
     self.assertEqual(blocks, 1)
     blocks, data = device.read_data_blocks(26)
     self.assertEqual(data[6:32], 'GNU GENERAL PUBLIC LICENSE')
     return
Exemple #8
0
 def test_ops(self):
     """Test running miscellaneous operations
     No assumption about the CD-ROM drives is made, so
     we're just going to run operations and see that they
     don't crash."""
     self.device = cdio.Device()
     # FIXME: Broken on Darwin?
     # self.device.open()
     self.device.have_ATAPI()
     # FIXME: Broken on Darwin?
     # self.device.get_media_changed()
     self.assertEqual(True, True, "Test misc operations")
     return
Exemple #9
0
def get_disc_info():
    # See: https://musicbrainz.org/doc/Disc_ID_Calculation for algorithm
    # Some of the stuff described in that doc is already handled by the cdio library. Only
    # the leadout adjustment based on the LBA address of data tracks is missing.
    d = cdio.Device(driver_id=pycdio.DRIVER_UNKNOWN)
    drive_name = d.get_device()

    if d.get_disc_mode() != "CD-DA":
        raise Exception("Not an audio disc.")

    first = pycdio.get_first_track_num(d.cd)
    count = d.get_num_tracks()
    last = first

    tracks = {}
    leadout = None
    for i in range(first, first + count):
        t = d.get_track(i)
        if t.get_format() == "audio":
            tracks[i] = t.get_lba()
            last = i
        elif leadout is None:
            leadout = t.get_lba() - 11400

    if leadout is None:
        leadout = d.get_track(pycdio.CDROM_LEADOUT_TRACK).get_lba()
    tracks[0] = leadout

    data = [
        f"{first:02X}",
        f"{last:02X}",
    ]

    for i in range(100):
        offset = tracks.get(i, 0)
        data.append(f"{offset:08X}")

    sha = hashlib.sha1()
    sha.update("".join(data).encode("utf-8"))

    b64 = base64.b64encode(sha.digest()).decode("utf-8")
    tbl = str.maketrans("+/=", "._-")
    return DiscInfo(
        discid=b64.translate(tbl),
        track_count=count,
    )
def cb_QComboBox(*args):
    global drive
    global drive_name
    selectedName = driveChooseComboBox.currentText()
    print("Selected drive named {!r}", selectedName)
    if (selectedName == err_no_drive):
        drive = None
        drive_name = selectedName
    else:
        try:
            drive = cdio.Device(selectedName)
            drive_name = selectedName
        except OSError:
            drive = None
            drive_name = 'No drive selected'
            cb_refreshDrivesList()

    print("Selected drive named {!s} object {!r}".format(drive_name, drive))
    enableOrDisableRelevantWidgets()
Exemple #11
0
    def __init__(self, device: PathLike = '/dev/cdrom') -> None:
        self._dev_path: Path = Path(device).resolve()
        self._udev_context: pyudev.Context = pyudev.Context()
        self._udev_device: pyudev.Device = pyudev.Devices.from_device_file(
            self._udev_context, str(self._dev_path))

        self._device: cdio.Device = cdio.Device(str(self._dev_path))
        self._cdinfo = None

        # sanity checks
        try:
            self.status()
        except OSError:  # open failed
            if not self.device_name.resolve().is_block_device():
                raise CDPlayerException(
                    f"Device `{self.device_name}' is not a block device")
            else:
                raise CDPlayerException(
                    f"Can't open device `{self.device_name}'")
Exemple #12
0
 def test_bincue(self):
     """Test functioning of BIN/CUE image routines"""
     cuefile = os.path.join(testdir, "cdda.cue")
     device = cdio.Device(source=cuefile)
     # Test known values of various access parameters:
     # access mode, driver name via string and via driver_id
     # and cue name
     result = device.get_arg("access-mode")
     self.assertEqual(
         result,
         'image',
         'get_arg("access_mode")',
     )
     result = device.get_driver_name()
     self.assertEqual(result, 'BIN/CUE', 'get_driver_name')
     result = device.get_driver_id()
     self.assertEqual(result, pycdio.DRIVER_BINCUE, 'get_driver_id')
     result = device.get_arg("cue")
     self.assertEqual(result, cuefile, 'get_arg("cue")')
     # Test getting is_binfile and is_cuefile
     binfile = cdio.is_cuefile(cuefile)
     self.assertEqual(True, binfile != None, "is_cuefile(cuefile)")
     cuefile2 = cdio.is_binfile(binfile)
     # Could check that cuefile2 == cuefile, but some OS's may
     # change the case of files
     self.assertEqual(True, cuefile2 != None, "is_cuefile(binfile)")
     result = cdio.is_tocfile(cuefile)
     self.assertEqual(False, result, "is_tocfile(tocfile)")
     ok, vendor, model, revision = device.get_hwinfo()
     self.assertEqual(True, ok, "get_hwinfo ok")
     self.assertEqual('libcdio', vendor, "get_hwinfo vendor")
     self.assertEqual('CDRWIN', model, "get_hwinfo model")
     result = cdio.is_device(cuefile)
     self.assertEqual(False, result, "is_device(tocfile)")
     result = device.get_media_changed()
     self.assertEqual(False, result, "binfile: get_media_changed")
     # There's a bug in libcdio 0.76 that causes these to crash
     self.assertRaises(cdio.DriverUnsupportedError, device.set_blocksize,
                       2048)
     self.assertRaises(cdio.DriverUnsupportedError, device.set_speed, 5)
     device.close()
     return
Exemple #13
0
 def test_tocfile(self):
     """Test functioning of cdrdao image routines"""
     ## TOC reading needs to be done in the directory where the
     ## TOC/BIN files reside.
     olddir = os.getcwd()
     os.chdir(testdir)
     tocfile = os.path.join(testdir, "cdda.toc")
     device = cdio.Device(tocfile, pycdio.DRIVER_CDRDAO)
     ok, vendor, model, revision = device.get_hwinfo()
     self.assertEqual(True, ok, "get_hwinfo ok")
     self.assertEqual('libcdio', vendor, "get_hwinfo vendor")
     self.assertEqual('cdrdao', model, "get_hwinfo cdrdao")
     # Test known values of various access parameters:
     # access mode, driver name via string and via driver_id
     # and cue name
     result = device.get_arg("access-mode")
     self.assertEqual(
         result,
         'image',
         'get_arg("access_mode")',
     )
     result = device.get_driver_name()
     self.assertEqual(result, 'CDRDAO', 'get_driver_name')
     result = device.get_driver_id()
     self.assertEqual(result, pycdio.DRIVER_CDRDAO, 'get_driver_id')
     result = device.get_arg("source")
     self.assertEqual(result, tocfile, 'get_arg("source")')
     result = device.get_media_changed()
     self.assertEqual(False, result, "tocfile: get_media_changed")
     # Test getting is_tocfile
     result = cdio.is_tocfile(tocfile)
     self.assertEqual(True, result, "is_tocfile(tocfile)")
     result = cdio.is_nrg(tocfile)
     self.assertEqual(False, result, "is_nrgfile(tocfile)")
     result = cdio.is_device(tocfile)
     self.assertEqual(False, result, "is_device(tocfile)")
     self.assertRaises(cdio.DriverUnsupportedError, device.set_blocksize,
                       2048)
     self.assertRaises(cdio.DriverUnsupportedError, device.set_speed, 5)
     device.close()
     os.chdir(olddir)
     return
Exemple #14
0
def current_disc():
    """
    Returns the disc information corresponding to the disc
    currently insterted into the default USB player.
    
    It contains among other data, the musicbrainz disc id
    and the number of tracks.
    """

    try:
        d = cdio.Device(driver_id=pycdio.DRIVER_UNKNOWN)
    except IOError as err:
        d = None

    if d is not None:
        try:
            if d.get_disc_mode() == 'CD-DA':
                d = libdiscid.read(libdiscid.default_device())
            else:
                d = None
        except:
            d = None

    return d
Exemple #15
0
    def do(self, args):
        paths = drive.getAllDevicePaths()

        if not paths:
            print 'No drives found.'
            print 'Create /dev/cdrom if you have a CD drive, '
            print 'or install pycdio for better detection.'

            return

        try:
            import cdio
        except ImportError:
            print 'Install pycdio for vendor/model/release detection.'
            return

        for path in paths:
            device = cdio.Device(path)
            ok, vendor, model, release = device.get_hwinfo()
            print "drive: %s, vendor: %s, model: %s, release: %s" % (
                path, vendor, model, release)

        if not paths:
            print 'No drives found.'
Exemple #16
0
    def do(self, args):
        prog = program.Program(record=self.getRootCommand().record)
        runner = task.SyncRunner()

        def function(r, t):
            r.run(t)

        # if the device is mounted (data session), unmount it
        device = self.parentCommand.options.device
        self.stdout.write('Checking device %s\n' % device)

        prog.loadDevice(device)
        prog.unmountDevice(device)

        version = None

        # first, read the normal TOC, which is fast
        ptoc = common.Persister(self.options.toc_pickle or None)
        if not ptoc.object:
            t = cdrdao.ReadTOCTask(device=device)
            function(runner, t)
            version = t.tasks[1].parser.version
            from pkg_resources import parse_version as V
            # we've built a cdrdao 1.2.3rc2 modified package with the patch
            if V(version) < V('1.2.3rc2p1'):
                self.stdout.write('''
Warning: cdrdao older than 1.2.3 has a pre-gap length bug.
See  http://sourceforge.net/tracker/?func=detail&aid=604751&group_id=2171&atid=102171
''')
            ptoc.persist(t.table)
        ittoc = ptoc.object
        assert ittoc.hasTOC()

        # already show us some info based on this
        prog.getRipResult(ittoc.getCDDBDiscId())
        self.stdout.write("CDDB disc id: %s\n" % ittoc.getCDDBDiscId())
        mbdiscid = ittoc.getMusicBrainzDiscId()
        self.stdout.write("MusicBrainz disc id %s\n" % mbdiscid)

        self.stdout.write("MusicBrainz lookup URL %s\n" %
                          ittoc.getMusicBrainzSubmitURL())

        prog.metadata = prog.getMusicBrainz(ittoc, mbdiscid,
                                            self.options.release)

        if not prog.metadata:
            # fall back to FreeDB for lookup
            cddbid = ittoc.getCDDBValues()
            cddbmd = prog.getCDDB(cddbid)
            if cddbmd:
                self.stdout.write('FreeDB identifies disc as %s\n' % cddbmd)

            if not self.options.unknown:
                prog.ejectDevice(device)
                return -1

        # now, read the complete index table, which is slower
        itable = prog.getTable(runner, ittoc.getCDDBDiscId(), device)

        assert itable.getCDDBDiscId() == ittoc.getCDDBDiscId(), \
            "full table's id %s differs from toc id %s" % (
                itable.getCDDBDiscId(), ittoc.getCDDBDiscId())
        assert itable.getMusicBrainzDiscId() == ittoc.getMusicBrainzDiscId(), \
            "full table's mb id %s differs from toc id mb %s" % (
            itable.getMusicBrainzDiscId(), ittoc.getMusicBrainzDiscId())
        assert itable.getAccurateRipURL() == ittoc.getAccurateRipURL(), \
            "full table's AR URL %s differs from toc AR URL %s" % (
            itable.getAccurateRipURL(), ittoc.getAccurateRipURL())

        prog.outdir = (self.options.output_directory or os.getcwd())
        prog.outdir = prog.outdir.decode('utf-8')
        # here to avoid import gst eating our options
        from morituri.common import encode
        profile = encode.PROFILES[self.options.profile]()

        # result

        prog.result.cdrdao_version = version
        prog.result.cdparanoia_version = cdparanoia.ParanoiaVersion()
        prog.result.offset = int(self.options.offset)
        prog.result.artist = prog.metadata and prog.metadata.artist \
            or 'Unknown Artist'
        prog.result.title = prog.metadata and prog.metadata.title \
            or 'Unknown Title'
        # cdio is optional for now
        try:
            import cdio
            _, prog.result.vendor, prog.result.model, prog.result.release = \
                cdio.Device(device).get_hwinfo()
        except ImportError:
            self.stdout.write(
                'WARNING: pycdio not installed, cannot identify drive\n')
            prog.result.vendor = 'Unknown'
            prog.result.model = 'Unknown'
            prog.result.release = 'Unknown'

        # FIXME: turn this into a method

        def ripIfNotRipped(number):
            # we can have a previous result
            trackResult = prog.result.getTrackResult(number)
            if not trackResult:
                trackResult = result.TrackResult()
                prog.result.tracks.append(trackResult)

            path = prog.getPath(prog.outdir, self.options.track_template,
                                mbdiscid, number) + '.' + profile.extension
            trackResult.number = number

            assert type(path) is unicode, "%r is not unicode" % path
            trackResult.filename = path
            if number > 0:
                trackResult.pregap = itable.tracks[number - 1].getPregap()

            # FIXME: optionally allow overriding reripping
            if os.path.exists(path):
                self.stdout.write('Verifying track %d of %d: %s\n' %
                                  (number, len(itable.tracks),
                                   os.path.basename(path).encode('utf-8')))
                if not prog.verifyTrack(runner, trackResult):
                    self.stdout.write('Verification failed, reripping...\n')
                    os.unlink(path)

            if not os.path.exists(path):
                tries = 0
                self.stdout.write('Ripping track %d of %d: %s\n' %
                                  (number, len(itable.tracks),
                                   os.path.basename(path).encode('utf-8')))
                while tries < MAX_TRIES:
                    tries += 1
                    try:
                        self.debug('ripIfNotRipped: track %d, try %d', number,
                                   tries)
                        prog.ripTrack(runner,
                                      trackResult,
                                      offset=int(self.options.offset),
                                      device=self.parentCommand.options.device,
                                      profile=profile,
                                      taglist=prog.getTagList(number),
                                      what='track %d of %d' %
                                      (number, len(itable.tracks)))
                        break
                    except Exception, e:
                        self.debug('Got exception %r on try %d', e, tries)

                if tries == MAX_TRIES:
                    self.error('Giving up on track %d after %d times' %
                               (number, tries))
                if trackResult.testcrc == trackResult.copycrc:
                    self.stdout.write('Checksums match for track %d\n' %
                                      number)
                else:
                    self.stdout.write(
                        'ERROR: checksums did not match for track %d\n' %
                        number)
                    raise

                self.stdout.write('Peak level: %.2f %%\n' %
                                  (math.sqrt(trackResult.peak) * 100.0, ))
                self.stdout.write('Rip quality: %.2f %%\n' %
                                  (trackResult.quality * 100.0, ))

            # overlay this rip onto the Table
            if number == 0:
                # HTOA goes on index 0 of track 1
                itable.setFile(1, 0, trackResult.filename,
                               ittoc.getTrackStart(1), number)
            else:
                itable.setFile(number, 1, trackResult.filename,
                               ittoc.getTrackLength(number), number)

            prog.saveRipResult()
Exemple #17
0
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os, sys
libdir = os.path.join(os.path.dirname(__file__), '..')
if libdir[-1] != os.path.sep:
    libdir += os.path.sep
sys.path.insert(0, libdir)
import pycdio
import cdio

if sys.argv[1:]:
    try:
        drive_name = sys.argv[1]
        d = cdio.Device(drive_name)
    except IOError:
        print("Problem opening CD-ROM: %s" % drive_name)
        sys.exit(1)
else:
    try:
        d = cdio.Device(driver_id=pycdio.DRIVER_UNKNOWN)
        drive_name = d.get_device()
    except IOError:
        print("Problem finding a CD-ROM")
        sys.exit(1)

try:

    print("Ejecting CD in drive %s" % drive_name)
    d.eject_media()
Exemple #18
0
    def do(self):
        self.config = config.Config()
        self.program = program.Program(self.config,
                                       record=self.options.record,
                                       stdout=sys.stdout)
        self.runner = task.SyncRunner()

        # if the device is mounted (data session), unmount it
        self.device = self.options.device
        sys.stdout.write('Checking device %s\n' % self.device)

        utils.load_device(self.device)
        utils.unmount_device(self.device)

        # first, read the normal TOC, which is fast
        self.ittoc = self.program.getFastToc(self.runner,
                                             self.options.toc_pickle,
                                             self.device)

        # already show us some info based on this
        self.program.getRipResult(self.ittoc.getCDDBDiscId())
        sys.stdout.write("CDDB disc id: %s\n" % self.ittoc.getCDDBDiscId())
        self.mbdiscid = self.ittoc.getMusicBrainzDiscId()
        sys.stdout.write("MusicBrainz disc id %s\n" % self.mbdiscid)

        sys.stdout.write("MusicBrainz lookup URL %s\n" %
                         self.ittoc.getMusicBrainzSubmitURL())

        self.program.metadata = (
            self.program.getMusicBrainz(self.ittoc, self.mbdiscid,
                                        release=self.options.release_id,
                                        country=self.options.country,
                                        prompt=self.options.prompt)
        )

        if not self.program.metadata:
            # fall back to FreeDB for lookup
            cddbid = self.ittoc.getCDDBValues()
            cddbmd = self.program.getCDDB(cddbid)
            if cddbmd:
                sys.stdout.write('FreeDB identifies disc as %s\n' % cddbmd)

            # also used by rip cd info
            if not getattr(self.options, 'unknown', False):
                logger.critical("unable to retrieve disc metadata, "
                                "--unknown not passed")
                return -1

        self.program.result.isCdr = cdrdao.DetectCdr(self.device)
        if (self.program.result.isCdr and
                not getattr(self.options, 'cdr', False)):
            logger.critical("inserted disc seems to be a CD-R, "
                            "--cdr not passed")
            return -1

        # now, read the complete index table, which is slower
        self.itable = self.program.getTable(self.runner,
                                            self.ittoc.getCDDBDiscId(),
                                            self.ittoc.getMusicBrainzDiscId(),
                                            self.device, self.options.offset)

        assert self.itable.getCDDBDiscId() == self.ittoc.getCDDBDiscId(), \
            "full table's id %s differs from toc id %s" % (
                self.itable.getCDDBDiscId(), self.ittoc.getCDDBDiscId())
        assert self.itable.getMusicBrainzDiscId() == \
            self.ittoc.getMusicBrainzDiscId(), \
            "full table's mb id %s differs from toc id mb %s" % (
            self.itable.getMusicBrainzDiscId(),
            self.ittoc.getMusicBrainzDiscId())
        assert self.itable.accuraterip_path() == \
            self.ittoc.accuraterip_path(), \
            "full table's AR URL %s differs from toc AR URL %s" % (
            self.itable.accuraterip_url(), self.ittoc.accuraterip_url())

        if self.program.metadata:
            self.program.metadata.discid = self.ittoc.getMusicBrainzDiscId()

        # result

        self.program.result.cdrdaoVersion = cdrdao.getCDRDAOVersion()
        self.program.result.cdparanoiaVersion = \
            cdparanoia.getCdParanoiaVersion()
        info = drive.getDeviceInfo(self.device)
        if info:
            try:
                self.program.result.cdparanoiaDefeatsCache = \
                    self.config.getDefeatsCache(*info)
            except KeyError as e:
                logger.debug('Got key error: %r' % (e, ))
        self.program.result.artist = self.program.metadata \
            and self.program.metadata.artist \
            or 'Unknown Artist'
        self.program.result.title = self.program.metadata \
            and self.program.metadata.title \
            or 'Unknown Title'
        _, self.program.result.vendor, self.program.result.model, \
            self.program.result.release = \
            cdio.Device(self.device).get_hwinfo()

        self.doCommand()

        if self.options.eject in ('success', 'always'):
            utils.eject_device(self.device)
Exemple #19
0
def info_from_cdtext(disc):
    """
    Extracts metadata from the CDText information if
    it exists on the `disc`. `None` iis returned if
    no CDText information is stored on the disc.
    """
    try:
        d = cdio.Device(driver_id=pycdio.DRIVER_UNKNOWN)
    except IOError as err:
        print("Problem finding a CD-ROM")
        raise err

    if d.get_disc_mode() != 'CD-DA':
        raise NotCDDAError()

    t = d.get_cdtext()

    # Build the dictionnary for album info
    album_info = {
        pycdio.cdtext_field2str(i): t.get(i, 0)
        for i in range(pycdio.MIN_CDTEXT_FIELD, pycdio.MAX_CDTEXT_FIELDS)
        if t.get(i, 0) is not None
    }

    if "TITLE" in album_info:
        disc_info = {"source": "CDText", "album": album_info["TITLE"]}

        if "PERFORMER" in album_info:
            disc_info["albumartist"] = album_info["PERFORMER"]
        elif "COMPOSER" in album_info:
            disc_info["albumartist"] = album_info["COMPOSER"]
        elif "SONGWRITER" in album_info:
            disc_info["albumartist"] = album_info["SONGWRITER"]
    else:
        return None

    disc_info["discid"] = disc.id

    disc_info["tracks"] = {}
    tracks_info = disc_info["tracks"]

    for track in itrack(disc):
        track_info = {
            pycdio.cdtext_field2str(i): t.get(i, int(track))
            for i in range(pycdio.MIN_CDTEXT_FIELD, pycdio.MAX_CDTEXT_FIELDS)
            if t.get(i, int(track)) is not None
        }

        tracks_info[track] = {
            "track": track,
            "album": disc_info["album"],
            "name": "Track {}".format(track),
            "title":
            track_info["TITLE"] if "TITLE" in track_info else "Unknown"
        }

        if "GENRE" in track_info:
            tracks_info[track]["genre"] = track_info["GENRE"]

        if "COMPOSER" in track_info:
            tracks_info[track]["composer"] = track_info["COMPOSER"]

        if "ARRANGER" in track_info:
            tracks_info[track]["conductor"] = track_info["ARRANGER"]

        if "PERFORMER" in track_info:
            tracks_info[track]["artist"] = track_info["PERFORMER"]
        elif "SONGWRITER" in track_info:
            tracks_info[track]["artist"] = track_info["SONGWRITER"]
        elif "COMPOSER" in track_info:
            tracks_info[track]["artist"] = track_info["COMPOSER"]
        else:
            tracks_info[track]["artist"] = "Unknown"

    return disc_info
Exemple #20
0
                pass
            print(s)
            s = ''
        i += 2
        pass
    print('')
    return


opts, argv, read_mode = process_options()
# While sys.argv[0] is a program name and sys.argv[1] the first
# option, argv[0] is the first unprocessed option -- roughly
# the equivalent of sys.argv[1].
if argv[0:]:
    try:
        d = cdio.Device(argv[0])
    except IOError:
        print("Problem opening CD-ROM: %s" % argv[0])
        sys.exit(1)
else:
    try:
        d = cdio.Device(driver_id=pycdio.DRIVER_UNKNOWN)
    except IOError:
        print("Problem finding a CD-ROM")
        sys.exit(1)

## All this setup just to issue this one of these commands.
if read_mode == None:
    blocks, data = d.read_data_blocks(opts.start, opts.number)
else:
    blocks, data = d.read_sectors(opts.start, read_mode, opts.number)
Exemple #21
0
cdName = '/dev/cdrom'  #variable para localizacion de cdrom default: /dev/cdrom
format = 'wav'  #variable para formato de salida default: wav
isTrackNum = False  #variable para checkear si se aclaro un numero de track
faso_array = []  #array para guardar los diferentes tracks


help = """ Parameters: 
-cd 		changes what cdrom cdriper uses. eg: -cd /dev/cdrom 
-"num" 		selects a single track from the cd. eg: -2 (only converts second track)
-open 		opens cdrom
-format 	selects the output file format default: wav. eg: -format flac
-h 			displays help.
-? 			displays help.""" #string con toda la info de ayuda

d = cdio.Device(cdName)  #Variable usada luego para abrir el cd

faso = str(sys.argv)  #se chequea si hay argumentos
argument = faso.find('-')  #se busca - para señalizar un comando

if argument != -1:  #si hay un argumentos

    faso = faso[argument:]
    firstLine = faso.find("-")
    secondLine = faso.rfind("-")

    while True:  #se comienza un loop para checkear argumentos

        firstLine = faso.find("-")
        secondLine = faso.rfind("-")  # se checkea si hay mas de 1 argumento
Exemple #22
0
def eject():
    try:
        d = cdio.Device(driver_id=pycdio.DRIVER_UNKNOWN)
        d.eject_media()
    except:
        print_error()
Exemple #23
0
class _CD(logcommand.LogCommand):
    """
    @type program: L{program.Program}
    @ivar eject:   whether to eject the drive after completing
    """

    eject = True

    def addOptions(self):
        # FIXME: have a cache of these pickles somewhere
        self.parser.add_option(
            '-T',
            '--toc-pickle',
            action="store",
            dest="toc_pickle",
            help="pickle to use for reading and writing the TOC")
        self.parser.add_option(
            '-R',
            '--release-id',
            action="store",
            dest="release_id",
            help="MusicBrainz release id to match to (if there are multiple)")
        self.parser.add_option(
            '-p',
            '--prompt',
            action="store_true",
            dest="prompt",
            help="Prompt if there are multiple matching releases")
        self.parser.add_option('-c',
                               '--country',
                               action="store",
                               dest="country",
                               help="Filter releases by country")

    def do(self, args):
        self.program = program.Program(self.getRootCommand().config,
                                       record=self.getRootCommand().record,
                                       stdout=self.stdout)
        self.runner = task.SyncRunner()

        # if the device is mounted (data session), unmount it
        self.device = self.parentCommand.options.device
        self.stdout.write('Checking device %s\n' % self.device)

        self.program.loadDevice(self.device)
        self.program.unmountDevice(self.device)

        # first, read the normal TOC, which is fast
        self.ittoc = self.program.getFastToc(self.runner,
                                             self.options.toc_pickle,
                                             self.device)

        # already show us some info based on this
        self.program.getRipResult(self.ittoc.getCDDBDiscId())
        self.stdout.write("CDDB disc id: %s\n" % self.ittoc.getCDDBDiscId())
        self.mbdiscid = self.ittoc.getMusicBrainzDiscId()
        self.stdout.write("MusicBrainz disc id %s\n" % self.mbdiscid)

        self.stdout.write("MusicBrainz lookup URL %s\n" %
                          self.ittoc.getMusicBrainzSubmitURL())

        self.program.metadata = self.program.getMusicBrainz(
            self.ittoc,
            self.mbdiscid,
            release=self.options.release_id,
            country=self.options.country,
            prompt=self.options.prompt)

        if not self.program.metadata:
            # fall back to FreeDB for lookup
            cddbid = self.ittoc.getCDDBValues()
            cddbmd = self.program.getCDDB(cddbid)
            if cddbmd:
                self.stdout.write('FreeDB identifies disc as %s\n' % cddbmd)

            # also used by rip cd info
            if not getattr(self.options, 'unknown', False):
                if self.eject:
                    self.program.ejectDevice(self.device)
                return -1

        # Hackish fix for broken commit
        offset = 0
        info = drive.getDeviceInfo(self.parentCommand.options.device)
        if info:
            try:
                offset = self.getRootCommand().config.getReadOffset(*info)
            except KeyError:
                pass

        # now, read the complete index table, which is slower
        self.itable = self.program.getTable(self.runner,
                                            self.ittoc.getCDDBDiscId(),
                                            self.ittoc.getMusicBrainzDiscId(),
                                            self.device, offset)

        assert self.itable.getCDDBDiscId() == self.ittoc.getCDDBDiscId(), \
            "full table's id %s differs from toc id %s" % (
                self.itable.getCDDBDiscId(), self.ittoc.getCDDBDiscId())
        assert self.itable.getMusicBrainzDiscId() == \
            self.ittoc.getMusicBrainzDiscId(), \
            "full table's mb id %s differs from toc id mb %s" % (
            self.itable.getMusicBrainzDiscId(),
            self.ittoc.getMusicBrainzDiscId())
        assert self.itable.getAccurateRipURL() == \
            self.ittoc.getAccurateRipURL(), \
            "full table's AR URL %s differs from toc AR URL %s" % (
            self.itable.getAccurateRipURL(), self.ittoc.getAccurateRipURL())

        if self.program.metadata:
            self.program.metadata.discid = self.ittoc.getMusicBrainzDiscId()

        # result

        self.program.result.cdrdaoVersion = cdrdao.getCDRDAOVersion()
        self.program.result.cdparanoiaVersion = \
            cdparanoia.getCdParanoiaVersion()
        info = drive.getDeviceInfo(self.parentCommand.options.device)
        if info:
            try:
                self.program.result.cdparanoiaDefeatsCache = \
                    self.getRootCommand().config.getDefeatsCache(*info)
            except KeyError, e:
                self.debug('Got key error: %r' % (e, ))
        self.program.result.artist = self.program.metadata \
            and self.program.metadata.artist \
            or 'Unknown Artist'
        self.program.result.title = self.program.metadata \
            and self.program.metadata.title \
            or 'Unknown Title'
        try:
            import cdio
            _, self.program.result.vendor, self.program.result.model, \
                self.program.result.release = \
                cdio.Device(self.device).get_hwinfo()
        except ImportError:
            raise ImportError("Pycdio module import failed.\n"
                              "This is a hard dependency: if not "
                              "available please install it")

        self.doCommand()

        if self.eject:
            self.program.ejectDevice(self.device)
Exemple #24
0
    def do(self):
        self.config = config.Config()
        self.program = program.Program(self.config,
                                       record=self.options.record)
        self.runner = task.SyncRunner()

        # if the device is mounted (data session), unmount it
        self.device = self.options.device
        logger.info('checking device %s', self.device)

        if self.options.drive_auto_close is True:
            utils.load_device(self.device)
        utils.unmount_device(self.device)
        # Exit and inform the user if there's no CD in the disk drive
        if drive.get_cdrom_drive_status(self.device) == 1:  # rc 1 -> no disc
            raise OSError("no CD detected, please insert one and retry")

        # first, read the normal TOC, which is fast
        self.ittoc = self.program.getFastToc(self.runner, self.device)

        # already show us some info based on this
        self.program.getRipResult()
        print("CDDB disc id: %s" % self.ittoc.getCDDBDiscId())
        self.mbdiscid = self.ittoc.getMusicBrainzDiscId()
        print("MusicBrainz disc id %s" % self.mbdiscid)

        print("MusicBrainz lookup URL %s" %
              self.ittoc.getMusicBrainzSubmitURL())

        self.program.metadata = (
            self.program.getMusicBrainz(self.ittoc, self.mbdiscid,
                                        release=self.options.release_id,
                                        country=self.options.country,
                                        prompt=self.options.prompt)
        )

        if not self.program.metadata:
            # fall back to FreeDB for lookup
            cddbid = self.ittoc.getCDDBValues()
            cddbmd = self.program.getCDDB(cddbid)
            if cddbmd:
                logger.info('FreeDB identifies disc as %s', cddbmd)

            # also used by rip cd info
            if not getattr(self.options, 'unknown', False):
                logger.critical("unable to retrieve disc metadata, "
                                "--unknown argument not passed")
                return -1

        self.program.result.isCdr = cdrdao.DetectCdr(self.device)
        if (self.program.result.isCdr and
                not getattr(self.options, 'cdr', False)):
            logger.critical("inserted disc seems to be a CD-R, "
                            "--cdr not passed")
            return -1

        # Change working directory before cdrdao's task
        if getattr(self.options, 'working_directory', False):
            os.chdir(os.path.expanduser(self.options.working_directory))
        if hasattr(self.options, 'output_directory'):
            out_bpath = self.options.output_directory
            # Needed to preserve cdrdao's tocfile
            out_fpath = self.program.getPath(out_bpath,
                                             self.options.disc_template,
                                             self.mbdiscid,
                                             self.program.metadata)
        else:
            out_fpath = None
        # now, read the complete index table, which is slower
        offset = getattr(self.options, 'offset', 0)
        self.itable = self.program.getTable(self.runner,
                                            self.ittoc.getCDDBDiscId(),
                                            self.ittoc.getMusicBrainzDiscId(),
                                            self.device, offset, out_fpath)

        assert self.itable.getCDDBDiscId() == self.ittoc.getCDDBDiscId(), \
            "full table's id %s differs from toc id %s" % (
                self.itable.getCDDBDiscId(), self.ittoc.getCDDBDiscId())
        assert self.itable.getMusicBrainzDiscId() == \
            self.ittoc.getMusicBrainzDiscId(), \
            "full table's mb id %s differs from toc id mb %s" % (
            self.itable.getMusicBrainzDiscId(),
            self.ittoc.getMusicBrainzDiscId())

        if self.program.metadata:
            self.program.metadata.discid = self.ittoc.getMusicBrainzDiscId()

        # result

        self.program.result.cdrdaoVersion = cdrdao.version()
        self.program.result.cdparanoiaVersion = \
            cdparanoia.getCdParanoiaVersion()
        info = drive.getDeviceInfo(self.device)
        if info:
            try:
                self.program.result.cdparanoiaDefeatsCache = \
                    self.config.getDefeatsCache(*info)
            except KeyError as e:
                logger.debug('got key error: %r', (e, ))
        self.program.result.artist = self.program.metadata \
            and self.program.metadata.artist \
            or 'Unknown Artist'
        self.program.result.title = self.program.metadata \
            and self.program.metadata.releaseTitle \
            or 'Unknown Title'
        _, self.program.result.vendor, self.program.result.model, \
            self.program.result.release = \
            cdio.Device(self.device).get_hwinfo()
        self.program.result.metadata = self.program.metadata

        ret = self.doCommand()

        if (self.options.eject == 'success' and self.eject or
                self.options.eject == 'always'):
            utils.eject_device(self.device)

        return ret
Exemple #25
0
    for t in range(i_first_track, i_tracks + i_first_track):
        for i in range(pycdio.MIN_CDTEXT_FIELD, pycdio.MAX_CDTEXT_FIELDS):
            value = cdt.get(i, t)
            # value can be empty but exist, compared to NULL values
            if value is not None:
                print("\t%s: %s" % (pycdio.cdtext_field2str(i), value))
                pass
            pass
        pass
    return

if sys.argv[1:]:
    try:
        drive_name = sys.argv[1]
        d = cdio.Device(sys.argv[1])
    except IOError:
        print("Problem opening CD-ROM: %s" % drive_name)
        sys.exit(1)
else:
    try:
        d = cdio.Device(driver_id=pycdio.DRIVER_UNKNOWN)
        drive_name = d.get_device()
    except IOError:
        print("Problem finding a CD-ROM")
        sys.exit(1)

if pycdio.VERSION_NUM < 83:
    i_tracks = d.get_num_tracks()
    i_first_track = pycdio.get_first_track_num(d.cd)
    print_cdtext_track_info_old(d, 0, 'CD-Text for Disc:')