1:mod:`audiotools` --- the Base Python Audio Tools Module 2======================================================== 3 4.. module:: audiotools 5 :synopsis: the Base Python Audio Tools Module 6 7 8The :mod:`audiotools` module contains a number of useful base 9classes and functions upon which all of the other modules depend. 10 11 12.. data:: VERSION 13 14 The current Python Audio Tools version as a plain string. 15 16.. data:: AVAILABLE_TYPES 17 18 A tuple of :class:`AudioFile`-compatible classes of available 19 audio types. 20 Note these are types available to audiotools, not necessarily 21 available to the user - depending on whether the required binaries 22 are installed or not. 23 24 ============= ================================== 25 Class Format 26 ------------- ---------------------------------- 27 AACAudio AAC in ADTS container 28 AiffAudio Audio Interchange File Format 29 ALACAudio Apple Lossless 30 AuAudio Sun Au 31 FlacAudio Native Free Lossless Audio Codec 32 M4AAudio AAC in M4A container 33 MP3Audio MPEG-1 Layer 3 34 MP2Audio MPEG-1 Layer 2 35 OggFlacAudio Ogg Free Lossless Audio Codec 36 OpusAudio Opus Audio Codec 37 ShortenAudio Shorten 38 SpeexAudio Ogg Speex 39 VorbisAudio Ogg Vorbis 40 WaveAudio Waveform Audio File Format 41 WavPackAudio WavPack 42 ============= ================================== 43 44.. data:: DEFAULT_TYPE 45 46 The default type to use as a plain string, such as ``'wav'`` or ``'flac'``. 47 48.. data:: DEFAULT_QUALITY 49 50 A dict of type name strings -> quality value strings 51 indicating the default compression quality value for the given type 52 name suitable for :meth:`AudioFile.from_pcm` and :meth:`AudioFile.convert` 53 method calls. 54 55.. data:: DEFAULT_CDROM 56 57 The default CD-ROM device to use for CD audio and DVD-Audio 58 extraction as a plain string. 59 60.. data:: TYPE_MAP 61 62 A dictionary of type name strings -> :class:`AudioFile` 63 values containing only types which have all required binaries 64 installed. 65 66.. data:: FILENAME_FORMAT 67 68 The default format string to use for newly created files. 69 70.. data:: BIN 71 72 A dictionary-like class for performing lookups of system binaries. 73 This checks the system and user's config files and ensures that 74 any redirected binaries are called from their proper location. 75 For example, if the user has configured ``flac(1)`` to be run 76 from ``/opt/flac/bin/flac`` 77 78 >>> BIN["flac"] 79 "/opt/flac/bin/flac" 80 81 This class also has a ``can_execute()`` method which returns 82 ``True`` if the given binary is executable. 83 84 >>> BIN.can_execute(BIN["flac"]) 85 True 86 87.. data:: IO_ENCODING 88 89 The defined encoding to use for output to the screen as a plain 90 string. 91 This is typically ``'utf-8'``. 92 93.. data:: FS_ENCODING 94 95 The defined encoding to use for filenames read and written to disk 96 as a plain string. 97 This is typically ``'utf-8'``. 98 99.. data:: MAX_JOBS 100 101 The maximum number of simultaneous jobs to run at once by default 102 as an integer. 103 This may be defined from the user's config file. 104 Otherwise, if Python's ``multiprocessing`` module is available, 105 this is set to the user's CPU count. 106 If neither is available, this is set to 1. 107 108.. function:: file_type(file) 109 110 Given a seekable file object returns an :class:`AudioFile`-compatible 111 class of the stream's detected type, or ``None`` 112 if the stream's type is unknown. 113 114 The :class:`AudioFile` class may not be available for use 115 and so its :meth:`AudioFile.available` classmethod 116 may need to be checked separately. 117 118.. function:: open(filename) 119 120 Opens the given filename string and returns an :class:`AudioFile`-compatible 121 object. 122 Raises :exc:`UnsupportedFile` if the file cannot identified or is 123 not supported. 124 Raises :exc:`IOError` if the file cannot be opened at all. 125 126.. function:: open_files(filenames[, sorted][, messenger][, no_duplicates][, warn_duplicates][, opened_files]) 127 128 Given a list of filename strings, returns a list of 129 :class:`AudioFile`-compatible objects which are successfully opened. 130 By default, they are returned sorted by album number and track number. 131 132 If ``sorted`` is ``False``, they are returned in the same order 133 as they appear in the filenames list. 134 135 If ``messenger`` is given, use that :class:`Messenger` object 136 to for warnings if files cannot be opened. 137 Otherwise, such warnings are sent to stdout. 138 139 If ``no_duplicates`` is ``True``, attempting to open 140 the same file twice raises a :exc:`DuplicateFile` exception. 141 142 If ``no_duplicates`` is ``False`` and ``warn_duplicates`` is ``True``, 143 attempting to open the same file twice results in a 144 warning to ``messenger``, if present. 145 146 ``opened_files``, if present, is a set of previously opened 147 :class:`Filename` objects for the purpose of detecting duplicates. 148 Any opened files are added to that set. 149 150.. function:: open_directory(directory[, sorted[, messenger]]) 151 152 Given a root directory, returns an iterator of all the 153 :class:`AudioFile`-compatible objects found via a recursive 154 search of that directory. 155 ``sorted``, and ``messenger`` work as in :func:`open_files`. 156 157.. function:: sorted_tracks(audiofiles) 158 159 Given a list of :class:`AudioFile` objects, 160 returns a new list of those objects sorted by 161 album number and track number, if present. 162 If album number and track number aren't present, 163 objects are sorted by base filename. 164 165.. function:: group_tracks(audiofiles) 166 167 Given an iterable collection of :class:`AudioFile`-compatible objects, 168 returns an iterator of objects grouped into lists by album. 169 That is, all objects with the same ``album_name`` and ``album_number`` 170 metadata fields will be returned in the same list on each pass. 171 172.. function:: filename_to_type(path) 173 174 Given a path, try to guess its :class:`AudioFile` class based on 175 its filename suffix. 176 Raises :exc:`UnknownAudioType` if the suffix is unrecognized. 177 Raises :exc:`AmbiguousAudioType` if more than one type of audio 178 shares the same suffix. 179 180.. function:: transfer_data(from_function, to_function) 181 182 This function takes two functions, presumably analogous 183 to :func:`write` and :func:`read` functions, respectively. 184 It calls ``to_function`` on the object returned by calling 185 ``from_function`` with an integer argument (presumably a string) 186 until that object's length is 0. 187 188 >>> infile = open("input.txt", "r") 189 >>> outfile = open("output.txt", "w") 190 >>> transfer_data(infile.read, outfile.write) 191 >>> infile.close() 192 >>> outfile.close() 193 194.. function:: transfer_framelist_data(pcmreader, to_function[, signed[, big_endian]]) 195 196 A natural progression of :func:`transfer_data`, this function takes 197 a :class:`PCMReader` object and transfers the :class:`pcm.FrameList` 198 objects returned by its :meth:`PCMReader.read` method to ``to_function`` 199 after converting them to plain strings. 200 201 The pcmreader is closed once decoding is complete. 202 203 May raise :exc:`IOError` or :exc:`ValueError` if a problem 204 occurs during decoding. 205 206 >>> pcm_data = audiotools.open("file.wav").to_pcm() 207 >>> outfile = open("output.pcm","wb") 208 >>> transfer_framelist_data(pcm_data,outfile) 209 >>> pcm_data.close() 210 >>> outfile.close() 211 212.. function:: pcm_cmp(pcmreader1, pcmreader2) 213 214 This function takes two :class:`PCMReader` objects and compares 215 their PCM output. 216 Returns ``True`` if that output matches exactly, ``False`` if not. 217 218 Both streams are closed once comparison is completed. 219 220 May raise :exc:`IOError` or :exc:`ValueError` if problems 221 occur during reading. 222 223.. function:: pcm_frame_cmp(pcmreader1, pcmreader2) 224 225 This function takes two :class:`PCMReader` objects and compares 226 their PCM frame output. 227 It returns the frame number of the first mismatch as an integer 228 which begins at frame number 0. 229 If the two streams match completely, it returns ``None``. 230 231 Both streams are closed once comparison is completed. 232 233 May raise :exc:`IOError` or :exc:`ValueError` if problems 234 occur during reading. 235 236.. function:: pcm_split(pcmreader, pcm_lengths) 237 238 Takes a :class:`PCMReader` object and list of PCM sample length integers. 239 Returns an iterator of new :class:`PCMReader` objects, 240 each limited to the given lengths. 241 The original pcmreader is closed upon the iterator's completion. 242 243.. function:: calculate_replay_gain(audiofiles) 244 245 Takes a list of :class:`AudioFile`-compatible objects. 246 Returns an iterator of 247 ``(audiofile, track_gain, track_peak, album_gain, album_peak)`` 248 tuples or raises :exc:`ValueError` if a problem occurs during calculation. 249 250.. function:: read_sheet(filename) 251 252 Given a ``.cue`` or ``.toc`` filename, returns a :class:`Sheet` 253 of that file's cuesheet data. 254 May raise :exc:`SheetException` if the file cannot be read 255 or parsed correctly. 256 257.. function:: to_pcm_progress(audiofile, progress) 258 259 Given an :class:`AudioFile`-compatible object and ``progress`` 260 function, returns a :class:`PCMReaderProgress` object 261 of that object's PCM stream. 262 263 If ``progress`` is ``None``, the audiofile's PCM stream 264 is returned as-is. 265 266Filename Objects 267---------------- 268 269.. class:: Filename(filename) 270 271 :class:`Filename` is a file which may or may not exist on disk. 272 ``filename`` is a raw string of the actual filename. 273 Filename objects are immutable and hashable, 274 which means they can be used as dictionary keys 275 or placed in sets. 276 277 The purpose of Filename objects is for easier 278 conversion of raw string filename paths to Unicode, 279 and to make it easier to detect filenames 280 which point to the same file on disk. 281 282 The former case is used by utilities to display 283 output about file operations in progress. 284 The latter case is for utilities 285 which need to avoid overwriting input files 286 with output files. 287 288.. function:: Filename.__str__() 289 290 Returns the raw string of the actual filename after 291 being normalized. 292 293.. function:: Filename.__unicode__() 294 295 Returns a Unicode string of the filename after being decoded 296 through :attr:`FS_ENCODING`. 297 298.. function:: Filename.__eq__(filename) 299 300 Filename objects which exist on disk hash and compare equally 301 if their device ID and inode number values match 302 (the ``st_dev`` and ``st_ino`` fields according to stat(2)). 303 Filename objects which don't exist on disk hash and compare 304 equally if their filename string matches. 305 306.. function:: Filename.open(mode) 307 308 Returns a file object of this filename opened with the given mode. 309 310.. function:: Filename.disk_file() 311 312 Returns ``True`` if the file currently exists on disk. 313 314.. function:: Filename.dirname() 315 316 Returns the directory name of this filename as a new 317 :class:`Filename` object. 318 319.. function:: Filename.basename() 320 321 Returns the base name (no directory) of this filename as a new 322 :class:`Filename` object. 323 324.. function:: Filename.expanduser() 325 326 Returns a new :class:`Filename` object with the user directory 327 expanded, if any. 328 329AudioFile Objects 330----------------- 331 332.. class:: AudioFile() 333 334 The :class:`AudioFile` class represents an audio file on disk, 335 such as a FLAC file, MP3 file, WAVE file and so forth. 336 It is not meant to be instantiated directly. Instead, functions 337 such as :func:`open` will return :class:`AudioFile`-compatible 338 objects with the following attributes and methods. 339 340.. attribute:: AudioFile.NAME 341 342 The name of the format as a string. 343 This is how the format is referenced by utilities via the `-t` option, 344 and must be unique among all formats. 345 346.. attribute:: AudioFile.SUFFIX 347 348 The default file suffix as a string. 349 This is used by the ``%(suffix)s`` format field in the 350 :meth:`track_name` classmethod, and by the :func:`filename_to_type` 351 function for inferring the file format from its name. 352 However, it need not be unique among all formats. 353 354.. attribute:: AudioFile.DESCRIPTION 355 356 A longer, descriptive name for the audio type as a Unicode string. 357 This is meant to be human-readable. 358 359.. attribute:: AudioFile.COMPRESSION_MODES 360 361 A tuple of valid compression level strings, for use with the 362 :meth:`from_pcm` and :meth:`convert` methods. 363 If the format has no compression levels, this tuple will be empty. 364 365.. attribute:: AudioFile.DEFAULT_COMPRESSION 366 367 A string of the default compression level to use 368 with :meth:`from_pcm` and :meth:`convert`, if none is given. 369 This is *not* the default compression indicated in the user's 370 configuration file; it is a hard-coded value of last resort. 371 372.. attribute:: AudioFile.COMPRESSION_DESCRIPTIONS 373 374 A dict of compression descriptions, as Unicode strings. 375 The key is a valid compression mode string. 376 Not all compression modes need have a description; 377 some may be left blank. 378 379.. attribute:: AudioFile.BINARIES 380 381 A tuple of binary strings required by the format. 382 For example, the Vorbis format may require ``"oggenc"`` and ``"oggdec"`` 383 in order to be available for the user. 384 385.. attribute:: AudioFile.REPLAYGAIN_BINARIES 386 387 A tuple of binary strings required for ReplayGain application. 388 For example, the Vorbis format may require ``"vorbisgain"`` in 389 order to use the :meth:`add_replay_gain` classmethod. 390 This tuple may be empty if the format requires no binaries 391 or has no ReplayGain support. 392 393.. method:: AudioFile.bits_per_sample() 394 395 Returns the number of bits-per-sample in this audio file as a positive 396 integer. 397 398.. method:: AudioFile.channels() 399 400 Returns the number of channels in this audio file as a positive integer. 401 402.. method:: AudioFile.channel_mask() 403 404 Returns a :class:`ChannelMask` object representing the channel assignment 405 of this audio file. 406 If the channel assignment is unknown or undefined, that :class:`ChannelMask` 407 object may have an undefined value. 408 409.. method:: AudioFile.sample_rate() 410 411 Returns the sample rate of this audio file, in Hz, as a positive integer. 412 413.. method:: AudioFile.total_frames() 414 415 Returns the total number of PCM frames in this audio file, 416 as a non-negative integer. 417 418.. method:: AudioFile.cd_frames() 419 420 Returns the total number of CD frames in this audio file, 421 as a non-negative integer. 422 Each CD frame is 1/75th of a second. 423 424.. method:: AudioFile.seconds_length() 425 426 Returns the length of this audio file as a :class:`fractions.Fraction` 427 number of seconds. 428 429.. method:: AudioFile.lossless() 430 431 Returns ``True`` if the data in the audio file has been stored losslessly. 432 Returns ``False`` if not. 433 434.. classmethod:: AudioFile.supports_metadata() 435 436 Returns ``True`` is this audio type supports metadata. 437 If not, :meth:`AudioFile.get_metadata` will always return 438 ``None`` and the metadata updating routines will do nothing. 439 440.. method:: AudioFile.set_metadata(metadata) 441 442 Takes a :class:`MetaData` object and sets this audio file's 443 metadata to that value, if possible. 444 Setting metadata to ``None`` is the same as calling 445 :meth:`AudioFile.delete_metadata`. 446 Raises :exc:`IOError` if a problem occurs when writing the file. 447 448.. method:: AudioFile.update_metadata(metadata) 449 450 Takes the :class:`MetaData`-compatible object returned by this 451 audio file's :meth:`AudioFile.get_metadata` method 452 and sets this audiofile's metadata to that value, if possible. 453 Raises :exc:`IOError` if a problem occurs when writing the file. 454 455.. note:: 456 457 What's the difference between :meth:`AudioFile.set_metadata` 458 and :meth:`AudioFile.update_metadata`? 459 460 Metadata implementations may also contain side information 461 such as track length, file encoder, and so forth. 462 :meth:`AudioFile.set_metadata` presumes the :class:`MetaData` 463 object is from a different :class:`AudioFile` object or has 464 been built from scratch. 465 Therefore, it will update the newly added 466 metadata side info as needed so as to not break the file. 467 468 :meth:`AudioFile.update_metadata` presumes the :class:`MetaData` 469 object is either taken from the original :class:`AudioFile` object 470 or has been carefully constructed to not break anything when 471 applied to the file. 472 It is a lower-level routine which does *not* update metadata side info 473 (which may be necessary when modifying that side info is required). 474 475.. method:: AudioFile.get_metadata() 476 477 Returns a :class:`MetaData`-compatible object representing this 478 audio file's metadata, or ``None`` if this file contains no 479 metadata. 480 Raises :exc:`IOError` if a problem occurs when reading the file. 481 482.. method:: AudioFile.delete_metadata() 483 484 Deletes the audio file's metadata, removing or unsetting tags 485 as necessary. 486 Raises :exc:`IOError` if a problem occurs when writing the file. 487 488.. method:: AudioFile.to_pcm() 489 490 Returns this audio file's PCM data as a :class:`PCMReader`-compatible 491 object. 492 May return a :class:`PCMReaderError` if an error occurs 493 initializing the decoder. 494 495.. classmethod:: AudioFile.from_pcm(filename, pcmreader[, compression][, total_pcm_frames]) 496 497 Takes a filename string, :class:`PCMReader`-compatible object, 498 optional compression level string and optional total_pcm_frames integer. 499 Creates a new audio file as the same format as this audio class 500 and returns a new :class:`AudioFile`-compatible object. 501 The :meth:`PCMReader.close` method is called once encoding is complete. 502 503 Raises :exc:`EncodingError` if a problem occurs during encoding. 504 505 Specifying the total number of PCM frames to be encoded, 506 when the number is known in advance, may allow the encoder 507 to work more efficiently but is never required. 508 509 In this example, we'll transcode ``track.flac`` to ``track.mp3`` 510 at the default compression level: 511 512 >>> audiotools.MP3Audio.from_pcm("track.mp3", 513 ... audiotools.open("track.flac").to_pcm()) 514 515.. method:: AudioFile.convert(filename, target_class[, compression[, progress]]) 516 517 Takes a filename string, :class:`AudioFile` subclass 518 and optional compression level string. 519 Creates a new audio file and returns an object of the same class. 520 Raises :exc:`EncodingError` if a problem occurs during encoding. 521 522 In this example, we'll transcode ``track.flac`` to ``track.mp3`` 523 at the default compression level: 524 525 >>> audiotools.open("track.flac").convert("track.mp3", 526 ... audiotools.MP3Audio) 527 528 Why have both a ``convert`` method as well as ``to_pcm``/``from_pcm`` 529 methods? 530 Although the former is often implemented using the latter, 531 the pcm methods alone contain only raw audio data. 532 By comparison, the ``convert`` method has information about 533 what is the file is being converted to and can transfer other side data 534 if necessary. 535 536 For example, if .wav file with non-audio RIFF chunks is 537 converted to WavPack, this method will preserve those chunks: 538 539 >>> audiotools.open("chunks.wav").convert("chunks.wv", 540 ... audiotools.WavPackAudio) 541 542 whereas the ``to_pcm``/``from_pcm`` method alone will not. 543 544 The optional ``progress`` argument is a function which takes 545 two integer arguments: ``amount_processed`` and ``total_amount``. 546 If supplied, this function is called at regular intervals 547 during the conversion process and may be used to indicate 548 the current status to the user. 549 Note that these numbers are only meaningful when compared 550 to one another; ``amount`` may represent PCM frames, bytes 551 or anything else. 552 The only restriction is that ``total_amount`` will remain 553 static during processing and ``amount_processed`` will 554 progress from 0 to ``total_amount``. 555 556 >>> def print_progress(x, y): 557 ... print "%d%%" % (x * 100 / y) 558 ... 559 >>> audiotools.open("track.flac").convert("track.wv", 560 ... audiotools.WavPackAudio, 561 ... progress=print_progress) 562 563.. method:: AudioFile.seekable() 564 565 Returns ``True`` if the file is seekable. 566 That is, if its :class:`PCMReader` has a .seek() method 567 and that method supports some fine-grained seeking 568 when the PCMReader is working from on-disk files. 569 570.. method:: AudioFile.verify([progress]) 571 572 Verifies the track for correctness. 573 Returns ``True`` if verification is successful. 574 Raises an :class:`InvalidFile` subclass if some problem is detected. 575 If the file has built-in checksums or other error detection 576 capabilities, this method checks those values to ensure it has not 577 been damaged in some way. 578 579 The optional ``progress`` argument functions identically 580 to the one provided to :meth:`convert`. 581 That is, it takes a two integer argument function which is called 582 at regular intervals to indicate the status of verification. 583 584.. classmethod:: AudioFile.track_name(file_path[, track_metadata[, format[, suffix]]]) 585 586 Given a file path string, optional :class:`MetaData`-compatible object, 587 optional Python format string, and optional suffix string, 588 returns a filename string with the format string fields filled-in. 589 Raises :exc:`UnsupportedTracknameField` if the format string contains 590 unsupported fields. 591 592 Currently supported fields are: 593 594 ========================== =============================================== 595 Field Value 596 -------------------------- ----------------------------------------------- 597 ``%(album_name)s`` ``track_metadata.album_name`` 598 ``%(album_number)s`` ``track_metadata.album_number`` 599 ``%(album_total)s`` ``track_metadata.album_total`` 600 ``%(album_track_number)s`` ``album_number`` combined with ``track_number`` 601 ``%(artist_name)s`` ``track_metadata.artist_name`` 602 ``%(catalog)s`` ``track_metadata.catalog`` 603 ``%(comment)s`` ``track_metadata.comment`` 604 ``%(composer_name)s`` ``track_metadata.composer_name`` 605 ``%(conductor_name)s`` ``track_metadata.conductor_name`` 606 ``%(copyright)s`` ``track_metadata.copyright`` 607 ``%(date)s`` ``track_metadata.date`` 608 ``%(ISRC)s`` ``track_metadata.ISRC`` 609 ``%(media)s`` ``track_metadata.year`` 610 ``%(performer_name)s`` ``track_metadata.performer_name`` 611 ``%(publisher)s`` ``track_metadata.publisher`` 612 ``%(suffix)s`` the :class:`AudioFile` suffix 613 ``%(track_name)s`` ``track_metadata.track_name`` 614 ``%(track_number)2.2d`` ``track_metadata.track_number`` 615 ``%(track_total)s`` ``track_metadata.track_total`` 616 ``%(year)s`` ``track_metadata.year`` 617 ``%(basename)s`` ``file_path`` basename without suffix 618 ========================== =============================================== 619 620.. classmethod:: AudioFile.supports_replay_gain() 621 622 Returns ``True`` if this class supports ReplayGain metadata. 623 624.. method:: AudioFile.get_replay_gain() 625 626 Returns this audio file's ReplayGain values as a 627 :class:`ReplayGain` object, or ``None`` if this audio file has no values. 628 629.. method:: AudioFile.set_replay_gain(replaygain) 630 631 Given a :class:`ReplayGain` object, sets the audio file's gain values. 632 633 Raises :exc:`IOError` if unable to modify the file. 634 635.. method:: AudioFile.delete_replay_gain() 636 637 Removes any gain values from the file. 638 639 Raises :exc:`IOError` if unable to modify the file. 640 641.. classmethod:: AudioFile.supports_cuesheet() 642 643 Returns ``True`` if the audio format supports embedded 644 :class:`Sheet` objects. 645 646.. method:: AudioFile.set_cuesheet(cuesheet) 647 648 Given a :class:`Sheet` object, embeds a cuesheet in the track. 649 This is for tracks which represent a whole CD image 650 and wish to store track break data internally. 651 May raise :exc:`IOError` if an error occurs writing the file. 652 653.. method:: AudioFile.get_cuesheet() 654 655 Returns a :class:`Sheet` object of a track's embedded cuesheet, 656 or ``None`` if the track contains no cuesheet. 657 May raise :exc:`IOError` if an error occurs reading the file. 658 659.. method:: AudioFile.delete_cuesheet() 660 661 Deletes embedded :class:`Sheet` object, if any. 662 May raise :exc:`IOError` if an error occurs updating the file. 663 664.. method:: AudioFile.clean([output_filename]) 665 666 Cleans the audio file of known data and metadata problems. 667 668 ``output_filename`` is an optional string in which the fixed 669 audio file is placed. 670 If omitted, no actual fixes are performed. 671 Note that this method never modifies the original file. 672 673 Returns list of fixes performed as Unicode strings. 674 675 Raises :exc:`IOError` if some error occurs when writing the new file. 676 Raises :exc:`ValueError` if the file itself is invalid. 677 678.. classmethod:: AudioFile.available(system_binaries) 679 680 Takes the :attr:`audiotools.BIN` object of system binaries. 681 Returns ``True`` if all the binaries necessary to implement 682 this :class:`AudioFile`-compatible class are present and executable. 683 Returns ``False`` if not. 684 685.. classmethod:: AudioFile.missing_components(messenger) 686 687 Takes a :class:`Messenger` object and displays missing binaries 688 or libraries needed to support this format and where to get them, 689 if any. 690 691WaveContainer Objects 692^^^^^^^^^^^^^^^^^^^^^ 693 694This is an abstract :class:`AudioFile` subclass suitable 695for extending by formats that store RIFF WAVE chunks internally, 696such as Wave, FLAC, WavPack and Shorten. 697It overrides the :meth:`AudioFile.convert` method such that 698any stored chunks are transferred properly from one file to the next. 699This is accomplished by implementing three additional methods. 700 701.. class:: WaveContainer 702 703.. method:: WaveContainer.has_foreign_wave_chunks() 704 705 Returns ``True`` if our object has non-audio RIFF WAVE chunks. 706 707.. method:: WaveContainer.wave_header_footer() 708 709 Returns ``(header, footer)`` tuple of strings 710 where ``header`` is everything before the PCM data 711 and ``footer`` is everything after the PCM data. 712 713 May raise :exc:`ValueError` if there's a problem 714 with the header or footer data, such as invalid chunk IDs. 715 May raise :exc:`IOError` if there's a problem 716 reading the header or footer data from the file. 717 718.. classmethod:: WaveContainer.from_wave(filename, header, pcmreader, footer[, compression]) 719 720 Encodes a new file from wave data. 721 ``header`` and ``footer`` are binary strings as returned by a 722 :meth:`WaveContainer.wave_header_footer` method, 723 ``pcmreader`` is a :class:`PCMReader` object 724 and ``compression`` is a binary string. 725 726 Returns a new :class:`AudioFile`-compatible object 727 or raises :exc:`EncodingError` if some error occurs when 728 encoding the file. 729 730AiffContainer Objects 731^^^^^^^^^^^^^^^^^^^^^ 732 733Much like :class:`WaveContainer`, this is an abstract 734:class:`AudioFile` subclass suitable 735for extending by formats that store AIFF chunks internally, 736such as AIFF, FLAC and Shorten. 737It overrides the :meth:`AudioFile.convert` method such that 738any stored chunks are transferred properly from one file to the next. 739This is accomplished by implementing three additional methods. 740 741.. class:: AiffContainer 742 743.. method:: AiffContainer.has_foreign_aiff_chunks() 744 745 Returns ``True`` if our object has non-audio AIFF chunks. 746 747.. method:: AiffContainer.aiff_header_footer() 748 749 Returns ``(header, footer)`` tuple of strings 750 where ``header`` is everything before the PCM data 751 and ``footer`` is everything after the PCM data. 752 753 May raise :exc:`ValueError` if there's a problem 754 with the header or footer data, such as invalid chunk IDs. 755 May raise :exc:`IOError` if there's a problem 756 reading the header or footer data from the file. 757 758.. classmethod:: AiffContainer.from_aiff(filename, header, pcmreader, footer[, compression]) 759 760 Encodes a new file from wave data. 761 ``header`` and ``footer`` are binary strings as returned by a 762 :meth:`AiffContainer.aiff_header_footer` method, 763 ``pcmreader`` is a :class:`PCMReader` object 764 and ``compression`` is a binary string. 765 766 Returns a new :class:`AudioFile`-compatible object 767 or raises :exc:`EncodingError` if some error occurs when 768 encoding the file. 769 770MetaData Objects 771---------------- 772 773.. class:: MetaData([track_name][, track_number][, track_total][, album_name][, artist_name][, performer_name][, composer_name][, conductor_name][, media][, ISRC][, catalog][, copyright][, publisher][, year][, data][, album_number][, album_total][, comment][, images]) 774 775 The :class:`MetaData` class represents an :class:`AudioFile`'s 776 non-technical metadata. 777 It can be instantiated directly for use by the :meth:`set_metadata` 778 method. 779 However, the :meth:`get_metadata` method will typically return 780 :class:`MetaData`-compatible objects corresponding to the audio file's 781 low-level metadata implementation rather than actual :class:`MetaData` 782 objects. 783 Modifying fields within a :class:`MetaData`-compatible object 784 will modify its underlying representation and those changes 785 will take effect should :meth:`set_metadata` be called with 786 that updated object. 787 788 The ``images`` argument, if given, should be an iterable collection 789 of :class:`Image`-compatible objects. 790 791 MetaData attributes may be ``None``, 792 which indicates the low-level implementation has 793 no corresponding entry. 794 For instance, ID3v2.3 tags use the ``"TALB"`` frame 795 to indicate the track's album name. 796 If that frame is present, an :class:`audiotools.ID3v23Comment` 797 MetaData object will have an ``album_name`` field containing 798 a Unicode string of its value. 799 If that frame is not present in the ID3v2.3 tag, 800 its ``album_name`` field will be ``None``. 801 802 For example, to access a track's album name field: 803 804 >>> metadata = track.get_metadata() 805 >>> metadata.album_name 806 u"Album Name" 807 808 To change a track's album name field: 809 810 >>> metadata = track.get_metadata() 811 >>> metadata.album_name = u"Updated Album Name" 812 >>> track.update_metadata(metadata) # because metadata comes from track's get_metadata() method, one can use update_metadata() 813 814 To delete a track's album name field: 815 816 >>> metadata = track.get_metadata() 817 >>> del(metadata.album_name) 818 >>> track.update_metadata(metadata) 819 820 Or to replace a track's entire set of metadata: 821 822 >>> metadata = MetaData(track_name=u"Track Name", 823 ... album_name=u"Updated Album Name", 824 ... track_number=1, 825 ... track_total=3) 826 >>> track.set_metadata(metadata) # because metadata is built from scratch, one must use set_metadata() 827 828.. data:: MetaData.track_name 829 830 This individual track's name as a Unicode string. 831 832.. data:: MetaData.track_number 833 834 This track's number within the album as an integer. 835 836.. data:: MetaData.track_total 837 838 The total number of tracks on the album as an integer. 839 840.. data:: MetaData.album_name 841 842 The name of this track's album as a Unicode string. 843 844.. data:: MetaData.artist_name 845 846 The name of this track's original creator/composer as a Unicode string. 847 848.. data:: MetaData.performer_name 849 850 The name of this track's performing artist as a Unicode string. 851 852.. data:: MetaData.composer_name 853 854 The name of this track's composer as a Unicode string. 855 856.. data:: MetaData.conductor_name 857 858 The name of this track's conductor as a Unicode string. 859 860.. data:: MetaData.media 861 862 The album's media type, such as u"CD", u"tape", u"LP", etc. 863 as a Unicode string. 864 865.. data:: MetaData.ISRC 866 867 This track's ISRC value as a Unicode string. 868 869.. data:: MetaData.catalog 870 871 This track's album catalog number as a Unicode string. 872 873.. data:: MetaData.year 874 875 This track's album release year as a Unicode string. 876 877.. data:: MetaData.date 878 879 This track's album recording date as a Unicode string. 880 881.. data:: MetaData.album_number 882 883 This track's album number if it is one of a series of albums, 884 as an integer. 885 886.. data:: MetaData.album_total 887 888 The total number of albums within the set, as an integer. 889 890.. data:: MetaData.comment 891 892 This track's comment as a Unicode string. 893 894.. method:: MetaData.fields() 895 896 Yields an ``(attr, value)`` tuple per :class:`MetaData` field. 897 898.. method:: MetaData.filled_fields() 899 900 Yields an ``(attr, value)`` tuple per non-blank :class:`MetaData` field. 901 Non-blank fields are those with a value other than ``None``. 902 903.. method:: MetaData.empty_fields() 904 905 Yields an ``(attr, value)`` tuple per blank :class:`MetaData` field. 906 Blank fields are those with a value of ``None``. 907 908.. classmethod:: MetaData.converted(metadata) 909 910 Takes a :class:`MetaData`-compatible object (or ``None``) 911 and returns a new :class:`MetaData` object of the same class, or ``None``. 912 For instance, ``VorbisComment.converted()`` returns ``VorbisComment`` 913 objects. 914 The purpose of this classmethod is to offload metadata conversion 915 to the metadata classes themselves. 916 Therefore, by using the ``VorbisComment.converted()`` classmethod, 917 the ``VorbisAudio`` class only needs to know how to handle 918 ``VorbisComment`` metadata. 919 920 Why not simply handle all metadata using this high-level representation 921 and avoid conversion altogether? 922 The reason is that :class:`MetaData` is often only a subset of 923 what the low-level implementation can support. 924 For example, a ``VorbisComment`` may contain the ``'FOO'`` tag 925 which has no analogue in :class:`MetaData`'s list of fields. 926 But when passed through the ``VorbisComment.converted()`` classmethod, 927 that ``'FOO'`` tag will be preserved as one would expect. 928 929 The key is that performing: 930 931 >>> track.set_metadata(track.get_metadata()) 932 933 should always round-trip properly and not lose any metadata values. 934 935.. classmethod:: MetaData.supports_images() 936 937 Returns ``True`` if this :class:`MetaData` implementation supports images. 938 Returns ``False`` if not. 939 940.. method:: MetaData.images() 941 942 Returns a list of :class:`Image`-compatible objects this metadata contains. 943 944.. method:: MetaData.front_covers() 945 946 Returns a subset of :meth:`images` which are marked as front covers. 947 948.. method:: MetaData.back_covers() 949 950 Returns a subset of :meth:`images` which are marked as back covers. 951 952.. method:: MetaData.leaflet_pages() 953 954 Returns a subset of :meth:`images` which are marked as leaflet pages. 955 956.. method:: MetaData.media_images() 957 958 Returns a subset of :meth:`images` which are marked as media. 959 960.. method:: MetaData.other_images() 961 962 Returns a subset of :meth:`images` which are marked as other. 963 964.. method:: MetaData.add_image(image) 965 966 Takes a :class:`Image`-compatible object and adds it to this 967 metadata's list of images. 968 969.. method:: MetaData.delete_image(image) 970 971 Takes an :class:`Image` from this class, as returned by :meth:`images`, 972 and removes it from this metadata's list of images. 973 974.. method:: MetaData.clean() 975 976 Returns a (:class:`MetaData`, ``fixes_performed``) tuple 977 where ``MetaData`` is an object that's been cleaned of problems 978 and ``fixes_performed`` is a list of unicode strings detailing 979 those problems. 980 Problems include: 981 982 * Leading whitespace in text fields 983 * Trailing whitespace in text fields 984 * Empty fields 985 * Leading zeroes in numerical fields 986 * Incorrectly labeled image metadata fields 987 988.. method:: MetaData.raw_info() 989 990 Returns a Unicode string of raw metadata information 991 with as little filtering as possible. 992 This is meant to be useful for debugging purposes. 993 994Image Objects 995------------- 996 997.. class:: Image(data, mime_type, width, height, color_depth, color_count, description, type) 998 999 This class is a container for image data. 1000 1001.. data:: Image.data 1002 1003 A plain string of raw image bytes. 1004 1005.. data:: Image.mime_type 1006 1007 A Unicode string of this image's MIME type, such as u'image/jpeg' 1008 1009.. data:: Image.width 1010 1011 This image's width in pixels as an integer. 1012 1013.. data:: Image.height 1014 1015 This image's height in pixels as an integer 1016 1017.. data:: Image.color_depth 1018 1019 This image's color depth in bits as an integer. 1020 24 for JPEG, 8 for GIF, etc. 1021 1022.. data:: Image.color_count 1023 1024 For palette-based images, this is the number of colors the image contains 1025 as an integer. 1026 For non-palette images, this value is 0. 1027 1028.. data:: Image.description 1029 1030 A Unicode string of this image's description. 1031 1032.. data:: Image.type 1033 1034 An integer representing this image's type. 1035 1036 ===== ============ 1037 Value Type 1038 ----- ------------ 1039 0 front cover 1040 1 back cover 1041 2 leaflet page 1042 3 media 1043 4 other 1044 ===== ============ 1045 1046.. method:: Image.suffix() 1047 1048 Returns this image's typical filename suffix as a plain string. 1049 For example, JPEGs return ``"jpg"`` 1050 1051.. method:: Image.type_string() 1052 1053 Returns this image's type as a plain string. 1054 For example, an image of type 0 returns ``"Front Cover"`` 1055 1056.. classmethod:: Image.new(image_data, description, type) 1057 1058 Given a string of raw image bytes, a Unicode description string 1059 and image type integer, returns an :class:`Image`-compatible object. 1060 Raises :exc:`InvalidImage` If unable to determine the 1061 image type from the data string. 1062 1063ReplayGain Objects 1064------------------ 1065 1066.. class:: ReplayGain(track_gain, track_peak, album_gain, album_peak) 1067 1068 This is a simple container for ReplayGain values. 1069 1070.. data:: ReplayGain.track_gain 1071 1072 A float of a track's ReplayGain value. 1073 1074.. data:: ReplayGain.track_peak 1075 1076 A float of a track's peak value, from 0.0 to 1.0 1077 1078.. data:: ReplayGain.album_gain 1079 1080 A float of an album's ReplayGain value. 1081 1082.. data:: ReplayGain.album_peak 1083 1084 A float of an album's peak value, from 0.0 to 1.0 1085 1086PCMReader Objects 1087----------------- 1088 1089.. class:: PCMReader(sample_rate, channels, channel_mask, bits_per_sample) 1090 1091 This is an abstract base class for streams of audio data 1092 which are file-like objects with additional stream parameters. 1093 Subclasses are expected to implement ``read`` and ``close``. 1094 1095.. data:: PCMReader.sample_rate 1096 1097 The sample rate of this audio stream, in Hz, as a positive integer. 1098 1099.. data:: PCMReader.channels 1100 1101 The number of channels in this audio stream as a positive integer. 1102 1103.. data:: PCMReader.channel_mask 1104 1105 The channel mask of this audio stream as a non-negative integer. 1106 1107.. data:: PCMReader.bits_per_sample 1108 1109 The number of bits-per-sample in this audio stream as a positive integer. 1110 1111.. method:: PCMReader.read(pcm_frames) 1112 1113 Try to read a :class:`pcm.FrameList` object with the given 1114 number of PCM frames, if possible. 1115 This method is *not* guaranteed to read that amount of frames. 1116 It may return less, particularly at the end of an audio stream. 1117 It may even return FrameLists larger than requested. 1118 However, it must always return a non-empty FrameList until the 1119 end of the PCM stream is reached. 1120 1121 Once the end of the stream is reached, subsequent calls 1122 will return empty FrameLists. 1123 1124 May raise :exc:`IOError` if there is a problem reading the 1125 source file, or :exc:`ValueError` if the source file has 1126 some sort of error. 1127 1128.. method:: PCMReader.close() 1129 1130 Closes the audio stream. 1131 If any subprocesses were used for audio decoding, they will also be 1132 closed and waited for their process to finish. 1133 1134 Subsequent calls to :meth:`PCMReader.read` will 1135 raise :exc:`ValueError` exceptions once the stream is closed. 1136 1137.. method:: PCMReader.__enter__() 1138 1139 Returns the PCMReader. 1140 This is used for implementing context management. 1141 1142.. method:: PCMReader.__exit__(exc_type, exc_value, traceback) 1143 1144 Calls :meth:`PCMReader.close`. 1145 This is used for implementing context management. 1146 1147PCMFileReader Objects 1148^^^^^^^^^^^^^^^^^^^^^ 1149 1150.. class:: PCMFileReader(file, sample_rate, channels, channel_mask, bits_per_sample[, process[, signed[, big_endian]]]) 1151 1152 This class wraps around file-like objects and generates 1153 :class:`pcm.FrameList` objects on each call to :meth:`read`. 1154 ``sample_rate``, ``channels``, ``channel_mask`` and ``bits_per_sample`` 1155 should be integers. 1156 ``process`` is a subprocess helper object which generates PCM data. 1157 ``signed`` is ``True`` if the generated PCM data is signed. 1158 ``big_endian`` is ``True`` if the generated PCM data is big-endian. 1159 1160PCMReaderError Objects 1161^^^^^^^^^^^^^^^^^^^^^^ 1162 1163.. class:: PCMReaderError(error_message, sample_rate, channels, channel_mask, bits_per_sample) 1164 1165 This is a subclass of :class:`PCMReader` which always returns empty 1166 always raises a :class:`ValueError` when its read method is called. 1167 The purpose of this is to postpone error generation so that 1168 all encoding errors, even those caused by unsuccessful decoding, 1169 are restricted to the :meth:`from_pcm` classmethod 1170 which can then propagate an :class:`EncodingError` error message 1171 to the user. 1172 1173PCMConverter Objects 1174^^^^^^^^^^^^^^^^^^^^ 1175 1176.. class:: PCMConverter(pcmreader, sample_rate, channels, channel_mask, bits_per_sample) 1177 1178 This class takes an existing :class:`PCMReader`-compatible object 1179 along with a new set of ``sample_rate``, ``channels``, 1180 ``channel_mask`` and ``bits_per_sample`` values. 1181 Data from ``pcmreader`` is then automatically converted to 1182 the same format as those values. 1183 1184.. data:: PCMConverter.sample_rate 1185 1186 If the new sample rate differs from ``pcmreader``'s sample rate, 1187 audio data is automatically resampled on each call to :meth:`read`. 1188 1189.. data:: PCMConverter.channels 1190 1191 If the new number of channels is smaller than ``pcmreader``'s channel 1192 count, existing channels are removed or downmixed as necessary. 1193 If the new number of channels is larger, data from the first channel 1194 is duplicated as necessary to fill the rest. 1195 1196.. data:: PCMConverter.channel_mask 1197 1198 If the new channel mask differs from ``pcmreader``'s channel mask, 1199 channels are removed as necessary such that the proper channel 1200 only outputs to the proper speaker. 1201 1202.. data:: PCMConverter.bits_per_sample 1203 1204 If the new bits-per-sample differs from ``pcmreader``'s 1205 number of bits-per-sample, samples are shrunk or enlarged 1206 as necessary to cover the full amount of bits. 1207 1208.. method:: PCMConverter.read 1209 1210 This method functions the same as the :meth:`PCMReader.read` method. 1211 1212.. method:: PCMConverter.close 1213 1214 This method functions the same as the :meth:`PCMReader.close` method. 1215 1216BufferedPCMReader Objects 1217^^^^^^^^^^^^^^^^^^^^^^^^^ 1218 1219.. class:: BufferedPCMReader(pcmreader) 1220 1221 This class wraps around an existing :class:`PCMReader` object. 1222 Its calls to :meth:`read` are guaranteed to return 1223 :class:`pcm.FrameList` objects as close to the requested amount 1224 of PCM frames as possible without going over by buffering data 1225 internally. 1226 1227 The reason such behavior is not required is that we often 1228 don't care about the size of the individual FrameLists being 1229 passed from one routine to another. 1230 But on occasions when we need :class:`pcm.FrameList` objects 1231 to be of a particular size, this class can accomplish that. 1232 1233CounterPCMReader Objects 1234^^^^^^^^^^^^^^^^^^^^^^^^ 1235 1236.. class:: CounterPCMReader(pcmreader) 1237 1238 This class wraps around an existing :class:`PCMReader` object 1239 and keeps track of the number of bytes and frames written 1240 upon each call to ``read``. 1241 1242.. attribute:: CounterPCMReader.frames_written 1243 1244 The number of PCM frames written thus far. 1245 1246.. method:: CounterPCMReader.bytes_written() 1247 1248 The number of bytes written thus far. 1249 1250ReorderedPCMReader Objects 1251^^^^^^^^^^^^^^^^^^^^^^^^^^ 1252 1253.. class:: ReorderedPCMReader(pcmreader, channel_order) 1254 1255 This class wraps around an existing :class:`PCMReader` object. 1256 It takes a list of channel number integers 1257 (which should be the same as ``pcmreader``'s channel count) 1258 and reorders channels upon each call to :meth:`read`. 1259 1260 For example, to swap channels 0 and 1 in a stereo stream, 1261 one could do the following: 1262 1263 >>> reordered = ReorderedPCMReader(original, [1, 0]) 1264 1265 Calls to ``reordered.read()`` will then have the left channel 1266 on the right side and vice versa. 1267 1268PCMCat Objects 1269^^^^^^^^^^^^^^ 1270 1271.. class:: PCMCat(pcmreaders) 1272 1273 This class wraps around a list of :class:`PCMReader` objects 1274 and concatenates their output into a single output stream. 1275 1276 If any of the readers has different attributes 1277 from the first reader in the stream, :exc:`ValueError` is raised 1278 at init-time. 1279 1280PCMReaderWindow Objects 1281^^^^^^^^^^^^^^^^^^^^^^^ 1282 1283.. class:: PCMReaderWindow(pcmreader, initial_offset, total_pcm_frames, [forward_close=True]) 1284 1285 This class wraps around an existing :class:`PCMReader` object 1286 and truncates or extends its samples as needed. 1287 ``initial_offset``, if positive, indicates how many 1288 PCM frames to truncate from the beginning of the stream. 1289 If negative, the beginning of the stream is padded by 1290 that many PCM frames - all of which have a value of 0. 1291 ``total_pcm_frames`` indicates the total length of the stream 1292 as a non-negative number of PCM frames. 1293 If shorter than the actual length of the PCM reader's stream, 1294 the reader is truncated. 1295 If longer, the stream is extended by as many PCM frames as needed. 1296 Again, padding frames have a value of 0. 1297 1298 If ``forward_close`` is True, calls to :meth:`PCMReaderWindow.close` 1299 are passed along to the wrapped :class:`PCMReader` object. 1300 Otherwise, the close is confined to the :class:`PCMReaderWindow` 1301 object. 1302 This may be necessary when encoding sub-streams from a larger 1303 stream in which closing the larger stream after each encode 1304 isn't desirable. 1305 1306LimitedPCMReader Objects 1307^^^^^^^^^^^^^^^^^^^^^^^^ 1308 1309.. class:: LimitedPCMReader(buffered_pcmreader, total_pcm_frames) 1310 1311 This class wraps around an existing :class:`BufferedPCMReader` 1312 and ensures that no more than ``total_pcm_frames`` will be read 1313 from that stream by limiting reads to it. 1314 1315.. note:: 1316 1317 :class:`PCMReaderWindow` is designed primarily for handling 1318 sample offset values in a :class:`CDTrackReader`, 1319 or for skipping a potentially large number of samples 1320 in a stream. 1321 :class:`LimitedPCMReader` is designed for splitting a 1322 stream into several smaller streams without losing any PCM frames. 1323 1324 Which to use for a given situation depends on whether one cares 1325 about consuming the samples outside of the sub-reader or not. 1326 1327PCMReaderProgress Objects 1328^^^^^^^^^^^^^^^^^^^^^^^^^ 1329 1330.. class:: PCMReaderProgress(pcmreader, total_frames, progress) 1331 1332 This class wraps around an existing :class:`PCMReader` object 1333 and generates periodic updates to a given ``progress`` function. 1334 ``total_frames`` indicates the total number of PCM frames 1335 in the PCM stream. 1336 1337 >>> progress_display = SingleProgressDisplay(Messenger("audiotools"), u"encoding file") 1338 >>> pcmreader = source_audiofile.to_pcm() 1339 >>> source_frames = source_audiofile.total_frames() 1340 >>> target_audiofile = AudioType.from_pcm("target_filename", 1341 ... PCMReaderProgress(pcmreader, 1342 ... source_frames, 1343 ... progress_display.update)) 1344 1345 1346ReplayGainCalculator Objects 1347---------------------------- 1348 1349.. class:: ReplayGainCalculator(sample_rate) 1350 1351 This class is for incrementally calculating ReplayGain 1352 for an album during decoding. 1353 All tracks calculated must have the same sample rate 1354 which may mean resampling them to that rate if necessary. 1355 1356.. method:: ReplayGainCalculator.to_pcm(pcmreader) 1357 1358 Given a :class:`PCMReader` object, 1359 returns a :class:`ReplayGainCalculatorReader` 1360 linked to this calculator. 1361 1362.. method:: ReplayGainCalculator.__iter__() 1363 1364 Yields ``(title_gain, title_peak, album_gain, album_peak)`` tuples 1365 for each :class:`PCMReader` processed with 1366 :meth:`ReplayGainCalculator.to_pcm` 1367 in the order in which they were processed. 1368 1369ReplayGainCalculatorReader Objects 1370^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1371 1372.. class:: ReplayGainCalculatorReader(replaygain, pcmreader) 1373 1374 These objects are typically returned from 1375 :meth:`ReplayGainCalculator.to_pcm` rather 1376 than instantiated directly. 1377 They function as :class:`PCMReader` objects 1378 which process the :class:`pcm.FrameList` objects 1379 returned by ``read`` prior to returning them. 1380 1381.. method:: ReplayGainCalculatorReader.title_gain() 1382 1383 Returns the title gain of the whole track as a floating point value. 1384 1385.. method:: ReplayGainCalculatorReader.title_peak() 1386 1387 Returns the title peak of the whole track as a floating point value. 1388 1389ChannelMask Objects 1390------------------- 1391 1392.. class:: ChannelMask(mask) 1393 1394 This is an integer-like class that abstracts channel assignments 1395 into a set of bit fields. 1396 1397 ======= ========================= 1398 Mask Speaker 1399 ------- ------------------------- 1400 0x1 ``front_left`` 1401 0x2 ``front_right`` 1402 0x4 ``front_center`` 1403 0x8 ``low_frequency`` 1404 0x10 ``back_left`` 1405 0x20 ``back_right`` 1406 0x40 ``front_left_of_center`` 1407 0x80 ``front_right_of_center`` 1408 0x100 ``back_center`` 1409 0x200 ``side_left`` 1410 0x400 ``side_right`` 1411 0x800 ``top_center`` 1412 0x1000 ``top_front_left`` 1413 0x2000 ``top_front_center`` 1414 0x4000 ``top_front_right`` 1415 0x8000 ``top_back_left`` 1416 0x10000 ``top_back_center`` 1417 0x20000 ``top_back_right`` 1418 ======= ========================= 1419 1420 All channels in a :class:`pcm.FrameList` will be in RIFF WAVE order 1421 as a sensible convention. 1422 But which channel corresponds to which speaker is decided by this mask. 1423 For example, a 4 channel PCMReader with the channel mask ``0x33`` 1424 corresponds to the bits ``00110011`` 1425 1426 Reading those bits from right to left (least significant first) 1427 the ``front_left``, ``front_right``, ``back_left``, ``back_right`` 1428 speakers are set. 1429 Therefore, the PCMReader's 4 channel FrameLists are laid out as follows: 1430 1431 0. ``front_left`` 1432 1. ``front_right`` 1433 2. ``back_left`` 1434 3. ``back_right`` 1435 1436 Since the ``front_center`` and ``low_frequency`` bits are not set, 1437 those channels are skipped in the returned FrameLists. 1438 1439 Many formats store their channels internally in a different order. 1440 Their :class:`PCMReader` objects will be expected to reorder channels 1441 and set a :class:`ChannelMask` matching this convention. 1442 And, their :func:`from_pcm` classmethods will be expected 1443 to reverse the process. 1444 1445 A :class:`ChannelMask` of 0 is "undefined", 1446 which means that channels aren't assigned to *any* speaker. 1447 This is an ugly last resort for handling formats 1448 where multi-channel assignments aren't properly defined. 1449 In this case, a :func:`from_pcm` classmethod is free to assign 1450 the undefined channels any way it likes, and is under no obligation 1451 to keep them undefined when passing back out to :meth:`to_pcm` 1452 1453.. method:: ChannelMask.defined() 1454 1455 Returns ``True`` if this mask is defined. 1456 1457.. method:: ChannelMask.undefined() 1458 1459 Returns ``True`` if this mask is undefined. 1460 1461.. method:: ChannelMask.channels() 1462 1463 Returns the speakers this mask contains as a list of strings 1464 in the order they appear in the PCM stream. 1465 1466.. method:: ChannelMask.index(channel_name) 1467 1468 Given a channel name string, returns the index of that channel 1469 within the PCM stream. 1470 For example: 1471 1472 >>> mask = ChannelMask(0xB) #fL, fR, LFE, but no fC 1473 >>> mask.index("low_frequency") 1474 2 1475 1476.. classmethod:: ChannelMask.from_fields(**fields) 1477 1478 Takes channel names as function arguments and returns a 1479 :class:`ChannelMask` object. 1480 1481 >>> mask = ChannelMask.from_fields(front_right=True, 1482 ... front_left=True, 1483 ... front_center=True) 1484 >>> int(mask) 1485 7 1486 1487.. classmethod:: ChannelMask.from_channels(channel_count) 1488 1489 Takes a channel count integer and returns a :class:`ChannelMask` object. 1490 1491.. warning:: 1492 1493 :func:`from_channels` *only* works for 1 and 2 channel counts 1494 and is meant purely as a convenience method for mono or stereo streams. 1495 All other values will trigger a :exc:`ValueError` 1496 1497CD Lookups 1498^^^^^^^^^^ 1499 1500.. function:: metadata_lookup(musicbrainz_disc_id, freedb_disc_id, [musicbrainz_server], [musicbrainz_port], [freedb_server], [freedb_port], [use_musicbrainz], [use_freedb]) 1501 1502 Given a :class:`audiotools.musicbrainz.DiscID` and 1503 :class:`audiotools.freedb.DiscID`, returns a 1504 ``metadata[c][t]`` list of lists 1505 where ``c`` is a possible choice and ``t`` is the :class:`MetaData` 1506 for a given track (starting from 0). 1507 1508 This will always return a list of :class:`MetaData` objects 1509 for at least one choice. 1510 In the event that no matches for the CD can be found, 1511 those objects will only contain ``track_number`` and ``track_total`` 1512 fields. 1513 1514.. function:: cddareader_metadata_lookup(cddareader, [musicbrainz_server], [musicbrainz_port], [freedb_server], [freedb_port], [use_musicbrainz], [use_freedb]) 1515 1516 Given a :class:`cdio.CDDAReader` object, 1517 returns ``metadata[c][t]`` list of lists 1518 where ``c`` is a possible choice and ``t`` is the :class:`MetaData` 1519 for a given track (starting from 0). 1520 1521 This will always return a list of :class:`MetaData` objects 1522 for at least one choice. 1523 In the event that no matches for the CD can be found, 1524 those objects will only contain ``track_number`` and ``track_total`` 1525 fields. 1526 1527.. function:: track_metadata_lookup(audiofiles, [, musicbrainz_server][, musicbrainz_port][, freedb_server][, freedb_port][, use_musicbrainz][, use_freedb]) 1528 1529 Given a sorted list of :class:`AudioFile` objects, 1530 returns ``metadata[c][t]`` list of lists 1531 where ``c`` is a possible choice and ``t`` is the :class:`MetaData` 1532 for a given track (starting from 0). 1533 1534 This will always return a list of :class:`MetaData` objects 1535 for at least one choice. 1536 In the event that no matches for the CD can be found, 1537 those objects will only contain ``track_number`` and ``track_total`` 1538 fields. 1539 1540.. function:: sheet_metadata_lookup(sheet, total_pcm_frames, sample_rate, [, musicbrainz_server][, musicbrainz_port][, freedb_server][, freedb_port][, use_musicbrainz][, use_freedb]) 1541 1542 Given a :class:`Sheet` object, total number of PCM frames 1543 and the disc's sample rate, 1544 returns ``metadata[c][t]`` list of lists 1545 where ``c`` is a possible choice and ``t`` is the :class:`MetaData` 1546 for a given track (starting from 0). 1547 1548 This will always return a list of :class:`MetaData` objects 1549 for at least one choice. 1550 In the event that no matches for the CD can be found, 1551 those objects will only contain ``track_number`` and ``track_total`` 1552 fields. 1553 1554.. function:: accuraterip_lookup(sorted_tracks[, server][, port]) 1555 1556 Given a list of :class:`AudioFile` objects sorted by 1557 track number, returns a 1558 ``{track_number:[(confidence, checksum, alt), ...], ...}`` 1559 dict of values retrieved from the AccurateRip database 1560 where ``track_number`` is an int starting from 1, 1561 ``confidence`` is the number of people with the same people 1562 with a matching ``checksum`` of the track. 1563 1564 May return a dict of empty lists if no AccurateRip entry is found. 1565 1566 May return :exc:`urllib2.HTTPError` if an error occurs 1567 querying the server. 1568 1569.. function:: accuraterip_sheet_lookup(sheet, total_pcm_frames, sample_rate[, server][, port]) 1570 1571 Given a :class:`Sheet` object, total number of PCM frames and sample rate, 1572 returns a 1573 ``{track_number:[(confidence, checksum, alt), ...], ...}`` 1574 dict of values retrieved from the AccurateRip database 1575 where ``track_number`` is an int starting from 1, 1576 ``confidence`` is the number of people with the same people 1577 with a matching ``checksum`` of the track. 1578 1579 May return a dict of empty lists if no AccurateRip entry is found. 1580 1581 May return :exc:`urllib2.HTTPError` if an error occurs 1582 querying the server. 1583 1584Cuesheets 1585--------- 1586 1587Sheet Objects 1588^^^^^^^^^^^^^ 1589 1590These objects represent a CDDA layout such as provided 1591by a ``.cue`` or ``.toc`` file. 1592This can be used to recreate the exact layout of the disc 1593when burning a set of tracks back to CD. 1594 1595.. class:: Sheet(sheet_tracks, [metadata]) 1596 1597 ``sheet_tracks`` is a list of :class:`SheetTrack` objects, 1598 one per track on the CD. 1599 ``metadata`` is a :class:`MetaData` object or None 1600 1601.. classmethod:: Sheet.converted(sheet) 1602 1603 Given a :class:`Sheet`-compatible object, 1604 returns a :class:`Sheet` object. 1605 1606.. method:: Sheet.__len__() 1607 1608 Returns the number of tracks in the sheet. 1609 1610.. method:: Sheet.__getitem__(track_index) 1611 1612 Given a track index (starting from 0), returns a 1613 :class:`SheetTrack` object. 1614 Raises :exc:`IndexError` if the track cannot be found. 1615 1616.. method:: Sheet.track_numbers() 1617 1618 Returns a list of all track numbers in the sheet. 1619 1620.. method:: Sheet.track(track_number) 1621 1622 Given a track number (often starting from 1), 1623 returns a :class:`SheetTrack` object with that number. 1624 Raises :exc:`KeyError` if the track cannot be found. 1625 1626.. method:: Sheet.pre_gap() 1627 1628 Returns the disc's pre-gap 1629 (the amount of empty samples before the first track) 1630 as a :class:`Fraction` number of seconds. 1631 This number is often zero. 1632 1633.. method:: Sheet.track_offset(track_number) 1634 1635 Given a track number (often starting from 1), 1636 returns the offset to that track as a :class:`Fraction` number 1637 of seconds. 1638 1639 May raise :exc:`KeyError` if the track cannot be found. 1640 1641.. method:: Sheet.track_length(track_number) 1642 1643 Given a track number (often starting from 1), 1644 returns the length of that track as a :class:`Fraction` number 1645 of seconds. 1646 1647 May return ``None`` if the track is to use the remainder 1648 of the samples in the stream. 1649 This is typical of the last track in an album. 1650 1651 May raise :exc:`KeyError` if the track cannot be found. 1652 1653.. method:: Sheet.get_metadata() 1654 1655 Returns a :class:`MetaData` object containing metadata 1656 for the entire sheet such as catalog number or CD-TEXT information. 1657 May return ``None`` if there is no such metadata. 1658 1659SheetTrack Objects 1660^^^^^^^^^^^^^^^^^^ 1661 1662These objects represent a track on a given cuesheet. 1663 1664.. class:: SheetTrack(number, track_indexes, [metadata], [filename], [is_audio=True], [pre_emphasis=False], [copy_permitted=False]) 1665 1666 =============== ============ ====================================== 1667 argument type value 1668 --------------- ------------ -------------------------------------- 1669 number int track number, starting from 1 1670 track_indexes [SheetIndex] list of SheetIndex objects 1671 metadata MetaData track's metadata, or None 1672 filename unicode track's filename on disc 1673 is_audio boolean whether track contains audio data 1674 pre_emphasis boolean whether track has pre-emphasis 1675 copy_permitted boolean whether copying is permitted 1676 =============== ============ ====================================== 1677 1678.. classmethod:: SheetTrack.converted(sheet_track) 1679 1680 Given a :class:`SheetTrack`-compatible object, 1681 returns a :class:`SheetTrack`. 1682 1683.. method:: SheetTrack.__len__() 1684 1685 Returns the number of :class:`SheetIndex` objects in the track. 1686 1687.. method:: SheetTrack.__getitem__(i) 1688 1689 Given an index (starting from 0), returns a track's 1690 :class:`SheetIndex` object. 1691 Raises :exc:`IndexError` if the index cannot be found. 1692 1693.. method:: SheetTrack.indexes() 1694 1695 Returns a list of all index numbers in the track. 1696 1697.. method:: SheetTrack.index(sheet_index) 1698 1699 Given an index number (often starting from 1), 1700 returns a track's :class:`SheetIndex` object. 1701 Raises :exc:`KeyError` if the index is not present. 1702 1703.. method:: SheetTrack.number() 1704 1705 Returns the track's number, typically starting from 1. 1706 1707.. method:: SheetTrack.get_metadata() 1708 1709 Returns the track's metadata such as ISRC and CD-TEXT information 1710 as a :class:`MetaData` object. 1711 May return ``None`` if it has no metadata. 1712 1713.. method:: SheetTrack.filename() 1714 1715 Returns the track's filename as a Unicode string. 1716 1717.. method:: SheetTrack.is_audio() 1718 1719 Returns whether the track contains audio data. 1720 1721.. method:: SheetTrack.pre_emphasis() 1722 1723 Returns whether the track has pre-emphasis. 1724 1725.. method:: SheetTrack.copy_permitted() 1726 1727 Returns whether copying is permitted. 1728 1729SheetIndex Objects 1730^^^^^^^^^^^^^^^^^^ 1731 1732.. class:: SheetIndex(number, offset) 1733 1734 ``number`` is the number of the index in the track, 1735 often starting from 1. 1736 A number of 0 indicates a pre-gap index. 1737 ``offset`` is the index's offset from the start of the 1738 stream as a :class:`Fraction` number of seconds. 1739 1740.. method:: SheetIndex.number() 1741 1742 Returns the track's index as an integer. 1743 1744.. method:: SheetIndex.offset() 1745 1746 Returns the index point's offset from the start of the stream 1747 as a :class:`Fraction` number of seconds. 1748 1749DVDAudio Objects 1750---------------- 1751 1752.. class:: DVDAudio(audio_ts_path[, device]) 1753 1754 This class is used to access a DVD-Audio. 1755 It contains a collection of titlesets. 1756 Each titleset contains a list of 1757 :class:`audiotools.dvda.DVDATitle` objects, 1758 and each :class:`audiotools.dvda.DVDATitle` contains a list of 1759 :class:`audiotools.dvda.DVDATrack` objects. 1760 ``audio_ts_path`` is the path to the DVD-Audio's 1761 ``AUDIO_TS`` directory, such as ``/media/cdrom/AUDIO_TS``. 1762 ``device`` is the path to the DVD-Audio's mount device, 1763 such as ``/dev/cdrom``. 1764 1765 For example, to access the 3rd :class:`DVDATrack` object 1766 of the 2nd :class:`DVDATitle` of the first titleset, 1767 one can simply perform the following: 1768 1769 >>> track = DVDAudio(path)[0][1][2] 1770 1771.. note:: 1772 1773 If ``device`` is indicated *and* the ``AUDIO_TS`` directory 1774 contains a ``DVDAUDIO.MKB`` file, unprotection will be 1775 performed automatically if supported on the user's platform. 1776 Otherwise, the files are assumed to be unprotected. 1777 1778ExecQueue Objects 1779----------------- 1780 1781.. class:: ExecQueue() 1782 1783 This is a class for executing multiple Python functions in 1784 parallel across multiple CPUs. 1785 1786.. method:: ExecQueue.execute(function, args[, kwargs]) 1787 1788 Queues a Python function, list of arguments and optional 1789 dictionary of keyword arguments. 1790 1791.. method:: ExecQueue.run([max_processes]) 1792 1793 Executes all queued Python functions, running ``max_processes`` 1794 number of functions at a time until the entire queue is empty. 1795 This operates by forking a new subprocess per function, 1796 executing that function and then, regardless of the function's result, 1797 the child job performs an unconditional exit. 1798 1799 This means that any side effects of executed functions have 1800 no effect on ExecQueue's caller besides those which modify 1801 files on disk (encoding an audio file, for example). 1802 1803.. class:: ExecQueue2() 1804 1805 This is a class for executing multiple Python functions in 1806 parallel across multiple CPUs and receiving results 1807 from those functions. 1808 1809.. method:: ExecQueue2.execute(function, args[, kwargs]) 1810 1811 Queues a Python function, list of arguments and optional 1812 dictionary of keyword arguments. 1813 1814.. method:: ExecQueue2.run([max_processes]) 1815 1816 Executes all queued Python functions, running ``max_processes`` 1817 number of functions at a time until the entire queue is empty. 1818 Returns an iterator of the returned values of those functions. 1819 This operates by forking a new subprocess per function 1820 with a pipe between them, executing that function in the child process 1821 and then transferring the resulting pickled object back to the parent 1822 before performing an unconditional exit. 1823 1824 Queued functions that raise an exception or otherwise exit uncleanly 1825 yield ``None``. 1826 Likewise, any side effects of the called function have no 1827 effect on ExecQueue's caller. 1828 1829ExecProgressQueue Objects 1830------------------------- 1831 1832.. class:: ExecProgressQueue(messenger) 1833 1834 This class runs multiple jobs in parallel and displays their 1835 progress output to the given :class:`Messenger` object. 1836 1837.. method:: ExecProgressQueue.execute(function[, progress_text[, completion_output[, *args[, **kwargs]]]]) 1838 1839 Queues a Python function for execution. 1840 This function is passed the optional ``args`` and ``kwargs`` 1841 arguments upon execution. 1842 However, this function is also passed an *additional* ``progress`` 1843 keyword argument which is a function that takes ``current`` and 1844 ``total`` integer arguments. 1845 The executed function can then call that ``progress`` function 1846 at regular intervals to indicate its progress. 1847 1848 If given, ``progress_text`` is a Unicode string to be displayed 1849 while the function is being executed. 1850 1851 ``completion_output`` is displayed once the executed function is 1852 completed. 1853 It can be either a Unicode string or a function whose argument 1854 is the returned result of the executed function and which must 1855 output either a Unicode string or ``None``. 1856 If ``None``, no output text is generated for the completed job. 1857 1858.. method:: ExecProgressQueue.run([max_processes]) 1859 1860 Executes all the queued functions, running ``max_processes`` number 1861 of functions at a time until the entire queue is empty. 1862 Returns the results of the called functions in the order 1863 in which they were added for execution. 1864 This operates by forking a new subprocess per function 1865 in which the running progress and function output are 1866 piped to the parent for display to the screen. 1867 1868 If an exception occurs in one of the subprocesses, 1869 that exception will be raised by :meth:`ExecProgressQueue.run` 1870 and all the running jobs will be terminated. 1871 1872 >>> def progress_function(progress, filename): 1873 ... # perform work here 1874 ... progress(current, total) 1875 ... # more work 1876 ... result.a = a 1877 ... result.b = b 1878 ... result.c = c 1879 ... return result 1880 ... 1881 >>> def format_result(result): 1882 ... return u"%s %s %s" % (result.a, result.b, result.c) 1883 ... 1884 >>> queue = ExecProgressQueue(ProgressDisplay(Messenger("executable"))) 1885 >>> queue.execute(function=progress_function, 1886 ... progress_text=u"%s progress" % (filename1), 1887 ... completion_output=format_result, 1888 ... filename=filename1) 1889 ... 1890 >>> queue.execute(function=progress_function, 1891 ... progress_text=u"%s progress" % (filename2), 1892 ... completion_output=format_result, 1893 ... filename=filename2) 1894 ... 1895 >>> queue.run() 1896 1897 1898Messenger Objects 1899----------------- 1900 1901.. class:: Messenger(silent=False) 1902 1903 This is a helper class for displaying program data, 1904 analogous to a primitive logging facility. 1905 If ``silent`` is ``True``, the output methods will not 1906 actually display any output to the screen. 1907 1908.. method:: Messenger.output(string) 1909 1910 Outputs Unicode ``string`` to stdout and adds a newline, 1911 unless ``verbosity`` level is ``"silent"``. 1912 1913.. method:: Messenger.partial_output(string) 1914 1915 Output Unicode ``string`` to stdout and flushes output 1916 so it is displayed, but does not add a newline. 1917 Does nothing if ``verbosity`` level is ``"silent"``. 1918 1919.. method:: Messenger.info(string) 1920 1921 Outputs Unicode ``string`` to stdout and adds a newline, 1922 unless ``verbosity`` level is ``"silent"``. 1923 1924.. method:: Messenger.partial_info(string) 1925 1926 Output Unicode ``string`` to stdout and flushes output 1927 so it is displayed, but does not add a newline. 1928 Does nothing if ``verbosity`` level is ``"silent"``. 1929 1930.. note:: 1931 1932 What's the difference between :meth:`Messenger.output` and :meth:`Messenger.info`? 1933 :meth:`Messenger.output` is for a program's primary data. 1934 :meth:`Messenger.info` is for incidental information. 1935 For example, trackinfo uses :meth:`Messenger.output` for what it 1936 displays since that output is its primary function. 1937 But track2track uses :meth:`Messenger.info` for its lines of progress 1938 since its primary function is converting audio 1939 and tty output is purely incidental. 1940 1941.. method:: Messenger.warning(string) 1942 1943 Outputs warning text, Unicode ``string`` and a newline to stderr, 1944 unless ``verbosity`` level is ``"silent"``. 1945 1946 >>> m = audiotools.Messenger() 1947 >>> m.warning(u"Watch Out!") 1948 *** Warning: Watch Out! 1949 1950.. method:: Messenger.error(string) 1951 1952 Outputs error text, Unicode ``string`` and a newline to stderr. 1953 1954 >>> m.error(u"Fatal Error!") 1955 *** Error: Fatal Error! 1956 1957.. method:: Messenger.os_error(oserror) 1958 1959 Given an :class:`OSError` object, displays it as a properly formatted 1960 error message with an appended newline. 1961 1962.. note:: 1963 1964 This is necessary because of the way :class:`OSError` handles 1965 its embedded filename string. 1966 Using this method ensures that filename is properly encoded when 1967 displayed. 1968 Otherwise, there's a good chance that non-ASCII filenames will 1969 be garbled. 1970 1971.. method:: Messenger.output_isatty() 1972 1973 Returns ``True`` if the output method sends to a TTY rather than a file. 1974 1975.. method:: Messenger.info_isatty() 1976 1977 Returns ``True`` if the info method sends to a TTY rather than a file. 1978 1979.. method:: Messenger.error_isatty() 1980 1981 Returns ``True`` if the error method sends to a TTY rather than a file. 1982 1983.. method:: Messenger.ansi_clearline() 1984 1985 Generates a ANSI escape codes to clear the current line. 1986 1987 This works only if ``stdout`` is a TTY, otherwise is does nothing. 1988 1989 >>> msg = Messenger() 1990 >>> msg.partial_output(u"working") 1991 >>> time.sleep(1) 1992 >>> msg.ansi_clearline() 1993 >>> msg.output(u"done") 1994 1995.. method:: Messenger.ansi_uplines(self, lines) 1996 1997 Moves the cursor upwards by the given number of lines. 1998 1999.. method:: Messenger.ansi_cleardown(self) 2000 2001 Clears all the output below the current line. 2002 This is typically used in conjunction with :meth:`Messenger.ansi_uplines`. 2003 2004 >>> msg = Messenger() 2005 >>> msg.output(u"line 1") 2006 >>> msg.output(u"line 2") 2007 >>> msg.output(u"line 3") 2008 >>> msg.output(u"line 4") 2009 >>> time.sleep(2) 2010 >>> msg.ansi_uplines(4) 2011 >>> msg.ansi_cleardown() 2012 >>> msg.output(u"done") 2013 2014.. method:: Messenger.terminal_size(fd) 2015 2016 Given a file descriptor integer, or file object with a fileno() method, 2017 returns the size of the current terminal as a (``height``, ``width``) 2018 tuple of integers. 2019 2020ProgressDisplay Objects 2021----------------------- 2022 2023.. class:: ProgressDisplay(messenger) 2024 2025 This is a class for displaying incremental progress updates to the screen. 2026 It takes a :class:`Messenger` object which is used for generating 2027 output. 2028 Whether or not :attr:`sys.stdout` is a TTY determines how 2029 this class operates. 2030 If a TTY is detected, screen updates are performed incrementally 2031 with individual rows generated and refreshed as needed using 2032 ANSI escape sequences such that the user's screen need not scroll. 2033 If a TTY is not detected, most progress output is omitted. 2034 2035.. method:: ProgressDisplay.add_row(output_line) 2036 2037 ``output_line`` is a Unicode string indicating what 2038 we're displaying the progress of. 2039 Returns a :class:`ProgressRow` object which can be updated 2040 with the current progress for display. 2041 2042.. method:: ProgressDisplay.remove_row(row_index) 2043 2044 Removes the given row index and frees the slot for reuse. 2045 2046.. method:: ProgressDisplay.display_rows() 2047 2048 Outputs the current state of all progress rows. 2049 2050.. method:: ProgressDisplay.clear_row() 2051 2052 Clears all previously displayed output rows, if any. 2053 2054.. class:: ProgressRow(progress_display, row_index, output_line) 2055 2056 This is used by :class:`ProgressDisplay` and its subclasses 2057 for actual output generation. 2058 ``progress_display`` is a parent :class:`ProgressDisplay` object. 2059 ``row_index`` is this row's index on the screen. 2060 ``output_line`` is a unicode string. 2061 It is not typically instantiated directly. 2062 2063.. method:: ProgressRow.update(current, total) 2064 2065 Updates the current progress with ``current`` and ``total`` integer values. 2066 2067.. method:: ProgressRow.finish() 2068 2069 Indicate output is finished and the row will no longer be needed. 2070 2071.. method:: ProgressRow.unicode(width) 2072 2073 Returns the output line and its current progress as a Unicode string, 2074 formatted to the given width in onscreen characters. 2075 Screen width can be determined from the :meth:`Messenger.terminal_size` 2076 method. 2077 2078.. class:: SingleProgressDisplay(messenger, progress_text) 2079 2080 This is a subclass of :class:`ProgressDisplay` used 2081 for generating only a single line of progress output. 2082 As such, one only specifies a single row of Unicode ``progress_text`` 2083 at initialization time and can avoid the row management functions 2084 entirely. 2085 2086.. method:: SingleProgressDisplay.update(current, total) 2087 2088 Updates the status of our output row with ``current`` and ``total`` 2089 integers, which function identically to those of 2090 :meth:`ProgressDisplay.update_row`. 2091 2092.. class:: ReplayGainProgressDisplay(messenger, lossless_replay_gain) 2093 2094 This is another :class:`ProgressDisplay` subclass optimized 2095 for the display of ReplayGain application progress. 2096 ``messenger`` is a :class:`Messenger` object and 2097 ``lossless_replay_gain`` is a boolean indicating whether 2098 ReplayGain is being applied losslessly or not 2099 (which can be determined from the :meth:`AudioFile.lossless_replay_gain` 2100 classmethod). 2101 Whether or not :attr:`sys.stdout` is a TTY determines how 2102 this class behaves. 2103 2104.. method:: ReplayGainProgressDisplay.initial_message() 2105 2106 If operating on a TTY, this does nothing since progress output 2107 will be displayed. 2108 Otherwise, this indicates that ReplayGain application has begun. 2109 2110.. method:: ReplayGainProgressDisplay.update(current, total) 2111 2112 Updates the status of ReplayGain application. 2113 2114.. method:: ReplayGainProgressDisplay.final_message() 2115 2116 If operating on a TTY, this indicates that ReplayGain application 2117 is complete. 2118 Otherwise, this does nothing. 2119 2120 >>> rg_progress = ReplayGainProgressDisplay(messenger, AudioType.lossless_replay_gain()) 2121 >>> rg_progress.initial_message() 2122 >>> AudioType.add_replay_gain(filename_list, rg_progress.update) 2123 >>> rg_Progress.final_message() 2124 2125output_text Objects 2126^^^^^^^^^^^^^^^^^^^ 2127 2128This class is for displaying portions of a Unicode string to 2129the screen and applying formatting such as color via ANSI escape 2130sequences. 2131 2132The reason this is needed is because not all Unicode characters 2133are the same width when displayed to the screen. 2134So, for example, if one wishes to display a portion of a Unicode string to 2135a screen that's 80 ASCII characters wide, one can't simply perform: 2136 2137>>> messenger.output(unicode_string[0:80]) 2138 2139since some of those Unicode characters might be double width, 2140which would cause the string to wrap. 2141 2142.. class:: output_text(unicode_string[, fg_color][, bg_color][, style]) 2143 2144 ``unicode_string`` is the text to display. 2145 ``fg_color`` and ``bg_color`` may be one of 2146 ``"black"``, ``"red"``, ``"green"``, ``"yellow"``, 2147 ``"blue"``, ``"magenta"``, ``"cyan"``, or ``"white"``. 2148 ``style`` may be one of 2149 ``"bold"``, ``"underline"``, ``"blink"`` or ``"inverse"``. 2150 2151.. method:: output_text.__unicode__ 2152 2153 Returns the raw Unicode string. 2154 2155.. method:: output_text.__len__ 2156 2157 Returns the width of the text in displayed characters. 2158 2159.. method:: output_text.fg_color() 2160 2161 Returns the foreground color as a string, or ``None``. 2162 2163.. method:: output_text.bg_color() 2164 2165 Returns the background color as a string, or ``None``. 2166 2167.. method:: output_text.style() 2168 2169 Returns the style as a string, or ``None``. 2170 2171.. method:: output_text.set_format([fg_color][, bg_color][, style]) 2172 2173 Returns a new :class:`output_text` object with the given styles. 2174 2175.. method:: output_text.format([is_tty]) 2176 2177 If formatting is present and ``is_tty`` is ``True``, 2178 returns a Unicode string with ANSI escape sequences applied. 2179 Otherwise, returns the Unicode string with no ANSI formatting. 2180 2181.. method:: output_text.head(display_characters) 2182 2183 Returns a new :class:`output_text` object that's been 2184 truncated up to the given number of display characters, 2185 but may return less. 2186 2187 >>> s = u"".join(map(unichr, range(0x30a1, 0x30a1+25))) 2188 >>> len(s) 2189 25 2190 >>> u = unicode(output_text(s).head(40)) 2191 >>> len(u) 2192 20 2193 >>> print repr(u) 2194 u'\u30a1\u30a2\u30a3\u30a4\u30a5\u30a6\u30a7\u30a8\u30a9\u30aa\u30ab\u30ac\u30ad\u30ae\u30af\u30b0\u30b1\u30b2\u30b3\u30b4' 2195 2196.. note:: 2197 2198 Because some characters are double-width, this method 2199 along with :meth:`output_text.tail` and :meth:`output_text.split` 2200 may not return strings that are the same length as requested 2201 if the dividing point in the middle of a character. 2202 2203.. method:: output_text.tail(display_characters) 2204 2205 Returns a new :class:`output_text` object that's been 2206 truncated up to the given number of display characters. 2207 2208 >>> s = u"".join(map(unichr, range(0x30a1, 0x30a1+25))) 2209 >>> len(s) 2210 25 2211 >>> u = unicode(output_text(s).tail(40)) 2212 >>> len(u) 2213 20 2214 >>> print repr(u) 2215 u'\u30a6\u30a7\u30a8\u30a9\u30aa\u30ab\u30ac\u30ad\u30ae\u30af\u30b0\u30b1\u30b2\u30b3\u30b4\u30b5\u30b6\u30b7\u30b8\u30b9' 2216 2217.. method:: output_text.split(display_characters) 2218 2219 Returns a tuple of :class:`output_text` objects. 2220 The first is up to ``display_characters`` wide, 2221 while the second contains the remainder. 2222 2223 >>> s = u"".join(map(unichr, range(0x30a1, 0x30a1+25))) 2224 >>> (head, tail) = display_unicode(s).split(40) 2225 >>> print repr(unicode(head)) 2226 u'\u30a1\u30a2\u30a3\u30a4\u30a5\u30a6\u30a7\u30a8\u30a9\u30aa\u30ab\u30ac\u30ad\u30ae\u30af\u30b0\u30b1\u30b2\u30b3\u30b4' 2227 >>> print repr(unicode(tail)) 2228 u'\u30b5\u30b6\u30b7\u30b8\u30b9' 2229 2230.. method:: output_text.join(output_texts) 2231 2232 Given an iterable collection of :class:`output_text` objects, 2233 returns an :class:`output_list` joined by our formatted text. 2234 2235output_list Objects 2236^^^^^^^^^^^^^^^^^^^ 2237 2238output_list is an :class:`output_text` subclass 2239for formatting multiple :class:`output_text` objects as a unit. 2240 2241.. class:: output_list(output_texts[, fg_color][, bg_color][, style]) 2242 2243 ``output_texts`` is an iterable collection of 2244 :class:`output_text` or unicode objects. 2245 ``fg_color`` and ``bg_color`` may be one of 2246 ``"black"``, ``"red"``, ``"green"``, ``"yellow"``, 2247 ``"blue"``, ``"magenta"``, ``"cyan"``, or ``"white"``. 2248 ``style`` may be one of 2249 ``"bold"``, ``"underline"``, ``"blink"`` or ``"inverse"``. 2250 2251.. warning:: 2252 2253 Formatting is unlikely to nest properly since 2254 ANSI is un-escaped to the terminal default. 2255 Therefore, if the :class:`output_list` has formatting, 2256 its contained :class:`output_text` objects should not have formatting. 2257 Or if the :class:`output_text` objects do have formatting, 2258 the :class:`output_list` container should not have formatting. 2259 2260.. method:: output_list.fg_color() 2261 2262 Returns the foreground color as a string, or ``None``. 2263 2264.. method:: output_list.bg_color() 2265 2266 Returns the background color as a string, or ``None``. 2267 2268.. method:: output_list.style() 2269 2270 Returns the style as a string, or ``None``. 2271 2272.. method:: output_list.set_format([fg_color][, bg_color][, style]) 2273 2274 Returns a new :class:`output_list` object with the given formatting. 2275 2276.. method:: output_list.format([is_tty]) 2277 2278 If formatting is present and ``is_tty`` is ``True``, 2279 returns a Unicode string with ANSI escape sequences applied. 2280 Otherwise, returns the Unicode string with no ANSI formatting. 2281 2282.. method:: output_list.head(display_characters) 2283 2284 Returns a new :class:`output_list` object that's been 2285 truncated up to the given number of display characters, 2286 but may return less. 2287 2288.. method:: output_list.tail(display_characters) 2289 2290 Returns a new :class:`output_list` object that's been 2291 truncated up to the given number of display characters. 2292 2293.. method:: output_list.split(display_characters) 2294 2295 Returns a tuple of :class:`output_text` objects. 2296 The first is up to ``display_characters`` wide, 2297 while the second contains the remainder. 2298 2299.. method:: output_list.join(output_texts) 2300 2301 Given an iterable collection of :class:`output_text` objects, 2302 returns an :class:`output_list` joined by our formatted text. 2303 2304output_table Objects 2305^^^^^^^^^^^^^^^^^^^^ 2306 2307output_table is for formatting text into rows and columns. 2308 2309.. class:: output_table() 2310 2311.. method:: output_table.row() 2312 2313 Adds new row to table and returns :class:`output_table_row` object 2314 which columns may be added to. 2315 2316.. method:: output_table.blank_row() 2317 2318 Adds empty row to table whose columns will be blank. 2319 2320.. method:: output_table.divider_row(dividers) 2321 2322 Takes a list of Unicode characters, one per column, 2323 and generates a row which will expand those characters 2324 as needed to fill each column. 2325 2326.. method:: output_table.format([is_tty]) 2327 2328 Yields one formatted Unicode string per row. 2329 If ``is_tty`` is ``True``, rows may contain ANSI escape sequences 2330 for color and style. 2331 2332output_table_row Objects 2333^^^^^^^^^^^^^^^^^^^^^^^^ 2334 2335output_table_row is a container for table columns 2336and is returned from :meth:`output_table.row()` 2337rather than instantiated directly. 2338 2339.. class:: output_table_row() 2340 2341.. method:: output_table_row.__len__() 2342 2343 Returns the total number of columns in the table. 2344 2345.. method:: output_table_row.add_column(text[, alignment="left"][, colspan=1]) 2346 2347 Adds text, which may be a Unicode string or 2348 :class:`output_text` object. 2349 ``alignment`` may be ``"left"``, ``"center"`` or ``"right"``. 2350 If `colspan` is greater than 1, the column is widened to span 2351 that many other non-spanning columns. 2352 2353.. method:: output_table_row.column_width(column) 2354 2355 Returns the width of the given column in printable characters. 2356 2357.. method:: output_table_row.format(column_widths[, is_tty]) 2358 2359 Given a list of column widths, returns the table row 2360 as a Unicode string such that each column is padded to the 2361 corresponding width depending on its alignment. 2362 If ``is_tty`` is ``True``, columns may contain ANSI escape 2363 sequences for color and style. 2364 2365Exceptions 2366---------- 2367 2368.. exception:: UnknownAudioType 2369 2370 Raised by :func:`filename_to_type` if the file's suffix is unknown. 2371 2372.. exception:: AmbiguousAudioType 2373 2374 Raised by :func:`filename_to_type` if the file's suffix 2375 applies to more than one audio class. 2376 2377.. exception:: DecodingError 2378 2379 Raised by :class:`PCMReader`'s .close() method if 2380 a helper subprocess exits with an error, 2381 typically indicating a problem decoding the file. 2382 2383.. exception:: DuplicateFile 2384 2385 Raised by :func:`open_files` if the same file 2386 is included more than once and ``no_duplicates`` is indicated. 2387 2388.. exception:: DuplicateOutputFile 2389 2390 Raised by :func:`audiotools.ui.process_output_options` 2391 if the same output file is generated more than once. 2392 2393.. exception:: EncodingError 2394 2395 Raised by :meth:`AudioFile.from_pcm` and :meth:`AudioFile.convert` 2396 if an error occurs when encoding an input file. 2397 This includes errors from the input stream, 2398 a problem writing the output file in the given location, 2399 or EncodingError subclasses such as 2400 :exc:`UnsupportedBitsPerSample` if the input stream 2401 is formatted in a way the output class does not support. 2402 2403.. exception:: InvalidFile 2404 2405 Raised by :meth:`AudioFile.__init__` if the file 2406 is invalid in some way. 2407 2408.. exception:: InvalidFilenameFormat 2409 2410 Raised by :meth:`AudioFile.track_name` if the format string 2411 contains broken fields. 2412 2413.. exception:: InvalidImage 2414 2415 Raised by :meth:`Image.new` if the image cannot be parsed correctly. 2416 2417.. exception:: OutputFileIsInput 2418 2419 Raised by :func:`process_output_options` if an output file 2420 is the same as any of the input files. 2421 2422.. exception:: SheetException 2423 2424 A parent exception of :exc:`audiotools.cue.CueException` 2425 and :exc:`audiotools.toc.TOCException`, 2426 to be raised by :func:`read_sheet` if a .toc or .cue file 2427 is unable to be parsed correctly. 2428 2429.. exception:: UnsupportedBitsPerSample 2430 2431 Subclass of :exc:`EncodingError`, indicating 2432 the input stream's bits-per-sample is not supported 2433 by the output class. 2434 2435.. exception:: UnsupportedChannelCount 2436 2437 Subclass of :exc:`EncodingError`, indicating 2438 the input stream's channel count is not supported 2439 by the output class. 2440 2441.. exception:: UnsupportedChannelMask 2442 2443 Subclass of :exc:`EncodingError`, indicating 2444 the input stream's channel mask is not supported 2445 by the output class. 2446 2447.. exception:: UnsupportedFile 2448 2449 Raised by :func:`open` if the given file is not something 2450 identifiable, or we do not have the installed binaries to support. 2451 2452.. exception:: UnsupportedTracknameField 2453 2454 Raised by :meth:`AudioFile.track_name` if a track name 2455 field is not supported. 2456