1# -*- coding: utf-8 -*-
2# Copyright (C) 2006  Joe Wreschnig
3#
4# This program is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation; either version 2 of the License, or
7# (at your option) any later version.
8
9"""True Audio audio stream information and tags.
10
11True Audio is a lossless format designed for real-time encoding and
12decoding. This module is based on the documentation at
13http://www.true-audio.com/TTA_Lossless_Audio_Codec\\_-_Format_Description
14
15True Audio files use ID3 tags.
16"""
17
18__all__ = ["TrueAudio", "Open", "delete", "EasyTrueAudio"]
19
20from ._compat import endswith
21from mutagen import StreamInfo
22from mutagen.id3 import ID3FileType, delete
23from mutagen._util import cdata, MutagenError, convert_error
24
25
26class error(MutagenError):
27    pass
28
29
30class TrueAudioHeaderError(error):
31    pass
32
33
34class TrueAudioInfo(StreamInfo):
35    """TrueAudioInfo()
36
37    True Audio stream information.
38
39    Attributes:
40        length (`float`): audio length, in seconds
41        sample_rate (`int`): audio sample rate, in Hz
42    """
43
44    @convert_error(IOError, TrueAudioHeaderError)
45    def __init__(self, fileobj, offset):
46        """Raises TrueAudioHeaderError"""
47
48        fileobj.seek(offset or 0)
49        header = fileobj.read(18)
50        if len(header) != 18 or not header.startswith(b"TTA"):
51            raise TrueAudioHeaderError("TTA header not found")
52        self.sample_rate = cdata.int_le(header[10:14])
53        samples = cdata.uint_le(header[14:18])
54        self.length = float(samples) / self.sample_rate
55
56    def pprint(self):
57        return u"True Audio, %.2f seconds, %d Hz." % (
58            self.length, self.sample_rate)
59
60
61class TrueAudio(ID3FileType):
62    """TrueAudio(filething, ID3=None)
63
64    A True Audio file.
65
66    Arguments:
67        filething (filething)
68        ID3 (mutagen.id3.ID3)
69
70    Attributes:
71        info (`TrueAudioInfo`)
72        tags (`mutagen.id3.ID3`)
73    """
74
75    _Info = TrueAudioInfo
76    _mimes = ["audio/x-tta"]
77
78    @staticmethod
79    def score(filename, fileobj, header):
80        return (header.startswith(b"ID3") + header.startswith(b"TTA") +
81                endswith(filename.lower(), b".tta") * 2)
82
83
84Open = TrueAudio
85
86
87class EasyTrueAudio(TrueAudio):
88    """EasyTrueAudio(filething, ID3=None)
89
90    Like MP3, but uses EasyID3 for tags.
91
92    Arguments:
93        filething (filething)
94        ID3 (mutagen.id3.ID3)
95
96    Attributes:
97        info (`TrueAudioInfo`)
98        tags (`mutagen.easyid3.EasyID3`)
99    """
100
101    from mutagen.easyid3 import EasyID3 as ID3
102    ID3 = ID3
103