Esempio n. 1
0
class __GIF__(ImageMetrics):
    HEADER = construct.Struct('header',
                        construct.Const(construct.String('gif',3),'GIF'),
                        construct.String('version',3))

    SCREEN_DESCRIPTOR = construct.Struct('logical_screen_descriptor',
                                   construct.ULInt16('width'),
                                   construct.ULInt16('height'),
                                   construct.Embed(
        construct.BitStruct('packed_fields',
                      construct.Flag('global_color_table'),
                      construct.Bits('color_resolution',3),
                      construct.Flag('sort'),
                      construct.Bits('global_color_table_size',3))),
                                   construct.Byte('background_color_index'),
                                   construct.Byte('pixel_aspect_ratio'))

    def __init__(self, width, height, color_count):
        ImageMetrics.__init__(self, width, height, 8, color_count, u'image/gif')

    @classmethod
    def parse(cls, file):
        try:
            header = cls.HEADER.parse_stream(file)
            descriptor = cls.SCREEN_DESCRIPTOR.parse_stream(file)

            return __GIF__(descriptor.width, descriptor.height,
                           2 ** (descriptor.global_color_table_size + 1))
        except construct.ConstError:
            raise InvalidGIF(_(u'Invalid GIF'))
Esempio n. 2
0
 def __init__(self, name):
     construct.Adapter.__init__(
         self,
         construct.Struct(
             name,
             construct.Embed(
                 construct.BitStruct(None, construct.Flag("signed"),
                                     construct.Bits("exponent", 15))),
             construct.UBInt64("mantissa")))
Esempio n. 3
0
                construct.Byte("video_profile"),
                construct.Byte("graphics_profile")),
            0x0E:
            construct.Struct(
                None,
                construct.StrictRepeater(
                    3, construct.Byte("extended_descriptor_type")),
                construct.Byte("descriptor_type_length"),
                construct.String("track_id", 4))
        }))

ATOM_TKHD = construct.Struct(
    "tkhd", construct.Byte("version"),
    construct.BitStruct("flags", construct.Padding(20),
                        construct.Flag("TrackInPoster"),
                        construct.Flag("TrackInPreview"),
                        construct.Flag("TrackInMovie"),
                        construct.Flag("TrackEnabled")),
    VersionLength("created_mac_UTC_date"),
    VersionLength("modified_mac_UTC_date"), construct.UBInt32("track_id"),
    construct.Padding(4), VersionLength("duration"), construct.Padding(8),
    construct.UBInt16("video_layer"), construct.UBInt16("quicktime_alternate"),
    construct.UBInt16("volume"), construct.Padding(2),
    construct.Struct("video", construct.UBInt32("geometry_matrix_a"),
                     construct.UBInt32("geometry_matrix_b"),
                     construct.UBInt32("geometry_matrix_u"),
                     construct.UBInt32("geometry_matrix_c"),
                     construct.UBInt32("geometry_matrix_d"),
                     construct.UBInt32("geometry_matrix_v"),
                     construct.UBInt32("geometry_matrix_x"),
                     construct.UBInt32("geometry_matrix_y"),
Esempio n. 4
0
class ApeTagItem:
    APEv2_FLAGS = construct.BitStruct("APEv2_FLAGS",
                                      construct.Bits("undefined1", 5),
                                      construct.Flag("read_only"),
                                      construct.Bits("encoding", 2),
                                      construct.Bits("undefined2", 16),
                                      construct.Flag("contains_header"),
                                      construct.Flag("contains_no_footer"),
                                      construct.Flag("is_header"),
                                      construct.Bits("undefined3", 5))

    APEv2_TAG = construct.Struct(
        "APEv2_TAG", construct.ULInt32("length"), construct.Embed(APEv2_FLAGS),
        construct.CString("key"),
        construct.MetaField("value", lambda ctx: ctx["length"]))

    #item_type is an int (0 = UTF-8, 1 = binary, 2 = external, 3 = reserved)
    #read_only is a boolean, True if the item is read only
    #key is an ASCII string
    #data is a binary string of the data itself
    def __init__(self, item_type, read_only, key, data):
        self.type = item_type
        self.read_only = read_only
        self.key = key
        self.data = data

    def __repr__(self):
        return "ApeTagItem(%s,%s,%s,%s)" % \
            (repr(self.type),
             repr(self.read_only),
             repr(self.key),
             repr(self.data))

    def __str__(self):
        return self.data

    def __unicode__(self):
        return self.data.rstrip(chr(0)).decode('utf-8', 'replace')

    def build(self):
        return self.APEv2_TAG.build(
            construct.Container(key=self.key,
                                value=self.data,
                                length=len(self.data),
                                encoding=self.type,
                                undefined1=0,
                                undefined2=0,
                                undefined3=0,
                                read_only=self.read_only,
                                contains_header=False,
                                contains_no_footer=False,
                                is_header=False))

    #takes an ASCII key and string of binary data
    #returns an ApeTagItem of that data
    @classmethod
    def binary(cls, key, data):
        return cls(1, False, key, data)

    #takes an ASCII key and string of binary data
    #returns an ApeTagItem of that data
    @classmethod
    def external(cls, key, data):
        return cls(2, False, key, data)

    #takes an ASCII key and a unicode string of data
    #returns an ApeTagItem of that data
    @classmethod
    def string(cls, key, data):
        return cls(0, False, key, data.encode('utf-8', 'replace'))
Esempio n. 5
0
class ApeTag(MetaData):
    ITEM = ApeTagItem

    APEv2_FLAGS = construct.BitStruct("APEv2_FLAGS",
                                      construct.Bits("undefined1", 5),
                                      construct.Flag("read_only"),
                                      construct.Bits("encoding", 2),
                                      construct.Bits("undefined2", 16),
                                      construct.Flag("contains_header"),
                                      construct.Flag("contains_no_footer"),
                                      construct.Flag("is_header"),
                                      construct.Bits("undefined3", 5))

    APEv2_FOOTER = construct.Struct("APEv2", construct.String("preamble", 8),
                                    construct.ULInt32("version_number"),
                                    construct.ULInt32("tag_size"),
                                    construct.ULInt32("item_count"),
                                    construct.Embed(APEv2_FLAGS),
                                    construct.ULInt64("reserved"))

    APEv2_HEADER = APEv2_FOOTER

    APEv2_TAG = ApeTagItem.APEv2_TAG

    ATTRIBUTE_MAP = {
        'track_name': 'Title',
        'track_number': 'Track',
        'track_total': 'Track',
        'album_number': 'Media',
        'album_total': 'Media',
        'album_name': 'Album',
        'artist_name': 'Artist',
        #"Performer" is not a defined APEv2 key
        #it would be nice to have, yet would not be standard
        'performer_name': 'Performer',
        'composer_name': 'Composer',
        'conductor_name': 'Conductor',
        'ISRC': 'ISRC',
        'catalog': 'Catalog',
        'copyright': 'Copyright',
        'publisher': 'Publisher',
        'year': 'Year',
        'date': 'Record Date',
        'comment': 'Comment'
    }

    INTEGER_ITEMS = ('Track', 'Media')

    #tags is a list of ApeTagItem objects
    #tag_length is an optional total length integer
    def __init__(self, tags, tag_length=None):
        for tag in tags:
            if (not isinstance(tag, ApeTagItem)):
                raise ValueError("%s is not ApeTag" % (repr(tag)))
        self.__dict__["tags"] = tags
        self.__dict__["tag_length"] = tag_length

    def __eq__(self, metadata):
        if (isinstance(metadata, ApeTag)):
            if (set(self.keys()) != set(metadata.keys())):
                return False

            for tag in self.tags:
                try:
                    if (tag.data != metadata[tag.key].data):
                        return False
                except KeyError:
                    return False
            else:
                return True
        elif (isinstance(metadata, MetaData)):
            return MetaData.__eq__(self, metadata)
        else:
            return False

    def keys(self):
        return [tag.key for tag in self.tags]

    def __getitem__(self, key):
        for tag in self.tags:
            if (tag.key == key):
                return tag
        else:
            raise KeyError(key)

    def get(self, key, default):
        try:
            return self[key]
        except KeyError:
            return default

    def __setitem__(self, key, value):
        for i in xrange(len(self.tags)):
            if (self.tags[i].key == key):
                self.tags[i] = value
                return
        else:
            self.tags.append(value)

    def index(self, key):
        for (i, tag) in enumerate(self.tags):
            if (tag.key == key):
                return i
        else:
            raise ValueError(key)

    def __delitem__(self, key):
        for i in xrange(len(self.tags)):
            if (self.tags[i].key == key):
                del (self.tags[i])
                return

    #if an attribute is updated (e.g. self.track_name)
    #make sure to update the corresponding dict pair
    def __setattr__(self, key, value):
        if (key in self.ATTRIBUTE_MAP):
            if (key == 'track_number'):
                self['Track'] = self.ITEM.string(
                    'Track', __number_pair__(value, self.track_total))
            elif (key == 'track_total'):
                self['Track'] = self.ITEM.string(
                    'Track', __number_pair__(self.track_number, value))
            elif (key == 'album_number'):
                self['Media'] = self.ITEM.string(
                    'Media', __number_pair__(value, self.album_total))
            elif (key == 'album_total'):
                self['Media'] = self.ITEM.string(
                    'Media', __number_pair__(self.album_number, value))
            else:
                self[self.ATTRIBUTE_MAP[key]] = self.ITEM.string(
                    self.ATTRIBUTE_MAP[key], value)
        else:
            self.__dict__[key] = value

    def __getattr__(self, key):
        if (key == 'track_number'):
            try:
                return int(
                    re.findall('\d+', unicode(self.get("Track", u"0")))[0])
            except IndexError:
                return 0
        elif (key == 'track_total'):
            try:
                return int(
                    re.findall('\d+/(\d+)', unicode(self.get("Track",
                                                             u"0")))[0])
            except IndexError:
                return 0
        elif (key == 'album_number'):
            try:
                return int(
                    re.findall('\d+', unicode(self.get("Media", u"0")))[0])
            except IndexError:
                return 0
        elif (key == 'album_total'):
            try:
                return int(
                    re.findall('\d+/(\d+)', unicode(self.get("Media",
                                                             u"0")))[0])
            except IndexError:
                return 0
        elif (key in self.ATTRIBUTE_MAP):
            return unicode(self.get(self.ATTRIBUTE_MAP[key], u''))
        elif (key in MetaData.__FIELDS__):
            return u''
        else:
            try:
                return self.__dict__[key]
            except KeyError:
                raise AttributeError(key)

    def __delattr__(self, key):
        if (key == 'track_number'):
            setattr(self, 'track_number', 0)
            if ((self.track_number == 0) and (self.track_total == 0)):
                del (self['Track'])
        elif (key == 'track_total'):
            setattr(self, 'track_total', 0)
            if ((self.track_number == 0) and (self.track_total == 0)):
                del (self['Track'])
        elif (key == 'album_number'):
            setattr(self, 'album_number', 0)
            if ((self.album_number == 0) and (self.album_total == 0)):
                del (self['Media'])
        elif (key == 'album_total'):
            setattr(self, 'album_total', 0)
            if ((self.album_number == 0) and (self.album_total == 0)):
                del (self['Media'])
        elif (key in self.ATTRIBUTE_MAP):
            try:
                del (self[self.ATTRIBUTE_MAP[key]])
            except ValueError:
                pass
        elif (key in MetaData.__FIELDS__):
            pass
        else:
            try:
                del (self.__dict__[key])
            except KeyError:
                raise AttributeError(key)

    @classmethod
    def converted(cls, metadata):
        if ((metadata is None) or (isinstance(metadata, ApeTag))):
            return metadata
        else:
            tags = cls([])
            for (field, key) in cls.ATTRIBUTE_MAP.items():
                if (field not in cls.__INTEGER_FIELDS__):
                    field = unicode(getattr(metadata, field))
                    if (len(field) > 0):
                        tags[key] = cls.ITEM.string(key, field)

            if ((metadata.track_number != 0) or (metadata.track_total != 0)):
                tags["Track"] = cls.ITEM.string(
                    "Track",
                    __number_pair__(metadata.track_number,
                                    metadata.track_total))

            if ((metadata.album_number != 0) or (metadata.album_total != 0)):
                tags["Media"] = cls.ITEM.string(
                    "Media",
                    __number_pair__(metadata.album_number,
                                    metadata.album_total))

            for image in metadata.images():
                tags.add_image(image)

            return tags

    def merge(self, metadata):
        metadata = self.__class__.converted(metadata)
        if (metadata is None):
            return

        for tag in metadata.tags:
            if ((tag.key not in ('Track', 'Media')) and (len(str(tag)) > 0)
                    and (len(str(self.get(tag.key, ""))) == 0)):
                self[tag.key] = tag
        for attr in ("track_number", "track_total", "album_number",
                     "album_total"):
            if ((getattr(self, attr) == 0) and (getattr(metadata, attr) != 0)):
                setattr(self, attr, getattr(metadata, attr))

    def __comment_name__(self):
        return u'APEv2'

    #takes two (key,value) apetag pairs
    #returns cmp on the weighted set of them
    #(title first, then artist, album, tracknumber)
    @classmethod
    def __by_pair__(cls, pair1, pair2):
        KEY_MAP = {
            "Title": 1,
            "Album": 2,
            "Track": 3,
            "Media": 4,
            "Artist": 5,
            "Performer": 6,
            "Composer": 7,
            "Conductor": 8,
            "Catalog": 9,
            "Publisher": 10,
            "ISRC": 11,
            #"Media":12,
            "Year": 13,
            "Record Date": 14,
            "Copyright": 15
        }

        return cmp((KEY_MAP.get(pair1[0], 16), pair1[0], pair1[1]),
                   (KEY_MAP.get(pair2[0], 16), pair2[0], pair2[1]))

    def __comment_pairs__(self):
        items = []

        for tag in self.tags:
            if (tag.key in ('Cover Art (front)', 'Cover Art (back)')):
                pass
            elif (tag.type == 0):
                items.append((tag.key, unicode(tag)))
            else:
                if (len(str(tag)) <= 20):
                    items.append((tag.key, str(tag).encode('hex')))
                else:
                    items.append(
                        (tag.key,
                         str(tag).encode('hex')[0:39].upper() + u"\u2026"))

        return sorted(items, ApeTag.__by_pair__)

    @classmethod
    def supports_images(cls):
        return True

    def __parse_image__(self, key, type):
        data = cStringIO.StringIO(str(self[key]))
        description = construct.CString(None).parse_stream(data).decode(
            'utf-8', 'replace')
        data = data.read()
        return Image.new(data, description, type)

    def add_image(self, image):
        if (image.type == 0):
            self['Cover Art (front)'] = self.ITEM.external(
                'Cover Art (front)',
                construct.CString(None).build(
                    image.description.encode('utf-8', 'replace')) + image.data)
        elif (image.type == 1):
            self['Cover Art (back)'] = self.ITEM.binary(
                'Cover Art (back)',
                construct.CString(None).build(
                    image.description.encode('utf-8', 'replace')) + image.data)

    def delete_image(self, image):
        if ((image.type == 0) and 'Cover Art (front)' in self.keys()):
            del (self['Cover Art (front)'])
        elif ((image.type == 1) and 'Cover Art (back)' in self.keys()):
            del (self['Cover Art (back)'])

    def images(self):
        #APEv2 supports only one value per key
        #so a single front and back cover are all that is possible
        img = []
        if ('Cover Art (front)' in self.keys()):
            img.append(self.__parse_image__('Cover Art (front)', 0))
        if ('Cover Art (back)' in self.keys()):
            img.append(self.__parse_image__('Cover Art (back)', 1))
        return img

    #takes a file object of a APEv2 tagged file
    #returns an ApeTag object or None
    @classmethod
    def read(cls, apefile):
        apefile.seek(-32, 2)
        footer = cls.APEv2_FOOTER.parse(apefile.read(32))

        if (footer.preamble != 'APETAGEX'):
            return None

        apefile.seek(-(footer.tag_size), 2)

        return cls([
            ApeTagItem(item_type=tag.encoding,
                       read_only=tag.read_only,
                       key=tag.key,
                       data=tag.value)
            for tag in construct.StrictRepeater(
                footer.item_count, cls.APEv2_TAG).parse(apefile.read())
        ],
                   tag_length=footer.tag_size + ApeTag.APEv2_FOOTER.sizeof()
                   if footer.contains_header else footer.tag_size)

    def build(self):
        header = construct.Container(preamble='APETAGEX',
                                     version_number=2000,
                                     tag_size=0,
                                     item_count=len(self.tags),
                                     undefined1=0,
                                     undefined2=0,
                                     undefined3=0,
                                     read_only=False,
                                     encoding=0,
                                     contains_header=True,
                                     contains_no_footer=False,
                                     is_header=True,
                                     reserved=0l)

        footer = construct.Container(preamble=header.preamble,
                                     version_number=header.version_number,
                                     tag_size=0,
                                     item_count=len(self.tags),
                                     undefined1=0,
                                     undefined2=0,
                                     undefined3=0,
                                     read_only=False,
                                     encoding=0,
                                     contains_header=True,
                                     contains_no_footer=False,
                                     is_header=False,
                                     reserved=0l)

        tags = "".join([tag.build() for tag in self.tags])

        footer.tag_size = header.tag_size = \
          len(tags) + len(ApeTag.APEv2_FOOTER.build(footer))

        return ApeTag.APEv2_FOOTER.build(header) + \
               tags + \
               ApeTag.APEv2_FOOTER.build(footer)
Esempio n. 6
0
class MP3Audio(AudioFile):
    SUFFIX = "mp3"
    NAME = SUFFIX
    DEFAULT_COMPRESSION = "2"
    #0 is better quality/lower compression
    #9 is worse quality/higher compression
    COMPRESSION_MODES = ("0","1","2","3","4","5","6","7","8","9")
    BINARIES = ("lame",)

    #MPEG1, Layer 1
    #MPEG1, Layer 2,
    #MPEG1, Layer 3,
    #MPEG2, Layer 1,
    #MPEG2, Layer 2,
    #MPEG2, Layer 3
    MP3_BITRATE = ((None,None,None,None,None,None),
                   (32,32,32,32,8,8),
                   (64,48,40,48,16,16),
                   (96,56,48,56,24,24),
                   (128,64,56,64,32,32),
                   (160,80,64,80,40,40),
                   (192,96,80,96,48,48),
                   (224,112,96,112,56,56),
                   (256,128,112,128,64,64),
                   (288,160,128,144,80,80),
                   (320,192,160,160,96,96),
                   (352,224,192,176,112,112),
                   (384,256,224,192,128,128),
                   (416,320,256,224,144,144),
                   (448,384,320,256,160,160))

    #MPEG1, MPEG2, MPEG2.5
    MP3_SAMPLERATE = ((44100,22050,11025),
                      (48000,24000,12000),
                      (32000,16000,8000))

    MP3_FRAME_HEADER = construct.BitStruct("mp3_header",
                                  construct.Bits("sync",11),
                                  construct.Bits("mpeg_version",2),
                                  construct.Bits("layer",2),
                                  construct.Bits("protection",1),
                                  construct.Bits("bitrate",4),
                                  construct.Bits("sampling_rate",2),
                                  construct.Bits("padding",1),
                                  construct.Bits("private",1),
                                  construct.Bits("channel",2),
                                  construct.Bits("mode_extension",2),
                                  construct.Bits("copyright",1),
                                  construct.Bits("original",1),
                                  construct.Bits("emphasis",2))

    XING_HEADER = construct.Struct("xing_header",
                             construct.Bytes("header_id",4),
                             construct.Bytes("flags",4),
                             construct.UBInt32("num_frames"),
                             construct.UBInt32("bytes"),
                             construct.StrictRepeater(100,construct.Byte("toc_entries")),
                             construct.UBInt32("quality"))

    def __init__(self, filename):
        AudioFile.__init__(self, filename)

        mp3file = file(filename,"rb")
        try:
            MP3Audio.__find_next_mp3_frame__(mp3file)
            fr = MP3Audio.MP3_FRAME_HEADER.parse(mp3file.read(4))
            self.__samplerate__ = MP3Audio.__get_mp3_frame_sample_rate__(fr)
            self.__channels__ = MP3Audio.__get_mp3_frame_channels__(fr)
            self.__framelength__ = self.__length__()
        finally:
            mp3file.close()

    @classmethod
    def is_type(cls, file):
        ID3v2Comment.skip(file)

        try:
            frame = cls.MP3_FRAME_HEADER.parse_stream(file)
            if ((frame.sync == 0x07FF) and
                (frame.mpeg_version in (0x03,0x02,0x00)) and
                (frame.layer in (0x01,0x03))):
                return True
            else:
                #oddly, MP3s sometimes turn up in RIFF containers
                #this isn't a good idea, but can be supported nonetheless
                file.seek(-cls.MP3_FRAME_HEADER.sizeof(),1)
                header = file.read(12)
                if ((header[0:4] == 'RIFF') and
                    (header[8:12] == 'RMP3')):
                    return True
                else:
                    return False
        except:
            return False

    def lossless(self):
        return False

    def to_pcm(self):
        #if mpg123 is available, use that for decoding
        if (BIN.can_execute(BIN["mpg123"])):
            sub = subprocess.Popen([BIN["mpg123"],"-qs",self.filename],
                                   stdout=subprocess.PIPE,
                                   stderr=file(os.devnull,"a"))
            return PCMReader(sub.stdout,
                             sample_rate=self.sample_rate(),
                             channels=self.channels(),
                             bits_per_sample=16,
                             channel_mask=int(ChannelMask.from_channels(self.channels())),
                             process=sub,
                             big_endian=BIG_ENDIAN)
        else:
            #if not, use LAME for decoding
            if (self.filename.endswith("." + self.SUFFIX)):
                if (BIG_ENDIAN):
                    endian = ['-x']
                else:
                    endian = []

                sub = subprocess.Popen([BIN['lame']] + endian + \
                                           ["--decode","-t","--quiet",
                                            self.filename,"-"],
                                       stdout=subprocess.PIPE)
                return PCMReader(sub.stdout,
                                 sample_rate=self.sample_rate(),
                                 channels=self.channels(),
                                 bits_per_sample=16,
                                 channel_mask=int(ChannelMask.from_channels(self.channels())),
                                 process=sub)
            else:
                import tempfile
                from audiotools import TempWaveReader
                #copy our file to one that ends with .mp3
                tempmp3 = tempfile.NamedTemporaryFile(suffix='.' + self.SUFFIX)
                f = open(self.filename,'rb')
                transfer_data(f.read,tempmp3.write)
                f.close()
                tempmp3.flush()

                #decode the mp3 file to a WAVE file
                wave = tempfile.NamedTemporaryFile(suffix='.wav')
                returnval = subprocess.call([BIN['lame'],"--decode","--quiet",
                                             tempmp3.name,wave.name])
                tempmp3.close()

                if (returnval == 0):
                    #return WAVE file as a stream
                    wave.seek(0,0)
                    return TempWaveReader(wave)
                else:
                    return PCMReaderError(None,
                                          sample_rate=self.sample_rate(),
                                          channels=self.channels(),
                                          bits_per_sample=16)

    @classmethod
    def __help_output__(cls):
        import cStringIO
        help_data = cStringIO.StringIO()
        sub = subprocess.Popen([BIN['lame'],'--help'],
                               stdout=subprocess.PIPE)
        transfer_data(sub.stdout.read,help_data.write)
        sub.wait()
        return help_data.getvalue()

    @classmethod
    def __lame_version__(cls):
        try:
            version = re.findall(r'version \d+\.\d+',
                                 cls.__help_output__())[0]
            return tuple(map(int,version[len('version '):].split(".")))
        except IndexError:
            return (0,0)

    @classmethod
    def from_pcm(cls, filename, pcmreader,
                 compression="2"):
        import decimal,bisect

        if (compression not in cls.COMPRESSION_MODES):
            compression = cls.DEFAULT_COMPRESSION

        if ((pcmreader.channels > 2) or
            (pcmreader.sample_rate not in (32000,48000,44100))):
            pcmreader = PCMConverter(
                pcmreader,
                sample_rate=[32000,32000,44100,48000][bisect.bisect(
                        [32000,44100,48000],pcmreader.sample_rate)],
                channels=min(pcmreader.channels,2),
                channel_mask=ChannelMask.from_channels(min(pcmreader.channels,2)),
                bits_per_sample=16)


        if (pcmreader.channels > 1):
            mode = "j"
        else:
            mode = "m"

        #FIXME - not sure if all LAME versions support "--little-endian"
        # #LAME 3.98 (and up, presumably) handle the byteswap correctly
        # #LAME 3.97 always uses -x
        # if (BIG_ENDIAN or (cls.__lame_version__() < (3,98))):
        #     endian = ['-x']
        # else:
        #     endian = []

        devnull = file(os.devnull,'ab')

        sub = subprocess.Popen([BIN['lame'],"--quiet",
                                "-r",
                                "-s",str(decimal.Decimal(pcmreader.sample_rate) / 1000),
                                "--bitwidth",str(pcmreader.bits_per_sample),
                                "--signed","--little-endian",
                                "-m",mode,
                                "-V" + str(compression),
                                "-",
                                filename],
                               stdin=subprocess.PIPE,
                               stdout=devnull,
                               stderr=devnull,
                               preexec_fn=ignore_sigint)

        transfer_framelist_data(pcmreader,sub.stdin.write)
        try:
            pcmreader.close()
        except DecodingError:
            raise EncodingError()
        sub.stdin.close()

        devnull.close()

        if (sub.wait() == 0):
            return MP3Audio(filename)
        else:
            raise EncodingError(BIN['lame'])

    def bits_per_sample(self):
        return 16

    def channels(self):
        return self.__channels__

    def sample_rate(self):
        return self.__samplerate__

    def get_metadata(self):
        f = file(self.filename,"rb")
        try:
            if (f.read(3) != "ID3"):      #no ID3v2 tag, try ID3v1
                id3v1 = ID3v1Comment.read_id3v1_comment(self.filename)
                if (id3v1[-1] == -1):     #no ID3v1 either
                    return None
                else:
                    return ID3v1Comment(id3v1)
            else:
                id3v2 = ID3v2Comment.read_id3v2_comment(self.filename)

                id3v1 = ID3v1Comment.read_id3v1_comment(self.filename)
                if (id3v1[-1] == -1):      #only ID3v2, no ID3v1
                    return id3v2
                else:                      #both ID3v2 and ID3v1
                    return ID3CommentPair(
                        id3v2,
                        ID3v1Comment(id3v1))
        finally:
            f.close()

    def set_metadata(self, metadata):
        if (metadata is None): return

        if ((not isinstance(metadata,ID3v2Comment)) and
            (not isinstance(metadata,ID3v1Comment))):
            metadata = ID3CommentPair.converted(metadata)

        #metadata = ID3v24Comment.converted(metadata)

        #get the original MP3 data
        f = file(self.filename,"rb")
        MP3Audio.__find_mp3_start__(f)
        data_start = f.tell()
        MP3Audio.__find_last_mp3_frame__(f)
        data_end = f.tell()
        f.seek(data_start,0)
        mp3_data = f.read(data_end - data_start)
        f.close()

        if (isinstance(metadata,ID3CommentPair)):
            id3v2 = metadata.id3v2.build()
            id3v1 = metadata.id3v1.build_tag()
        elif (isinstance(metadata,ID3v2Comment)):
            id3v2 = metadata.build()
            id3v1 = ""
        elif (isinstance(metadata,ID3v1Comment)):
            id3v2 = ""
            id3v1 = metadata.build_tag()

        #write id3v2 + data + id3v1 to file
        f = file(self.filename,"wb")
        f.write(id3v2)
        f.write(mp3_data)
        f.write(id3v1)
        f.close()

    def delete_metadata(self):
        #get the original MP3 data
        f = file(self.filename,"rb")
        MP3Audio.__find_mp3_start__(f)
        data_start = f.tell()
        MP3Audio.__find_last_mp3_frame__(f)
        data_end = f.tell()
        f.seek(data_start,0)
        mp3_data = f.read(data_end - data_start)
        f.close()

        #write data to file
        f = file(self.filename,"wb")
        f.write(mp3_data)
        f.close()

    #places mp3file at the position of the next MP3 frame's start
    @classmethod
    def __find_next_mp3_frame__(cls, mp3file):
        #if we're starting at an ID3v2 header, skip it to save a bunch of time
        ID3v2Comment.skip(mp3file)

        #then find the next mp3 frame
        (b1,b2) = mp3file.read(2)
        while ((b1 != chr(0xFF)) or ((ord(b2) & 0xE0) != 0xE0)):
            mp3file.seek(-1,1)
            (b1,b2) = mp3file.read(2)
        mp3file.seek(-2,1)

    #places mp3file at the position of the MP3 file's start
    #either at the next frame (most commonly)
    #or at the "RIFF????RMP3" header
    @classmethod
    def __find_mp3_start__(cls, mp3file):
        #if we're starting at an ID3v2 header, skip it to save a bunch of time
        ID3v2Comment.skip(mp3file)

        while (True):
            byte = mp3file.read(1)
            while ((byte != chr(0xFF)) and (byte != 'R') and (len(byte) > 0)):
                byte = mp3file.read(1)

            if (byte == chr(0xFF)):  #possibly a frame sync
                mp3file.seek(-1,1)
                try:
                    header = cls.MP3_FRAME_HEADER.parse_stream(mp3file)
                    if ((header.sync == 0x07FF) and
                        (header.mpeg_version in (0x03,0x02,0x00)) and
                        (header.layer in (0x01,0x02,0x03))):
                        mp3file.seek(-4,1)
                        return
                    else:
                        mp3file.seek(-3,1)
                except:
                    continue
            elif (byte == 'R'):   #possibly a 'RIFF????RMP3' header
                header = mp3file.read(11)
                if ((header[0:3] == 'IFF') and
                    (header[7:11] == 'RMP3')):
                    mp3file.seek(-12,1)
                    return
                else:
                    mp3file.seek(-11,1)
            elif (len(byte) == 0): #we've run out of MP3 file
                return

    #places mp3file at the position of the last MP3 frame's end
    #(either the last byte in the file or just before the ID3v1 tag)
    #this may not be strictly accurate if ReplayGain data is present,
    #since APEv2 tags came before the ID3v1 tag,
    #but we're not planning to change that tag anyway
    @classmethod
    def __find_last_mp3_frame__(cls, mp3file):
        mp3file.seek(-128,2)
        if (mp3file.read(3) == 'TAG'):
            mp3file.seek(-128,2)
            return
        else:
            mp3file.seek(0,2)
        return

    #header is a Construct parsed from 4 bytes sent to MP3_FRAME_HEADER
    #returns the total length of the frame, including the header
    #(subtract 4 when doing a seek or read to the next one)
    @classmethod
    def __mp3_frame_length__(cls, header):
        layer = 4 - header.layer  #layer 1, 2 or 3

        bit_rate = MP3Audio.__get_mp3_frame_bitrate__(header)
        if (bit_rate is None): raise MP3Exception(_(u"Invalid bit rate"))

        sample_rate = MP3Audio.__get_mp3_frame_sample_rate__(header)

        #print layer,sample_rate,bit_rate
        if (layer == 1):
            return (12 * (bit_rate * 1000) / sample_rate + header.padding) * 4
        else:
            return 144 * (bit_rate * 1000) / sample_rate + header.padding


    #takes a parsed MP3_FRAME_HEADER
    #returns the mp3's sample rate based on that information
    #(typically 44100)
    @classmethod
    def __get_mp3_frame_sample_rate__(cls, frame):
        try:
            if (frame.mpeg_version == 0x00):   #MPEG 2.5
                return MP3Audio.MP3_SAMPLERATE[frame.sampling_rate][2]
            elif (frame.mpeg_version == 0x02): #MPEG 2
                return MP3Audio.MP3_SAMPLERATE[frame.sampling_rate][1]
            else:                              #MPEG 1
                return MP3Audio.MP3_SAMPLERATE[frame.sampling_rate][0]
        except IndexError:
            raise MP3Exception(_(u"Invalid sampling rate"))

    @classmethod
    def __get_mp3_frame_channels__(cls, frame):
        if (frame.channel == 0x03):
            return 1
        else:
            return 2

    @classmethod
    def __get_mp3_frame_bitrate__(cls, frame):
        layer = 4 - frame.layer  #layer 1, 2 or 3

        try:
            if (frame.mpeg_version == 0x00):   #MPEG 2.5
                return MP3Audio.MP3_BITRATE[frame.bitrate][layer + 2]
            elif (frame.mpeg_version == 0x02): #MPEG 2
                return MP3Audio.MP3_BITRATE[frame.bitrate][layer + 2]
            elif (frame.mpeg_version == 0x03): #MPEG 1
                return MP3Audio.MP3_BITRATE[frame.bitrate][layer - 1]
            else:
                return 0
        except IndexError:
            raise MP3Exception(_(u"Invalid bit rate"))

    def cd_frames(self):
        #calculate length at create-time so that we can
        #throw MP3Exception as soon as possible
        return self.__framelength__

    #returns the length of this file in CD frame
    #raises MP3Exception if any portion of the frame is invalid
    def __length__(self):
        mp3file = file(self.filename,"rb")

        try:
            MP3Audio.__find_next_mp3_frame__(mp3file)

            start_position = mp3file.tell()

            fr = MP3Audio.MP3_FRAME_HEADER.parse(mp3file.read(4))

            first_frame = mp3file.read(MP3Audio.__mp3_frame_length__(fr) - 4)

            sample_rate = MP3Audio.__get_mp3_frame_sample_rate__(fr)

            if (fr.mpeg_version == 0x00):   #MPEG 2.5
                version = 3
            elif (fr.mpeg_version == 0x02): #MPEG 2
                version = 3
            else:                           #MPEG 1
                version = 0

            try:
                if (fr.layer == 0x03):   #layer 1
                    frames_per_sample = 384
                    bit_rate = MP3Audio.MP3_BITRATE[fr.bitrate][version]
                elif (fr.layer == 0x02): #layer 2
                    frames_per_sample = 1152
                    bit_rate = MP3Audio.MP3_BITRATE[fr.bitrate][version + 1]
                elif (fr.layer == 0x01): #layer 3
                    frames_per_sample = 1152
                    bit_rate = MP3Audio.MP3_BITRATE[fr.bitrate][version + 2]
                else:
                    raise MP3Exception(_(u"Unsupported MPEG layer"))
            except IndexError:
                raise MP3Exception(_(u"Invalid bit rate"))

            if ('Xing' in first_frame):
                #the first frame has a Xing header,
                #use that to calculate the mp3's length
                xing_header = MP3Audio.XING_HEADER.parse(
                    first_frame[first_frame.index('Xing'):])

                return (xing_header.num_frames * frames_per_sample * 75 / sample_rate)
            else:
                #no Xing header,
                #assume a constant bitrate file
                mp3file.seek(-128,2)
                if (mp3file.read(3) == "TAG"):
                    end_position = mp3file.tell() - 3
                else:
                    mp3file.seek(0,2)
                    end_position = mp3file.tell()

                return (end_position - start_position) * 75 * 8 / (bit_rate * 1000)
        finally:
            mp3file.close()

    def total_frames(self):
        return self.cd_frames() * self.sample_rate() / 75

    @classmethod
    def can_add_replay_gain(cls):
        return BIN.can_execute(BIN['mp3gain'])

    @classmethod
    def lossless_replay_gain(cls):
        return False

    @classmethod
    def add_replay_gain(cls, filenames):
        track_names = [track.filename for track in
                       open_files(filenames) if
                       isinstance(track,cls)]

        if ((len(track_names) > 0) and (BIN.can_execute(BIN['mp3gain']))):
            devnull = file(os.devnull,'ab')
            sub = subprocess.Popen([BIN['mp3gain'],'-f','-k','-q','-r'] + \
                                       track_names,
                                   stdout=devnull,
                                   stderr=devnull)
            sub.wait()

            devnull.close()
Esempio n. 7
0
class VorbisAudio(AudioFile):
    SUFFIX = "ogg"
    NAME = SUFFIX
    DEFAULT_COMPRESSION = "3"
    COMPRESSION_MODES = tuple([str(i) for i in range(0, 11)])
    BINARIES = ("oggenc", "oggdec")

    OGG_IDENTIFICATION = construct.Struct(
        "ogg_id", construct.ULInt32("vorbis_version"),
        construct.Byte("channels"), construct.ULInt32("sample_rate"),
        construct.ULInt32("bitrate_maximum"),
        construct.ULInt32("bitrate_nominal"),
        construct.ULInt32("bitrate_minimum"),
        construct.Embed(
            construct.BitStruct("flags", construct.Bits("blocksize_0", 4),
                                construct.Bits("blocksize_1", 4))),
        construct.Byte("framing"))

    COMMENT_HEADER = construct.Struct("comment_header",
                                      construct.Byte("packet_type"),
                                      construct.String("vorbis", 6))

    def __init__(self, filename):
        AudioFile.__init__(self, filename)
        self.__read_metadata__()

    @classmethod
    def is_type(cls, file):
        header = file.read(0x23)

        return (header.startswith('OggS')
                and header[0x1C:0x23] == '\x01vorbis')

    def __read_metadata__(self):
        f = OggStreamReader(file(self.filename, "rb"))
        packets = f.packets()

        try:
            #we'll assume this Vorbis file isn't interleaved
            #with any other Ogg stream

            #the Identification packet comes first
            id_packet = packets.next()
            header = VorbisAudio.COMMENT_HEADER.parse(
                id_packet[0:VorbisAudio.COMMENT_HEADER.sizeof()])
            if ((header.packet_type == 0x01) and (header.vorbis == 'vorbis')):
                identification = VorbisAudio.OGG_IDENTIFICATION.parse(
                    id_packet[VorbisAudio.COMMENT_HEADER.sizeof():])
                self.__sample_rate__ = identification.sample_rate
                self.__channels__ = identification.channels
            else:
                raise InvalidFile(_(u'First packet is not Vorbis'))

            #the Comment packet comes next
            comment_packet = packets.next()
            header = VorbisAudio.COMMENT_HEADER.parse(
                comment_packet[0:VorbisAudio.COMMENT_HEADER.sizeof()])
            if ((header.packet_type == 0x03) and (header.vorbis == 'vorbis')):
                self.comment = VorbisComment.VORBIS_COMMENT.parse(
                    comment_packet[VorbisAudio.COMMENT_HEADER.sizeof():])

        finally:
            del (packets)
            f.close()
            del (f)

    def lossless(self):
        return False

    def bits_per_sample(self):
        return 16

    def channels(self):
        return self.__channels__

    def channel_mask(self):
        if (self.channels() == 1):
            return ChannelMask.from_fields(front_center=True)
        elif (self.channels() == 2):
            return ChannelMask.from_fields(front_left=True, front_right=True)
        elif (self.channels() == 3):
            return ChannelMask.from_fields(front_left=True,
                                           front_right=True,
                                           front_center=True)
        elif (self.channels() == 4):
            return ChannelMask.from_fields(front_left=True,
                                           front_right=True,
                                           back_left=True,
                                           back_right=True)
        elif (self.channels() == 5):
            return ChannelMask.from_fields(front_left=True,
                                           front_right=True,
                                           front_center=True,
                                           back_left=True,
                                           back_right=True)
        elif (self.channels() == 6):
            return ChannelMask.from_fields(front_left=True,
                                           front_right=True,
                                           front_center=True,
                                           back_left=True,
                                           back_right=True,
                                           low_frequency=True)
        elif (self.channels() == 7):
            return ChannelMask.from_fields(front_left=True,
                                           front_right=True,
                                           front_center=True,
                                           side_left=True,
                                           side_right=True,
                                           back_center=True,
                                           low_frequency=True)
        elif (self.channels() == 8):
            return ChannelMask.from_fields(front_left=True,
                                           front_right=True,
                                           side_left=True,
                                           side_right=True,
                                           back_left=True,
                                           back_right=True,
                                           front_center=True,
                                           low_frequency=True)
        else:
            return ChannelMask(0)

    def total_frames(self):
        pcm_samples = 0
        f = file(self.filename, "rb")
        try:
            while (True):
                try:
                    page = OggStreamReader.OGGS.parse_stream(f)
                    pcm_samples = page.granule_position
                    f.seek(sum(page.segment_lengths), 1)
                except construct.core.FieldError:
                    break
                except construct.ConstError:
                    break

            return pcm_samples
        finally:
            f.close()

    def sample_rate(self):
        return self.__sample_rate__

    def to_pcm(self):
        sub = subprocess.Popen([
            BIN['oggdec'], '-Q', '-b',
            str(16), '-e',
            str(0), '-s',
            str(1), '-R', '-o', '-', self.filename
        ],
                               stdout=subprocess.PIPE,
                               stderr=file(os.devnull, "a"))

        pcmreader = PCMReader(sub.stdout,
                              sample_rate=self.sample_rate(),
                              channels=self.channels(),
                              channel_mask=int(self.channel_mask()),
                              bits_per_sample=self.bits_per_sample(),
                              process=sub)

        if (self.channels() <= 2):
            return pcmreader
        elif (self.channels() <= 8):
            #these mappings transform Vorbis order into ChannelMask order
            standard_channel_mask = self.channel_mask()
            vorbis_channel_mask = VorbisChannelMask(self.channel_mask())
            return ReorderedPCMReader(pcmreader, [
                vorbis_channel_mask.channels().index(channel)
                for channel in standard_channel_mask.channels()
            ])
        else:
            return pcmreader

    @classmethod
    def from_pcm(cls, filename, pcmreader, compression=None):
        if (compression not in cls.COMPRESSION_MODES):
            compression = cls.DEFAULT_COMPRESSION

        devnull = file(os.devnull, 'ab')

        sub = subprocess.Popen([
            BIN['oggenc'], '-Q', '-r', '-B',
            str(pcmreader.bits_per_sample), '-C',
            str(pcmreader.channels), '-R',
            str(pcmreader.sample_rate), '--raw-endianness',
            str(0), '-q', compression, '-o', filename, '-'
        ],
                               stdin=subprocess.PIPE,
                               stdout=devnull,
                               stderr=devnull,
                               preexec_fn=ignore_sigint)

        if ((pcmreader.channels <= 2) or (int(pcmreader.channel_mask) == 0)):
            transfer_framelist_data(pcmreader, sub.stdin.write)
        elif (pcmreader.channels <= 8):
            if (int(pcmreader.channel_mask) in (
                    0x7,  #FR, FC, FL
                    0x33,  #FR, FL, BR, BL
                    0x37,  #FR, FC, FL, BL, BR
                    0x3f,  #FR, FC, FL, BL, BR, LFE
                    0x70f,  #FL, FC, FR, SL, SR, BC, LFE
                    0x63f)  #FL, FC, FR, SL, SR, BL, BR, LFE
                ):
                standard_channel_mask = ChannelMask(pcmreader.channel_mask)
                vorbis_channel_mask = VorbisChannelMask(standard_channel_mask)
            else:
                raise UnsupportedChannelMask()

            transfer_framelist_data(
                ReorderedPCMReader(pcmreader, [
                    standard_channel_mask.channels().index(channel)
                    for channel in vorbis_channel_mask.channels()
                ]), sub.stdin.write)
        else:
            raise UnsupportedChannelMask()

        try:
            pcmreader.close()
        except DecodingError:
            raise EncodingError()
        sub.stdin.close()

        devnull.close()

        if (sub.wait() == 0):
            return VorbisAudio(filename)
        else:
            raise EncodingError(BIN['oggenc'])

    def set_metadata(self, metadata):
        metadata = VorbisComment.converted(metadata)

        if (metadata is None): return

        reader = OggStreamReader(file(self.filename, 'rb'))
        new_file = cStringIO.StringIO()
        writer = OggStreamWriter(new_file)
        current_sequence_number = 0

        pages = reader.pages()

        #transfer our old header
        #this must always be the first packet and the first page
        (header_page, header_data) = pages.next()
        writer.write_page(header_page, header_data)
        current_sequence_number += 1

        #grab the current "comment" and "setup headers" packets
        #these may take one or more pages,
        #but will always end on a page boundary
        del (pages)
        packets = reader.packets(from_beginning=False)

        comment_packet = packets.next()
        headers_packet = packets.next()

        #write the pages for our new "comment" packet
        for (page, data) in OggStreamWriter.build_pages(
                0, header_page.bitstream_serial_number,
                current_sequence_number,
                VorbisAudio.COMMENT_HEADER.build(
                    construct.Container(packet_type=3, vorbis='vorbis')) +
                metadata.build()):
            writer.write_page(page, data)
            current_sequence_number += 1

        #write the pages for the old "setup headers" packet
        for (page, data) in OggStreamWriter.build_pages(
                0, header_page.bitstream_serial_number,
                current_sequence_number, headers_packet):
            writer.write_page(page, data)
            current_sequence_number += 1

        #write the rest of the pages, re-sequenced and re-checksummed
        del (packets)
        pages = reader.pages(from_beginning=False)

        for (i, (page, data)) in enumerate(pages):
            page.page_sequence_number = i + current_sequence_number
            page.checksum = OggStreamReader.calculate_ogg_checksum(page, data)
            writer.write_page(page, data)

        reader.close()

        #re-write the file with our new data in "new_file"
        f = file(self.filename, "wb")
        f.write(new_file.getvalue())
        f.close()
        writer.close()

        self.__read_metadata__()

    def get_metadata(self):
        self.__read_metadata__()
        data = {}
        for pair in self.comment.value:
            try:
                (key, value) = pair.split('=', 1)
                data.setdefault(key, []).append(value.decode('utf-8'))
            except ValueError:
                continue

        return VorbisComment(data)

    def delete_metadata(self):
        self.set_metadata(MetaData())

    @classmethod
    def add_replay_gain(cls, filenames):
        track_names = [
            track.filename for track in open_files(filenames)
            if isinstance(track, cls)
        ]

        if ((len(track_names) > 0) and BIN.can_execute(BIN['vorbisgain'])):
            devnull = file(os.devnull, 'ab')

            sub = subprocess.Popen([BIN['vorbisgain'], '-q', '-a'] +
                                   track_names,
                                   stdout=devnull,
                                   stderr=devnull)
            sub.wait()
            devnull.close()

    @classmethod
    def can_add_replay_gain(cls):
        return BIN.can_execute(BIN['vorbisgain'])

    @classmethod
    def lossless_replay_gain(cls):
        return True

    def replay_gain(self):
        vorbis_metadata = self.get_metadata()

        if (set([
                'REPLAYGAIN_TRACK_PEAK', 'REPLAYGAIN_TRACK_GAIN',
                'REPLAYGAIN_ALBUM_PEAK', 'REPLAYGAIN_ALBUM_GAIN'
        ]).issubset(vorbis_metadata.keys())):  #we have ReplayGain data
            try:
                return ReplayGain(
                    vorbis_metadata['REPLAYGAIN_TRACK_GAIN'][0][0:-len(" dB")],
                    vorbis_metadata['REPLAYGAIN_TRACK_PEAK'][0],
                    vorbis_metadata['REPLAYGAIN_ALBUM_GAIN'][0][0:-len(" dB")],
                    vorbis_metadata['REPLAYGAIN_ALBUM_PEAK'][0])
            except ValueError:
                return None
        else:
            return None
Esempio n. 8
0
class WavPackAudio(ApeTaggedAudio, AudioFile):
    SUFFIX = "wv"
    NAME = SUFFIX
    DEFAULT_COMPRESSION = "veryhigh"
    COMPRESSION_MODES = ("fast", "standard", "high", "veryhigh")
    BINARIES = ("wavpack", "wvunpack")

    APE_TAG_CLASS = WavePackAPEv2

    HEADER = construct.Struct(
        "wavpackheader", construct.Const(construct.String("id", 4), 'wvpk'),
        construct.ULInt32("block_size"), construct.ULInt16("version"),
        construct.ULInt8("track_number"), construct.ULInt8("index_number"),
        construct.ULInt32("total_samples"), construct.ULInt32("block_index"),
        construct.ULInt32("block_samples"),
        construct.Embed(
            construct.BitStruct("flags", construct.Flag("floating_point_data"),
                                construct.Flag("hybrid_noise_shaping"),
                                construct.Flag("cross_channel_decorrelation"),
                                construct.Flag("joint_stereo"),
                                construct.Flag("hybrid_mode"),
                                construct.Flag("mono_output"),
                                construct.Bits("bits_per_sample", 2),
                                construct.Bits("left_shift_data_low", 3),
                                construct.Flag("final_block_in_sequence"),
                                construct.Flag("initial_block_in_sequence"),
                                construct.Flag("hybrid_noise_balanced"),
                                construct.Flag("hybrid_mode_control_bitrate"),
                                construct.Flag("extended_size_integers"),
                                construct.Bit("sampling_rate_low"),
                                construct.Bits("maximum_magnitude", 5),
                                construct.Bits("left_shift_data_high", 2),
                                construct.Flag("reserved2"),
                                construct.Flag("false_stereo"),
                                construct.Flag("use_IIR"),
                                construct.Bits("reserved1", 2),
                                construct.Bits("sampling_rate_high", 3))),
        construct.ULInt32("crc"))

    SUB_HEADER = construct.Struct(
        "wavpacksubheader",
        construct.Embed(
            construct.BitStruct("flags", construct.Flag("large_block"),
                                construct.Flag("actual_size_1_less"),
                                construct.Flag("nondecoder_data"),
                                construct.Bits("metadata_function", 5))),
        construct.IfThenElse('size', lambda ctx: ctx['large_block'],
                             ULInt24('s'), construct.Byte('s')))

    BITS_PER_SAMPLE = (8, 16, 24, 32)
    SAMPLING_RATE = (6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000,
                     32000, 44100, 48000, 64000, 88200, 96000, 192000, 0)

    def __init__(self, filename):
        self.filename = filename
        self.__samplerate__ = 0
        self.__channels__ = 0
        self.__bitspersample__ = 0
        self.__total_frames__ = 0

        self.__read_info__()

    @classmethod
    def is_type(cls, file):
        return file.read(4) == 'wvpk'

    def lossless(self):
        return True

    @classmethod
    def supports_foreign_riff_chunks(cls):
        return True

    def channel_mask(self):
        fmt_chunk = WaveAudio.FMT_CHUNK.parse(self.__fmt_chunk__())
        if (fmt_chunk.compression != 0xFFFE):
            if (self.__channels__ == 1):
                return ChannelMask.from_fields(front_center=True)
            elif (self.__channels__ == 2):
                return ChannelMask.from_fields(front_left=True,
                                               front_right=True)
            #if we have a multi-channel WavPack file
            #that's not WAVEFORMATEXTENSIBLE,
            #assume the channels follow SMPTE/ITU-R recommendations
            #and hope for the best
            elif (self.__channels__ == 3):
                return ChannelMask.from_fields(front_left=True,
                                               front_right=True,
                                               front_center=True)
            elif (self.__channels__ == 4):
                return ChannelMask.from_fields(front_left=True,
                                               front_right=True,
                                               back_left=True,
                                               back_right=True)
            elif (self.__channels__ == 5):
                return ChannelMask.from_fields(front_left=True,
                                               front_right=True,
                                               back_left=True,
                                               back_right=True,
                                               front_center=True)
            elif (self.__channels__ == 6):
                return ChannelMask.from_fields(front_left=True,
                                               front_right=True,
                                               back_left=True,
                                               back_right=True,
                                               front_center=True,
                                               low_frequency=True)
            else:
                return ChannelMask(0)
        else:
            return WaveAudio.fmt_chunk_to_channel_mask(fmt_chunk.channel_mask)

    def get_metadata(self):
        metadata = ApeTaggedAudio.get_metadata(self)
        if (metadata is not None):
            metadata.frame_count = self.total_frames()
        return metadata

    def has_foreign_riff_chunks(self):
        for (sub_header, nondecoder, data) in self.sub_frames():
            if ((sub_header == 1) and nondecoder):
                return set(__riff_chunk_ids__(data)) != set(['fmt ', 'data'])
        else:
            return False

    def __fmt_chunk__(self):
        for (sub_header, nondecoder, data) in self.sub_frames():
            if ((sub_header == 1) and nondecoder):
                for (chunk_id, chunk_data) in __riff_chunks__(data):
                    if (chunk_id == 'fmt '):
                        return chunk_data
        else:
            return None

    def frames(self):
        f = file(self.filename)
        remaining_samples = None
        try:
            while ((remaining_samples is None) or (remaining_samples > 0)):
                try:
                    header = WavPackAudio.HEADER.parse(
                        f.read(WavPackAudio.HEADER.sizeof()))
                except construct.ConstError:
                    raise InvalidFile(_(u'WavPack header ID invalid'))

                if (remaining_samples is None):
                    remaining_samples = (header.total_samples - \
                                         header.block_samples)
                else:
                    remaining_samples -= header.block_samples

                data = f.read(header.block_size - 24)

                yield (header, data)
        finally:
            f.close()

    def sub_frames(self):
        import cStringIO

        for (header, data) in self.frames():
            total_size = len(data)
            data = cStringIO.StringIO(data)
            while (data.tell() < total_size):
                sub_header = WavPackAudio.SUB_HEADER.parse_stream(data)
                if (sub_header.actual_size_1_less):
                    yield (sub_header.metadata_function,
                           sub_header.nondecoder_data,
                           data.read((sub_header.size * 2) - 1))
                    data.read(1)
                else:
                    yield (sub_header.metadata_function,
                           sub_header.nondecoder_data,
                           data.read(sub_header.size * 2))

    def __read_info__(self):
        f = file(self.filename)
        try:
            try:
                header = WavPackAudio.HEADER.parse(
                    f.read(WavPackAudio.HEADER.sizeof()))
            except construct.ConstError:
                raise InvalidFile(_(u'WavPack header ID invalid'))

            self.__samplerate__ = WavPackAudio.SAMPLING_RATE[(
                header.sampling_rate_high << 1) | header.sampling_rate_low]
            self.__bitspersample__ = WavPackAudio.BITS_PER_SAMPLE[
                header.bits_per_sample]
            self.__total_frames__ = header.total_samples

            self.__channels__ = 0

            #go through as many headers as necessary
            #to count the number of channels
            if (header.mono_output):
                self.__channels__ += 1
            else:
                self.__channels__ += 2

            while (not header.final_block_in_sequence):
                f.seek(header.block_size - 24, 1)
                header = WavPackAudio.HEADER.parse(
                    f.read(WavPackAudio.HEADER.sizeof()))
                if (header.mono_output):
                    self.__channels__ += 1
                else:
                    self.__channels__ += 2
        finally:
            f.close()

    def bits_per_sample(self):
        return self.__bitspersample__

    def channels(self):
        return self.__channels__

    def total_frames(self):
        return self.__total_frames__

    def sample_rate(self):
        return self.__samplerate__

    @classmethod
    def from_pcm(cls, filename, pcmreader, compression=None):
        compression_param = {
            "fast": ["-f"],
            "standard": [],
            "high": ["-h"],
            "veryhigh": ["-hh"]
        }

        if (str(compression) not in cls.COMPRESSION_MODES):
            compression = cls.DEFAULT_COMPRESSION

        if ('--raw-pcm' in cls.__wavpack_help__()):
            if (filename.endswith(".wv")):
                devnull = file(os.devnull, 'ab')

                if (pcmreader.channels > 18):
                    raise UnsupportedChannelMask()
                elif (pcmreader.channels > 2):
                    order_map = {
                        "front_left": "FL",
                        "front_right": "FR",
                        "front_center": "FC",
                        "low_frequency": "LFE",
                        "back_left": "BL",
                        "back_right": "BR",
                        "front_left_of_center": "FLC",
                        "front_right_of_center": "FRC",
                        "back_center": "BC",
                        "side_left": "SL",
                        "side_right": "SR",
                        "top_center": "TC",
                        "top_front_left": "TFL",
                        "top_front_center": "TFC",
                        "top_front_right": "TFR",
                        "top_back_left": "TBL",
                        "top_back_center": "TBC",
                        "top_back_right": "TBR"
                    }

                    channel_order = [
                        "--channel-order=%s" % (",".join([
                            order_map[channel] for channel in ChannelMask(
                                pcmreader.channel_mask).channels()
                        ]))
                    ]
                else:
                    channel_order = []

                sub = subprocess.Popen([BIN['wavpack']] + \
                                           compression_param[compression] + \
                                           ['-q','-y',
                                            "--raw-pcm=%(sr)s,%(bps)s,%(ch)s"%\
                                              {"sr":pcmreader.sample_rate,
                                               "bps":pcmreader.bits_per_sample,
                                               "ch":pcmreader.channels}] + \
                                           channel_order + \
                                           ['-','-o',filename],
                                       stdout=devnull,
                                       stderr=devnull,
                                       stdin=subprocess.PIPE,
                                       preexec_fn=ignore_sigint)

                transfer_framelist_data(pcmreader, sub.stdin.write)
                devnull.close()
                sub.stdin.close()

                if (sub.wait() == 0):
                    return WavPackAudio(filename)
                else:
                    raise EncodingError(BIN['wavpack'])
            else:
                import tempfile

                tempdir = tempfile.mkdtemp()
                symlink = os.path.join(tempdir,
                                       os.path.basename(filename) + ".wv")
                try:
                    os.symlink(os.path.abspath(filename), symlink)
                    cls.from_pcm(symlink, pcmreader, compression)
                    return WavPackAudio(filename)
                finally:
                    os.unlink(symlink)
                    os.rmdir(tempdir)
        else:
            import tempfile

            f = tempfile.NamedTemporaryFile(suffix=".wav")
            w = WaveAudio.from_pcm(f.name, pcmreader)

            try:
                return cls.from_wave(filename, w.filename, compression)
            finally:
                del (w)
                f.close()

    def to_wave(self, wave_filename):
        devnull = file(os.devnull, 'ab')

        #WavPack stupidly refuses to run if the filename doesn't end with .wv
        if (self.filename.endswith(".wv")):
            sub = subprocess.Popen([
                BIN['wvunpack'], '-q', '-y', self.filename, '-o', wave_filename
            ],
                                   stdout=devnull,
                                   stderr=devnull)
            if (sub.wait() != 0):
                raise EncodingError()
        else:
            #create a temporary symlink to the current file
            #rather than rewrite the whole thing
            import tempfile

            tempdir = tempfile.mkdtemp()
            symlink = os.path.join(tempdir,
                                   os.path.basename(self.filename) + ".wv")
            try:
                os.symlink(os.path.abspath(self.filename), symlink)
                WavPackAudio(symlink).to_wave(wave_filename)
            finally:
                os.unlink(symlink)
                os.rmdir(tempdir)

    def to_pcm(self):
        if (self.filename.endswith(".wv")):
            if ('-r' in WavPackAudio.__wvunpack_help__()):
                sub = subprocess.Popen([
                    BIN['wvunpack'], '-q', '-y', self.filename, '-r', '-o', '-'
                ],
                                       stdout=subprocess.PIPE,
                                       stderr=file(os.devnull, 'ab'))

                return PCMReader(sub.stdout,
                                 sample_rate=self.sample_rate(),
                                 channels=self.channels(),
                                 channel_mask=int(self.channel_mask()),
                                 bits_per_sample=self.bits_per_sample(),
                                 process=sub)
            else:
                sub = subprocess.Popen(
                    [BIN['wvunpack'], '-q', '-y', self.filename, '-o', '-'],
                    stdout=subprocess.PIPE,
                    stderr=file(os.devnull, 'ab'))

                return WaveReader(sub.stdout,
                                  sample_rate=self.sample_rate(),
                                  channels=self.channels(),
                                  channel_mask=int(self.channel_mask()),
                                  bits_per_sample=self.bits_per_sample(),
                                  process=sub)
        else:
            #create a temporary symlink to the current file
            #rather than rewrite the whole thing
            (tempdir, symlink) = SymlinkPCMReader.new(self.filename, ".wv")
            return SymlinkPCMReader(
                WavPackAudio(symlink).to_pcm(), tempdir, symlink)

    @classmethod
    def from_wave(cls, filename, wave_filename, compression=None):
        if (str(compression) not in cls.COMPRESSION_MODES):
            compression = cls.DEFAULT_COMPRESSION

        compression_param = {
            "fast": ["-f"],
            "standard": [],
            "high": ["-h"],
            "veryhigh": ["-hh"]
        }

        #wavpack will add a .wv suffix if there isn't one
        #this isn't desired behavior
        if (filename.endswith(".wv")):
            devnull = file(os.devnull, 'ab')

            sub = subprocess.Popen([BIN['wavpack'],
                                    wave_filename] + \
                                   compression_param[compression] + \
                                   ['-q','-y','-o',
                                    filename],
                                   stdout=devnull,
                                   stderr=devnull,
                                   preexec_fn=ignore_sigint)

            devnull.close()

            if (sub.wait() == 0):
                return WavPackAudio(filename)
            else:
                raise EncodingError(BIN['wavpack'])
        else:
            import tempfile

            tempdir = tempfile.mkdtemp()
            symlink = os.path.join(tempdir, os.path.basename(filename) + ".wv")
            try:
                os.symlink(os.path.abspath(filename), symlink)
                cls.from_wave(symlink, wave_filename, compression)
                return WavPackAudio(filename)
            finally:
                os.unlink(symlink)
                os.rmdir(tempdir)

    @classmethod
    def __wavpack_help__(cls):
        devnull = open(os.devnull, "wb")
        sub = subprocess.Popen([BIN["wavpack"], "--help"],
                               stdout=subprocess.PIPE,
                               stderr=devnull)
        help_data = sub.stdout.read()
        sub.stdout.close()
        devnull.close()
        sub.wait()
        return help_data

    @classmethod
    def __wvunpack_help__(cls):
        devnull = open(os.devnull, "wb")
        sub = subprocess.Popen([BIN["wvunpack"], "--help"],
                               stdout=subprocess.PIPE,
                               stderr=devnull)
        help_data = sub.stdout.read()
        sub.stdout.close()
        devnull.close()
        sub.wait()
        return help_data

    @classmethod
    def add_replay_gain(cls, filenames):
        track_names = [
            track.filename for track in open_files(filenames)
            if isinstance(track, cls)
        ]

        if ((len(track_names) > 0) and BIN.can_execute(BIN['wvgain'])):
            devnull = file(os.devnull, 'ab')

            sub = subprocess.Popen([BIN['wvgain'], '-q', '-a'] + track_names,
                                   stdout=devnull,
                                   stderr=devnull)
            sub.wait()
            devnull.close()

    @classmethod
    def can_add_replay_gain(cls):
        return BIN.can_execute(BIN['wvgain'])

    @classmethod
    def lossless_replay_gain(cls):
        return True

    def replay_gain(self):
        metadata = self.get_metadata()
        if (metadata is None):
            return None

        if (set([
                'replaygain_track_gain', 'replaygain_track_peak',
                'replaygain_album_gain', 'replaygain_album_peak'
        ]).issubset(metadata.keys())):  #we have ReplayGain data
            try:
                return ReplayGain(
                    unicode(metadata['replaygain_track_gain'])[0:-len(" dB")],
                    unicode(metadata['replaygain_track_peak']),
                    unicode(metadata['replaygain_album_gain'])[0:-len(" dB")],
                    unicode(metadata['replaygain_album_peak']))
            except ValueError:
                return None
        else:
            return None

    def get_cuesheet(self):
        import cue

        metadata = self.get_metadata()

        if ((metadata is not None) and ('Cuesheet' in metadata.keys())):
            try:
                return cue.parse(
                    cue.tokens(
                        unicode(metadata['Cuesheet']).encode(
                            'utf-8', 'replace')))
            except cue.CueException:
                #unlike FLAC, just because a cuesheet is embedded
                #does not mean it is compliant
                return None
        else:
            return None

    def set_cuesheet(self, cuesheet):
        import os.path
        import cue

        if (cuesheet is None):
            return

        metadata = self.get_metadata()
        if (metadata is None):
            metadata = WavePackAPEv2.converted(MetaData())

        metadata['Cuesheet'] = WavePackAPEv2.ITEM.string(
            'Cuesheet',
            cue.Cuesheet.file(cuesheet,
                              os.path.basename(self.filename)).decode(
                                  'ascii', 'replace'))
        self.set_metadata(metadata)