You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

891 lines
30 KiB

Partially merge trunk into p3yk. The removal of Mac/Tools is confusing svn merge in bad ways, so I'll have to merge that extra-carefully (probably manually.) Merged revisions 46495-46605 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r46495 | tim.peters | 2006-05-28 03:52:38 +0200 (Sun, 28 May 2006) | 2 lines Added missing svn:eol-style property to text files. ........ r46497 | tim.peters | 2006-05-28 12:41:29 +0200 (Sun, 28 May 2006) | 3 lines PyErr_Display(), PyErr_WriteUnraisable(): Coverity found a cut-and-paste bug in both: `className` was referenced before being checked for NULL. ........ r46499 | fredrik.lundh | 2006-05-28 14:06:46 +0200 (Sun, 28 May 2006) | 5 lines needforspeed: added Py_MEMCPY macro (currently tuned for Visual C only), and use it for string copy operations. this gives a 20% speedup on some string benchmarks. ........ r46501 | michael.hudson | 2006-05-28 17:51:40 +0200 (Sun, 28 May 2006) | 26 lines Quality control, meet exceptions.c. Fix a number of problems with the need for speed code: One is doing this sort of thing: Py_DECREF(self->field); self->field = newval; Py_INCREF(self->field); without being very sure that self->field doesn't start with a value that has a __del__, because that almost certainly can lead to segfaults. As self->args is constrained to be an exact tuple we may as well exploit this fact consistently. This leads to quite a lot of simplification (and, hey, probably better performance). Add some error checking in places lacking it. Fix some rather strange indentation in the Unicode code. Delete some trailing whitespace. More to come, I haven't fixed all the reference leaks yet... ........ r46502 | george.yoshida | 2006-05-28 18:39:09 +0200 (Sun, 28 May 2006) | 3 lines Patch #1080727: add "encoding" parameter to doctest.DocFileSuite Contributed by Bjorn Tillenius. ........ r46503 | martin.v.loewis | 2006-05-28 18:57:38 +0200 (Sun, 28 May 2006) | 4 lines Rest of patch #1490384: Commit icon source, remove claim that Erik von Blokland is the author of the installer picture. ........ r46504 | michael.hudson | 2006-05-28 19:40:29 +0200 (Sun, 28 May 2006) | 16 lines Quality control, meet exceptions.c, round two. Make some functions that should have been static static. Fix a bunch of refleaks by fixing the definition of MiddlingExtendsException. Remove all the __new__ implementations apart from BaseException_new. Rewrite most code that needs it to cope with NULL fields (such code could get excercised anyway, the __new__-removal just makes it more likely). This involved editing the code for WindowsError, which I can't test. This fixes all the refleaks in at least the start of a regrtest -R :: run. ........ r46505 | marc-andre.lemburg | 2006-05-28 19:46:58 +0200 (Sun, 28 May 2006) | 10 lines Initial version of systimes - a module to provide platform dependent performance measurements. The module is currently just a proof-of-concept implementation, but will integrated into pybench once it is stable enough. License: pybench license. Author: Marc-Andre Lemburg. ........ r46507 | armin.rigo | 2006-05-28 21:13:17 +0200 (Sun, 28 May 2006) | 15 lines ("Forward-port" of r46506) Remove various dependencies on dictionary order in the standard library tests, and one (clearly an oversight, potentially critical) in the standard library itself - base64.py. Remaining open issues: * test_extcall is an output test, messy to make robust * tarfile.py has a potential bug here, but I'm not familiar enough with this code. Filed in as SF bug #1496501. * urllib2.HTTPPasswordMgr() returns a random result if there is more than one matching root path. I'm asking python-dev for clarification... ........ r46508 | georg.brandl | 2006-05-28 22:11:45 +0200 (Sun, 28 May 2006) | 4 lines The empty string is a valid import path. (fixes #1496539) ........ r46509 | georg.brandl | 2006-05-28 22:23:12 +0200 (Sun, 28 May 2006) | 3 lines Patch #1496206: urllib2 PasswordMgr ./. default ports ........ r46510 | georg.brandl | 2006-05-28 22:57:09 +0200 (Sun, 28 May 2006) | 3 lines Fix refleaks in UnicodeError get and set methods. ........ r46511 | michael.hudson | 2006-05-28 23:19:03 +0200 (Sun, 28 May 2006) | 3 lines use the UnicodeError traversal and clearing functions in UnicodeError subclasses. ........ r46512 | thomas.wouters | 2006-05-28 23:32:12 +0200 (Sun, 28 May 2006) | 4 lines Make last patch valid C89 so Windows compilers can deal with it. ........ r46513 | georg.brandl | 2006-05-28 23:42:54 +0200 (Sun, 28 May 2006) | 3 lines Fix ref-antileak in _struct.c which eventually lead to deallocating None. ........ r46514 | georg.brandl | 2006-05-28 23:57:35 +0200 (Sun, 28 May 2006) | 4 lines Correct None refcount issue in Mac modules. (Are they still used?) ........ r46515 | armin.rigo | 2006-05-29 00:07:08 +0200 (Mon, 29 May 2006) | 3 lines A clearer error message when passing -R to regrtest.py with release builds of Python. ........ r46516 | georg.brandl | 2006-05-29 00:14:04 +0200 (Mon, 29 May 2006) | 3 lines Fix C function calling conventions in _sre module. ........ r46517 | georg.brandl | 2006-05-29 00:34:51 +0200 (Mon, 29 May 2006) | 3 lines Convert audioop over to METH_VARARGS. ........ r46518 | georg.brandl | 2006-05-29 00:38:57 +0200 (Mon, 29 May 2006) | 3 lines METH_NOARGS functions do get called with two args. ........ r46519 | georg.brandl | 2006-05-29 11:46:51 +0200 (Mon, 29 May 2006) | 4 lines Fix refleak in socketmodule. Replace bogus Py_BuildValue calls. Fix refleak in exceptions. ........ r46520 | nick.coghlan | 2006-05-29 14:43:05 +0200 (Mon, 29 May 2006) | 7 lines Apply modified version of Collin Winter's patch #1478788 Renames functional extension module to _functools and adds a Python functools module so that utility functions like update_wrapper can be added easily. ........ r46522 | georg.brandl | 2006-05-29 15:53:16 +0200 (Mon, 29 May 2006) | 3 lines Convert fmmodule to METH_VARARGS. ........ r46523 | georg.brandl | 2006-05-29 16:13:21 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494605. ........ r46524 | georg.brandl | 2006-05-29 16:28:05 +0200 (Mon, 29 May 2006) | 3 lines Handle PyMem_Malloc failure in pystrtod.c. Closes #1494671. ........ r46525 | georg.brandl | 2006-05-29 16:33:55 +0200 (Mon, 29 May 2006) | 3 lines Fix compiler warning. ........ r46526 | georg.brandl | 2006-05-29 16:39:00 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494787 (pyclbr counts whitespace as superclass name) ........ r46527 | bob.ippolito | 2006-05-29 17:47:29 +0200 (Mon, 29 May 2006) | 1 line simplify the struct code a bit (no functional changes) ........ r46528 | armin.rigo | 2006-05-29 19:59:47 +0200 (Mon, 29 May 2006) | 2 lines Silence a warning. ........ r46529 | georg.brandl | 2006-05-29 21:39:45 +0200 (Mon, 29 May 2006) | 3 lines Correct some value converting strangenesses. ........ r46530 | nick.coghlan | 2006-05-29 22:27:44 +0200 (Mon, 29 May 2006) | 1 line When adding a module like functools, it helps to let SVN know about the file. ........ r46531 | georg.brandl | 2006-05-29 22:52:54 +0200 (Mon, 29 May 2006) | 4 lines Patches #1497027 and #972322: try HTTP digest auth first, and watch out for handler name collisions. ........ r46532 | georg.brandl | 2006-05-29 22:57:01 +0200 (Mon, 29 May 2006) | 3 lines Add News entry for last commit. ........ r46533 | georg.brandl | 2006-05-29 23:04:52 +0200 (Mon, 29 May 2006) | 4 lines Make use of METH_O and METH_NOARGS where possible. Use Py_UnpackTuple instead of PyArg_ParseTuple where possible. ........ r46534 | georg.brandl | 2006-05-29 23:58:42 +0200 (Mon, 29 May 2006) | 3 lines Convert more modules to METH_VARARGS. ........ r46535 | georg.brandl | 2006-05-30 00:00:30 +0200 (Tue, 30 May 2006) | 3 lines Whoops. ........ r46536 | fredrik.lundh | 2006-05-30 00:42:07 +0200 (Tue, 30 May 2006) | 4 lines fixed "abc".count("", 100) == -96 error (hopefully, nobody's relying on the current behaviour ;-) ........ r46537 | bob.ippolito | 2006-05-30 00:55:48 +0200 (Tue, 30 May 2006) | 1 line struct: modulo math plus warning on all endian-explicit formats for compatibility with older struct usage (ugly) ........ r46539 | bob.ippolito | 2006-05-30 02:26:01 +0200 (Tue, 30 May 2006) | 1 line Add a length check to aifc to ensure it doesn't write a bogus file ........ r46540 | tim.peters | 2006-05-30 04:25:25 +0200 (Tue, 30 May 2006) | 10 lines deprecated_err(): Stop bizarre warning messages when the tests are run in the order: test_genexps (or any other doctest-based test) test_struct test_doctest The `warnings` module needs an advertised way to save/restore its internal filter list. ........ r46541 | tim.peters | 2006-05-30 04:26:46 +0200 (Tue, 30 May 2006) | 2 lines Whitespace normalization. ........ r46542 | tim.peters | 2006-05-30 04:30:30 +0200 (Tue, 30 May 2006) | 2 lines Set a binary svn:mime-type property on this UTF-8 encoded file. ........ r46543 | neal.norwitz | 2006-05-30 05:18:50 +0200 (Tue, 30 May 2006) | 1 line Simplify further by using AddStringConstant ........ r46544 | tim.peters | 2006-05-30 06:16:25 +0200 (Tue, 30 May 2006) | 6 lines Convert relevant dict internals to Py_ssize_t. I don't have a box with nearly enough RAM, or an OS, that could get close to tickling this, though (requires a dict w/ at least 2**31 entries). ........ r46545 | neal.norwitz | 2006-05-30 06:19:21 +0200 (Tue, 30 May 2006) | 1 line Remove stray | in comment ........ r46546 | neal.norwitz | 2006-05-30 06:25:05 +0200 (Tue, 30 May 2006) | 1 line Use Py_SAFE_DOWNCAST for safety. Fix format strings. Remove 2 more stray | in comment ........ r46547 | neal.norwitz | 2006-05-30 06:43:23 +0200 (Tue, 30 May 2006) | 1 line No DOWNCAST is required since sizeof(Py_ssize_t) >= sizeof(int) and Py_ReprEntr returns an int ........ r46548 | tim.peters | 2006-05-30 07:04:59 +0200 (Tue, 30 May 2006) | 3 lines dict_print(): Explicitly narrow the return value from a (possibly) wider variable. ........ r46549 | tim.peters | 2006-05-30 07:23:59 +0200 (Tue, 30 May 2006) | 5 lines dict_print(): So that Neal & I don't spend the rest of our lives taking turns rewriting code that works ;-), get rid of casting illusions by declaring a new variable with the obvious type. ........ r46550 | georg.brandl | 2006-05-30 09:04:55 +0200 (Tue, 30 May 2006) | 3 lines Restore exception pickle support. #1497319. ........ r46551 | georg.brandl | 2006-05-30 09:13:29 +0200 (Tue, 30 May 2006) | 3 lines Add a test case for exception pickling. args is never NULL. ........ r46552 | neal.norwitz | 2006-05-30 09:21:10 +0200 (Tue, 30 May 2006) | 1 line Don't fail if the (sub)pkgname already exist. ........ r46553 | georg.brandl | 2006-05-30 09:34:45 +0200 (Tue, 30 May 2006) | 3 lines Disallow keyword args for exceptions. ........ r46554 | neal.norwitz | 2006-05-30 09:36:54 +0200 (Tue, 30 May 2006) | 5 lines I'm impatient. I think this will fix a few more problems with the buildbots. I'm not sure this is the best approach, but I can't think of anything better. If this creates problems, feel free to revert, but I think it's safe and should make things a little better. ........ r46555 | georg.brandl | 2006-05-30 10:17:00 +0200 (Tue, 30 May 2006) | 4 lines Do the check for no keyword arguments in __init__ so that subclasses of Exception can be supplied keyword args ........ r46556 | georg.brandl | 2006-05-30 10:47:19 +0200 (Tue, 30 May 2006) | 3 lines Convert test_exceptions to unittest. ........ r46557 | andrew.kuchling | 2006-05-30 14:52:01 +0200 (Tue, 30 May 2006) | 1 line Add SoC name, and reorganize this section a bit ........ r46559 | tim.peters | 2006-05-30 17:53:34 +0200 (Tue, 30 May 2006) | 11 lines PyLong_FromString(): Continued fraction analysis (explained in a new comment) suggests there are almost certainly large input integers in all non-binary input bases for which one Python digit too few is initally allocated to hold the final result. Instead of assert-failing when that happens, allocate more space. Alas, I estimate it would take a few days to find a specific such case, so this isn't backed up by a new test (not to mention that such a case may take hours to run, since conversion time is quadratic in the number of digits, and preliminary attempts suggested that the smallest such inputs contain at least a million digits). ........ r46560 | fredrik.lundh | 2006-05-30 19:11:48 +0200 (Tue, 30 May 2006) | 3 lines changed find/rfind to return -1 for matches outside the source string ........ r46561 | bob.ippolito | 2006-05-30 19:37:54 +0200 (Tue, 30 May 2006) | 1 line Change wrapping terminology to overflow masking ........ r46562 | fredrik.lundh | 2006-05-30 19:39:58 +0200 (Tue, 30 May 2006) | 3 lines changed count to return 0 for slices outside the source string ........ r46568 | tim.peters | 2006-05-31 01:28:02 +0200 (Wed, 31 May 2006) | 2 lines Whitespace normalization. ........ r46569 | brett.cannon | 2006-05-31 04:19:54 +0200 (Wed, 31 May 2006) | 5 lines Clarify wording on default values for strptime(); defaults are used when better values cannot be inferred. Closes bug #1496315. ........ r46572 | neal.norwitz | 2006-05-31 09:43:27 +0200 (Wed, 31 May 2006) | 1 line Calculate smallest properly (it was off by one) and use proper ssize_t types for Win64 ........ r46573 | neal.norwitz | 2006-05-31 10:01:08 +0200 (Wed, 31 May 2006) | 1 line Revert last checkin, it is better to do make distclean ........ r46574 | neal.norwitz | 2006-05-31 11:02:44 +0200 (Wed, 31 May 2006) | 3 lines On 64-bit platforms running test_struct after test_tarfile would fail since the deprecation warning wouldn't be raised. ........ r46575 | thomas.heller | 2006-05-31 13:37:58 +0200 (Wed, 31 May 2006) | 3 lines PyTuple_Pack is not available in Python 2.3, but ctypes must stay compatible with that. ........ r46576 | andrew.kuchling | 2006-05-31 15:18:56 +0200 (Wed, 31 May 2006) | 1 line 'functional' module was renamed to 'functools' ........ r46577 | kristjan.jonsson | 2006-05-31 15:35:41 +0200 (Wed, 31 May 2006) | 1 line Fixup the PCBuild8 project directory. exceptions.c have moved to Objects, and the functionalmodule.c has been replaced with _functoolsmodule.c. Other minor changes to .vcproj files and .sln to fix compilation ........ r46578 | andrew.kuchling | 2006-05-31 16:08:48 +0200 (Wed, 31 May 2006) | 15 lines [Bug #1473048] SimpleXMLRPCServer and DocXMLRPCServer don't look at the path of the HTTP request at all; you can POST or GET from / or /RPC2 or /blahblahblah with the same results. Security scanners that look for /cgi-bin/phf will therefore report lots of vulnerabilities. Fix: add a .rpc_paths attribute to the SimpleXMLRPCServer class, and report a 404 error if the path isn't on the allowed list. Possibly-controversial aspect of this change: the default makes only '/' and '/RPC2' legal. Maybe this will break people's applications (though I doubt it). We could just set the default to an empty tuple, which would exactly match the current behaviour. ........ r46579 | andrew.kuchling | 2006-05-31 16:12:47 +0200 (Wed, 31 May 2006) | 1 line Mention SimpleXMLRPCServer change ........ r46580 | tim.peters | 2006-05-31 16:28:07 +0200 (Wed, 31 May 2006) | 2 lines Trimmed trailing whitespace. ........ r46581 | tim.peters | 2006-05-31 17:33:22 +0200 (Wed, 31 May 2006) | 4 lines _range_error(): Speed and simplify (there's no real need for loops here). Assert that size_t is actually big enough, and that f->size is at least one. Wrap a long line. ........ r46582 | tim.peters | 2006-05-31 17:34:37 +0200 (Wed, 31 May 2006) | 2 lines Repaired error in new comment. ........ r46584 | neal.norwitz | 2006-06-01 07:32:49 +0200 (Thu, 01 Jun 2006) | 4 lines Remove ; at end of macro. There was a compiler recently that warned about extra semi-colons. It may have been the HP C compiler. This file will trigger a bunch of those warnings now. ........ r46585 | georg.brandl | 2006-06-01 08:39:19 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly unpickle 2.4 exceptions via __setstate__ (patch #1498571) ........ r46586 | georg.brandl | 2006-06-01 10:27:32 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly allocate complex types with tp_alloc. (bug #1498638) ........ r46587 | georg.brandl | 2006-06-01 14:30:46 +0200 (Thu, 01 Jun 2006) | 2 lines Correctly dispatch Faults in loads (patch #1498627) ........ r46588 | georg.brandl | 2006-06-01 15:00:49 +0200 (Thu, 01 Jun 2006) | 3 lines Some code style tweaks, and remove apply. ........ r46589 | armin.rigo | 2006-06-01 15:19:12 +0200 (Thu, 01 Jun 2006) | 5 lines [ 1497053 ] Let dicts propagate the exceptions in user __eq__(). [ 1456209 ] dictresize() vulnerability ( <- backport candidate ). ........ r46590 | tim.peters | 2006-06-01 15:41:46 +0200 (Thu, 01 Jun 2006) | 2 lines Whitespace normalization. ........ r46591 | tim.peters | 2006-06-01 15:49:23 +0200 (Thu, 01 Jun 2006) | 2 lines Record bugs 1275608 and 1456209 as being fixed. ........ r46592 | tim.peters | 2006-06-01 15:56:26 +0200 (Thu, 01 Jun 2006) | 5 lines Re-enable a new empty-string test added during the NFS sprint, but disabled then because str and unicode strings gave different results. The implementations were repaired later during the sprint, but the new test remained disabled. ........ r46594 | tim.peters | 2006-06-01 17:50:44 +0200 (Thu, 01 Jun 2006) | 7 lines Armin committed his patch while I was reviewing it (I'm sure he didn't know this), so merged in some changes I made during review. Nothing material apart from changing a new `mask` local from int to Py_ssize_t. Mostly this is repairing comments that were made incorrect, and adding new comments. Also a few minor code rewrites for clarity or helpful succinctness. ........ r46599 | neal.norwitz | 2006-06-02 06:45:53 +0200 (Fri, 02 Jun 2006) | 1 line Convert docstrings to comments so regrtest -v prints method names ........ r46600 | neal.norwitz | 2006-06-02 06:50:49 +0200 (Fri, 02 Jun 2006) | 2 lines Fix memory leak found by valgrind. ........ r46601 | neal.norwitz | 2006-06-02 06:54:52 +0200 (Fri, 02 Jun 2006) | 1 line More memory leaks from valgrind ........ r46602 | neal.norwitz | 2006-06-02 08:23:00 +0200 (Fri, 02 Jun 2006) | 11 lines Patch #1357836: Prevent an invalid memory read from test_coding in case the done flag is set. In that case, the loop isn't entered. I wonder if rather than setting the done flag in the cases before the loop, if they should just exit early. This code looks like it should be refactored. Backport candidate (also the early break above if decoding_fgets fails) ........ r46603 | martin.blais | 2006-06-02 15:03:43 +0200 (Fri, 02 Jun 2006) | 1 line Fixed struct test to not use unittest. ........ r46605 | tim.peters | 2006-06-03 01:22:51 +0200 (Sat, 03 Jun 2006) | 10 lines pprint functions used to sort a dict (by key) if and only if the output required more than one line. "Small" dicts got displayed in seemingly random order (the hash-induced order produced by dict.__repr__). None of this was documented. Now pprint functions always sort dicts by key, and the docs promise it. This was proposed and agreed to during the PyCon 2006 core sprint -- I just didn't have time for it before now. ........
20 years ago
  1. """Stuff to parse AIFF-C and AIFF files.
  2. Unless explicitly stated otherwise, the description below is true
  3. both for AIFF-C files and AIFF files.
  4. An AIFF-C file has the following structure.
  5. +-----------------+
  6. | FORM |
  7. +-----------------+
  8. | <size> |
  9. +----+------------+
  10. | | AIFC |
  11. | +------------+
  12. | | <chunks> |
  13. | | . |
  14. | | . |
  15. | | . |
  16. +----+------------+
  17. An AIFF file has the string "AIFF" instead of "AIFC".
  18. A chunk consists of an identifier (4 bytes) followed by a size (4 bytes,
  19. big endian order), followed by the data. The size field does not include
  20. the size of the 8 byte header.
  21. The following chunk types are recognized.
  22. FVER
  23. <version number of AIFF-C defining document> (AIFF-C only).
  24. MARK
  25. <# of markers> (2 bytes)
  26. list of markers:
  27. <marker ID> (2 bytes, must be > 0)
  28. <position> (4 bytes)
  29. <marker name> ("pstring")
  30. COMM
  31. <# of channels> (2 bytes)
  32. <# of sound frames> (4 bytes)
  33. <size of the samples> (2 bytes)
  34. <sampling frequency> (10 bytes, IEEE 80-bit extended
  35. floating point)
  36. in AIFF-C files only:
  37. <compression type> (4 bytes)
  38. <human-readable version of compression type> ("pstring")
  39. SSND
  40. <offset> (4 bytes, not used by this program)
  41. <blocksize> (4 bytes, not used by this program)
  42. <sound data>
  43. A pstring consists of 1 byte length, a string of characters, and 0 or 1
  44. byte pad to make the total length even.
  45. Usage.
  46. Reading AIFF files:
  47. f = aifc.open(file, 'r')
  48. where file is either the name of a file or an open file pointer.
  49. The open file pointer must have methods read(), seek(), and close().
  50. In some types of audio files, if the setpos() method is not used,
  51. the seek() method is not necessary.
  52. This returns an instance of a class with the following public methods:
  53. getnchannels() -- returns number of audio channels (1 for
  54. mono, 2 for stereo)
  55. getsampwidth() -- returns sample width in bytes
  56. getframerate() -- returns sampling frequency
  57. getnframes() -- returns number of audio frames
  58. getcomptype() -- returns compression type ('NONE' for AIFF files)
  59. getcompname() -- returns human-readable version of
  60. compression type ('not compressed' for AIFF files)
  61. getparams() -- returns a tuple consisting of all of the
  62. above in the above order
  63. getmarkers() -- get the list of marks in the audio file or None
  64. if there are no marks
  65. getmark(id) -- get mark with the specified id (raises an error
  66. if the mark does not exist)
  67. readframes(n) -- returns at most n frames of audio
  68. rewind() -- rewind to the beginning of the audio stream
  69. setpos(pos) -- seek to the specified position
  70. tell() -- return the current position
  71. close() -- close the instance (make it unusable)
  72. The position returned by tell(), the position given to setpos() and
  73. the position of marks are all compatible and have nothing to do with
  74. the actual position in the file.
  75. The close() method is called automatically when the class instance
  76. is destroyed.
  77. Writing AIFF files:
  78. f = aifc.open(file, 'w')
  79. where file is either the name of a file or an open file pointer.
  80. The open file pointer must have methods write(), tell(), seek(), and
  81. close().
  82. This returns an instance of a class with the following public methods:
  83. aiff() -- create an AIFF file (AIFF-C default)
  84. aifc() -- create an AIFF-C file
  85. setnchannels(n) -- set the number of channels
  86. setsampwidth(n) -- set the sample width
  87. setframerate(n) -- set the frame rate
  88. setnframes(n) -- set the number of frames
  89. setcomptype(type, name)
  90. -- set the compression type and the
  91. human-readable compression type
  92. setparams(tuple)
  93. -- set all parameters at once
  94. setmark(id, pos, name)
  95. -- add specified mark to the list of marks
  96. tell() -- return current position in output file (useful
  97. in combination with setmark())
  98. writeframesraw(data)
  99. -- write audio frames without pathing up the
  100. file header
  101. writeframes(data)
  102. -- write audio frames and patch up the file header
  103. close() -- patch up the file header and close the
  104. output file
  105. You should set the parameters before the first writeframesraw or
  106. writeframes. The total number of frames does not need to be set,
  107. but when it is set to the correct value, the header does not have to
  108. be patched up.
  109. It is best to first set all parameters, perhaps possibly the
  110. compression type, and then write audio frames using writeframesraw.
  111. When all frames have been written, either call writeframes('') or
  112. close() to patch up the sizes in the header.
  113. Marks can be added anytime. If there are any marks, ypu must call
  114. close() after all frames have been written.
  115. The close() method is called automatically when the class instance
  116. is destroyed.
  117. When a file is opened with the extension '.aiff', an AIFF file is
  118. written, otherwise an AIFF-C file is written. This default can be
  119. changed by calling aiff() or aifc() before the first writeframes or
  120. writeframesraw.
  121. """
  122. import struct
  123. import builtins
  124. __all__ = ["Error", "open", "openfp"]
  125. class Error(Exception):
  126. pass
  127. _AIFC_version = 0xA2805140 # Version 1 of AIFF-C
  128. def _read_long(file):
  129. try:
  130. return struct.unpack('>l', file.read(4))[0]
  131. except struct.error:
  132. raise EOFError
  133. def _read_ulong(file):
  134. try:
  135. return struct.unpack('>L', file.read(4))[0]
  136. except struct.error:
  137. raise EOFError
  138. def _read_short(file):
  139. try:
  140. return struct.unpack('>h', file.read(2))[0]
  141. except struct.error:
  142. raise EOFError
  143. def _read_ushort(file):
  144. try:
  145. return struct.unpack('>H', file.read(2))[0]
  146. except struct.error:
  147. raise EOFError
  148. def _read_string(file):
  149. length = ord(file.read(1))
  150. if length == 0:
  151. data = b''
  152. else:
  153. data = file.read(length)
  154. if length & 1 == 0:
  155. dummy = file.read(1)
  156. return data
  157. _HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
  158. def _read_float(f): # 10 bytes
  159. expon = _read_short(f) # 2 bytes
  160. sign = 1
  161. if expon < 0:
  162. sign = -1
  163. expon = expon + 0x8000
  164. himant = _read_ulong(f) # 4 bytes
  165. lomant = _read_ulong(f) # 4 bytes
  166. if expon == himant == lomant == 0:
  167. f = 0.0
  168. elif expon == 0x7FFF:
  169. f = _HUGE_VAL
  170. else:
  171. expon = expon - 16383
  172. f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63)
  173. return sign * f
  174. def _write_short(f, x):
  175. f.write(struct.pack('>h', x))
  176. def _write_ushort(f, x):
  177. f.write(struct.pack('>H', x))
  178. def _write_long(f, x):
  179. f.write(struct.pack('>l', x))
  180. def _write_ulong(f, x):
  181. f.write(struct.pack('>L', x))
  182. def _write_string(f, s):
  183. if len(s) > 255:
  184. raise ValueError("string exceeds maximum pstring length")
  185. f.write(struct.pack('B', len(s)))
  186. f.write(s)
  187. if len(s) & 1 == 0:
  188. f.write(b'\x00')
  189. def _write_float(f, x):
  190. import math
  191. if x < 0:
  192. sign = 0x8000
  193. x = x * -1
  194. else:
  195. sign = 0
  196. if x == 0:
  197. expon = 0
  198. himant = 0
  199. lomant = 0
  200. else:
  201. fmant, expon = math.frexp(x)
  202. if expon > 16384 or fmant >= 1 or fmant != fmant: # Infinity or NaN
  203. expon = sign|0x7FFF
  204. himant = 0
  205. lomant = 0
  206. else: # Finite
  207. expon = expon + 16382
  208. if expon < 0: # denormalized
  209. fmant = math.ldexp(fmant, expon)
  210. expon = 0
  211. expon = expon | sign
  212. fmant = math.ldexp(fmant, 32)
  213. fsmant = math.floor(fmant)
  214. himant = int(fsmant)
  215. fmant = math.ldexp(fmant - fsmant, 32)
  216. fsmant = math.floor(fmant)
  217. lomant = int(fsmant)
  218. _write_ushort(f, expon)
  219. _write_ulong(f, himant)
  220. _write_ulong(f, lomant)
  221. from chunk import Chunk
  222. class Aifc_read:
  223. # Variables used in this class:
  224. #
  225. # These variables are available to the user though appropriate
  226. # methods of this class:
  227. # _file -- the open file with methods read(), close(), and seek()
  228. # set through the __init__() method
  229. # _nchannels -- the number of audio channels
  230. # available through the getnchannels() method
  231. # _nframes -- the number of audio frames
  232. # available through the getnframes() method
  233. # _sampwidth -- the number of bytes per audio sample
  234. # available through the getsampwidth() method
  235. # _framerate -- the sampling frequency
  236. # available through the getframerate() method
  237. # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
  238. # available through the getcomptype() method
  239. # _compname -- the human-readable AIFF-C compression type
  240. # available through the getcomptype() method
  241. # _markers -- the marks in the audio file
  242. # available through the getmarkers() and getmark()
  243. # methods
  244. # _soundpos -- the position in the audio stream
  245. # available through the tell() method, set through the
  246. # setpos() method
  247. #
  248. # These variables are used internally only:
  249. # _version -- the AIFF-C version number
  250. # _decomp -- the decompressor from builtin module cl
  251. # _comm_chunk_read -- 1 iff the COMM chunk has been read
  252. # _aifc -- 1 iff reading an AIFF-C file
  253. # _ssnd_seek_needed -- 1 iff positioned correctly in audio
  254. # file for readframes()
  255. # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
  256. # _framesize -- size of one frame in the file
  257. def initfp(self, file):
  258. self._version = 0
  259. self._convert = None
  260. self._markers = []
  261. self._soundpos = 0
  262. self._file = file
  263. chunk = Chunk(file)
  264. if chunk.getname() != b'FORM':
  265. raise Error('file does not start with FORM id')
  266. formdata = chunk.read(4)
  267. if formdata == b'AIFF':
  268. self._aifc = 0
  269. elif formdata == b'AIFC':
  270. self._aifc = 1
  271. else:
  272. raise Error('not an AIFF or AIFF-C file')
  273. self._comm_chunk_read = 0
  274. while 1:
  275. self._ssnd_seek_needed = 1
  276. try:
  277. chunk = Chunk(self._file)
  278. except EOFError:
  279. break
  280. chunkname = chunk.getname()
  281. if chunkname == b'COMM':
  282. self._read_comm_chunk(chunk)
  283. self._comm_chunk_read = 1
  284. elif chunkname == b'SSND':
  285. self._ssnd_chunk = chunk
  286. dummy = chunk.read(8)
  287. self._ssnd_seek_needed = 0
  288. elif chunkname == b'FVER':
  289. self._version = _read_ulong(chunk)
  290. elif chunkname == b'MARK':
  291. self._readmark(chunk)
  292. chunk.skip()
  293. if not self._comm_chunk_read or not self._ssnd_chunk:
  294. raise Error('COMM chunk and/or SSND chunk missing')
  295. def __init__(self, f):
  296. if isinstance(f, str):
  297. f = builtins.open(f, 'rb')
  298. # else, assume it is an open file object already
  299. self.initfp(f)
  300. #
  301. # User visible methods.
  302. #
  303. def getfp(self):
  304. return self._file
  305. def rewind(self):
  306. self._ssnd_seek_needed = 1
  307. self._soundpos = 0
  308. def close(self):
  309. self._file.close()
  310. def tell(self):
  311. return self._soundpos
  312. def getnchannels(self):
  313. return self._nchannels
  314. def getnframes(self):
  315. return self._nframes
  316. def getsampwidth(self):
  317. return self._sampwidth
  318. def getframerate(self):
  319. return self._framerate
  320. def getcomptype(self):
  321. return self._comptype
  322. def getcompname(self):
  323. return self._compname
  324. ## def getversion(self):
  325. ## return self._version
  326. def getparams(self):
  327. return self.getnchannels(), self.getsampwidth(), \
  328. self.getframerate(), self.getnframes(), \
  329. self.getcomptype(), self.getcompname()
  330. def getmarkers(self):
  331. if len(self._markers) == 0:
  332. return None
  333. return self._markers
  334. def getmark(self, id):
  335. for marker in self._markers:
  336. if id == marker[0]:
  337. return marker
  338. raise Error('marker {0!r} does not exist'.format(id))
  339. def setpos(self, pos):
  340. if pos < 0 or pos > self._nframes:
  341. raise Error('position not in range')
  342. self._soundpos = pos
  343. self._ssnd_seek_needed = 1
  344. def readframes(self, nframes):
  345. if self._ssnd_seek_needed:
  346. self._ssnd_chunk.seek(0)
  347. dummy = self._ssnd_chunk.read(8)
  348. pos = self._soundpos * self._framesize
  349. if pos:
  350. self._ssnd_chunk.seek(pos + 8)
  351. self._ssnd_seek_needed = 0
  352. if nframes == 0:
  353. return b''
  354. data = self._ssnd_chunk.read(nframes * self._framesize)
  355. if self._convert and data:
  356. data = self._convert(data)
  357. self._soundpos = self._soundpos + len(data) // (self._nchannels
  358. * self._sampwidth)
  359. return data
  360. #
  361. # Internal methods.
  362. #
  363. def _alaw2lin(self, data):
  364. import audioop
  365. return audioop.alaw2lin(data, 2)
  366. def _ulaw2lin(self, data):
  367. import audioop
  368. return audioop.ulaw2lin(data, 2)
  369. def _adpcm2lin(self, data):
  370. import audioop
  371. if not hasattr(self, '_adpcmstate'):
  372. # first time
  373. self._adpcmstate = None
  374. data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate)
  375. return data
  376. def _read_comm_chunk(self, chunk):
  377. self._nchannels = _read_short(chunk)
  378. self._nframes = _read_long(chunk)
  379. self._sampwidth = (_read_short(chunk) + 7) // 8
  380. self._framerate = int(_read_float(chunk))
  381. self._framesize = self._nchannels * self._sampwidth
  382. if self._aifc:
  383. #DEBUG: SGI's soundeditor produces a bad size :-(
  384. kludge = 0
  385. if chunk.chunksize == 18:
  386. kludge = 1
  387. print('Warning: bad COMM chunk size')
  388. chunk.chunksize = 23
  389. #DEBUG end
  390. self._comptype = chunk.read(4)
  391. #DEBUG start
  392. if kludge:
  393. length = ord(chunk.file.read(1))
  394. if length & 1 == 0:
  395. length = length + 1
  396. chunk.chunksize = chunk.chunksize + length
  397. chunk.file.seek(-1, 1)
  398. #DEBUG end
  399. self._compname = _read_string(chunk)
  400. if self._comptype != b'NONE':
  401. if self._comptype == b'G722':
  402. self._convert = self._adpcm2lin
  403. self._framesize = self._framesize // 4
  404. elif self._comptype in (b'ulaw', b'ULAW'):
  405. self._convert = self._ulaw2lin
  406. self._framesize = self._framesize // 2
  407. elif self._comptype in (b'alaw', b'ALAW'):
  408. self._convert = self._alaw2lin
  409. self._framesize = self._framesize // 2
  410. else:
  411. raise Error('unsupported compression type')
  412. else:
  413. self._comptype = b'NONE'
  414. self._compname = b'not compressed'
  415. def _readmark(self, chunk):
  416. nmarkers = _read_short(chunk)
  417. # Some files appear to contain invalid counts.
  418. # Cope with this by testing for EOF.
  419. try:
  420. for i in range(nmarkers):
  421. id = _read_short(chunk)
  422. pos = _read_long(chunk)
  423. name = _read_string(chunk)
  424. if pos or name:
  425. # some files appear to have
  426. # dummy markers consisting of
  427. # a position 0 and name ''
  428. self._markers.append((id, pos, name))
  429. except EOFError:
  430. print('Warning: MARK chunk contains only', end=' ')
  431. print(len(self._markers), end=' ')
  432. if len(self._markers) == 1: print('marker', end=' ')
  433. else: print('markers', end=' ')
  434. print('instead of', nmarkers)
  435. class Aifc_write:
  436. # Variables used in this class:
  437. #
  438. # These variables are user settable through appropriate methods
  439. # of this class:
  440. # _file -- the open file with methods write(), close(), tell(), seek()
  441. # set through the __init__() method
  442. # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
  443. # set through the setcomptype() or setparams() method
  444. # _compname -- the human-readable AIFF-C compression type
  445. # set through the setcomptype() or setparams() method
  446. # _nchannels -- the number of audio channels
  447. # set through the setnchannels() or setparams() method
  448. # _sampwidth -- the number of bytes per audio sample
  449. # set through the setsampwidth() or setparams() method
  450. # _framerate -- the sampling frequency
  451. # set through the setframerate() or setparams() method
  452. # _nframes -- the number of audio frames written to the header
  453. # set through the setnframes() or setparams() method
  454. # _aifc -- whether we're writing an AIFF-C file or an AIFF file
  455. # set through the aifc() method, reset through the
  456. # aiff() method
  457. #
  458. # These variables are used internally only:
  459. # _version -- the AIFF-C version number
  460. # _comp -- the compressor from builtin module cl
  461. # _nframeswritten -- the number of audio frames actually written
  462. # _datalength -- the size of the audio samples written to the header
  463. # _datawritten -- the size of the audio samples actually written
  464. def __init__(self, f):
  465. if isinstance(f, str):
  466. filename = f
  467. f = builtins.open(f, 'wb')
  468. else:
  469. # else, assume it is an open file object already
  470. filename = '???'
  471. self.initfp(f)
  472. if filename[-5:] == '.aiff':
  473. self._aifc = 0
  474. else:
  475. self._aifc = 1
  476. def initfp(self, file):
  477. self._file = file
  478. self._version = _AIFC_version
  479. self._comptype = b'NONE'
  480. self._compname = b'not compressed'
  481. self._convert = None
  482. self._nchannels = 0
  483. self._sampwidth = 0
  484. self._framerate = 0
  485. self._nframes = 0
  486. self._nframeswritten = 0
  487. self._datawritten = 0
  488. self._datalength = 0
  489. self._markers = []
  490. self._marklength = 0
  491. self._aifc = 1 # AIFF-C is default
  492. def __del__(self):
  493. self.close()
  494. #
  495. # User visible methods.
  496. #
  497. def aiff(self):
  498. if self._nframeswritten:
  499. raise Error('cannot change parameters after starting to write')
  500. self._aifc = 0
  501. def aifc(self):
  502. if self._nframeswritten:
  503. raise Error('cannot change parameters after starting to write')
  504. self._aifc = 1
  505. def setnchannels(self, nchannels):
  506. if self._nframeswritten:
  507. raise Error('cannot change parameters after starting to write')
  508. if nchannels < 1:
  509. raise Error('bad # of channels')
  510. self._nchannels = nchannels
  511. def getnchannels(self):
  512. if not self._nchannels:
  513. raise Error('number of channels not set')
  514. return self._nchannels
  515. def setsampwidth(self, sampwidth):
  516. if self._nframeswritten:
  517. raise Error('cannot change parameters after starting to write')
  518. if sampwidth < 1 or sampwidth > 4:
  519. raise Error('bad sample width')
  520. self._sampwidth = sampwidth
  521. def getsampwidth(self):
  522. if not self._sampwidth:
  523. raise Error('sample width not set')
  524. return self._sampwidth
  525. def setframerate(self, framerate):
  526. if self._nframeswritten:
  527. raise Error('cannot change parameters after starting to write')
  528. if framerate <= 0:
  529. raise Error('bad frame rate')
  530. self._framerate = framerate
  531. def getframerate(self):
  532. if not self._framerate:
  533. raise Error('frame rate not set')
  534. return self._framerate
  535. def setnframes(self, nframes):
  536. if self._nframeswritten:
  537. raise Error('cannot change parameters after starting to write')
  538. self._nframes = nframes
  539. def getnframes(self):
  540. return self._nframeswritten
  541. def setcomptype(self, comptype, compname):
  542. if self._nframeswritten:
  543. raise Error('cannot change parameters after starting to write')
  544. if comptype not in (b'NONE', b'ulaw', b'ULAW',
  545. b'alaw', b'ALAW', b'G722'):
  546. raise Error('unsupported compression type')
  547. self._comptype = comptype
  548. self._compname = compname
  549. def getcomptype(self):
  550. return self._comptype
  551. def getcompname(self):
  552. return self._compname
  553. ## def setversion(self, version):
  554. ## if self._nframeswritten:
  555. ## raise Error, 'cannot change parameters after starting to write'
  556. ## self._version = version
  557. def setparams(self, params):
  558. nchannels, sampwidth, framerate, nframes, comptype, compname = params
  559. if self._nframeswritten:
  560. raise Error('cannot change parameters after starting to write')
  561. if comptype not in (b'NONE', b'ulaw', b'ULAW',
  562. b'alaw', b'ALAW', b'G722'):
  563. raise Error('unsupported compression type')
  564. self.setnchannels(nchannels)
  565. self.setsampwidth(sampwidth)
  566. self.setframerate(framerate)
  567. self.setnframes(nframes)
  568. self.setcomptype(comptype, compname)
  569. def getparams(self):
  570. if not self._nchannels or not self._sampwidth or not self._framerate:
  571. raise Error('not all parameters set')
  572. return self._nchannels, self._sampwidth, self._framerate, \
  573. self._nframes, self._comptype, self._compname
  574. def setmark(self, id, pos, name):
  575. if id <= 0:
  576. raise Error('marker ID must be > 0')
  577. if pos < 0:
  578. raise Error('marker position must be >= 0')
  579. if not isinstance(name, bytes):
  580. raise Error('marker name must be bytes')
  581. for i in range(len(self._markers)):
  582. if id == self._markers[i][0]:
  583. self._markers[i] = id, pos, name
  584. return
  585. self._markers.append((id, pos, name))
  586. def getmark(self, id):
  587. for marker in self._markers:
  588. if id == marker[0]:
  589. return marker
  590. raise Error('marker {0!r} does not exist'.format(id))
  591. def getmarkers(self):
  592. if len(self._markers) == 0:
  593. return None
  594. return self._markers
  595. def tell(self):
  596. return self._nframeswritten
  597. def writeframesraw(self, data):
  598. self._ensure_header_written(len(data))
  599. nframes = len(data) // (self._sampwidth * self._nchannels)
  600. if self._convert:
  601. data = self._convert(data)
  602. self._file.write(data)
  603. self._nframeswritten = self._nframeswritten + nframes
  604. self._datawritten = self._datawritten + len(data)
  605. def writeframes(self, data):
  606. self.writeframesraw(data)
  607. if self._nframeswritten != self._nframes or \
  608. self._datalength != self._datawritten:
  609. self._patchheader()
  610. def close(self):
  611. if self._file:
  612. self._ensure_header_written(0)
  613. if self._datawritten & 1:
  614. # quick pad to even size
  615. self._file.write(b'\x00')
  616. self._datawritten = self._datawritten + 1
  617. self._writemarkers()
  618. if self._nframeswritten != self._nframes or \
  619. self._datalength != self._datawritten or \
  620. self._marklength:
  621. self._patchheader()
  622. # Prevent ref cycles
  623. self._convert = None
  624. self._file.close()
  625. self._file = None
  626. #
  627. # Internal methods.
  628. #
  629. def _lin2alaw(self, data):
  630. import audioop
  631. return audioop.lin2alaw(data, 2)
  632. def _lin2ulaw(self, data):
  633. import audioop
  634. return audioop.lin2ulaw(data, 2)
  635. def _lin2adpcm(self, data):
  636. import audioop
  637. if not hasattr(self, '_adpcmstate'):
  638. self._adpcmstate = None
  639. data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate)
  640. return data
  641. def _ensure_header_written(self, datasize):
  642. if not self._nframeswritten:
  643. if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'):
  644. if not self._sampwidth:
  645. self._sampwidth = 2
  646. if self._sampwidth != 2:
  647. raise Error('sample width must be 2 when compressing '
  648. 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)')
  649. if not self._nchannels:
  650. raise Error('# channels not specified')
  651. if not self._sampwidth:
  652. raise Error('sample width not specified')
  653. if not self._framerate:
  654. raise Error('sampling rate not specified')
  655. self._write_header(datasize)
  656. def _init_compression(self):
  657. if self._comptype == b'G722':
  658. self._convert = self._lin2adpcm
  659. elif self._comptype in (b'ulaw', b'ULAW'):
  660. self._convert = self._lin2ulaw
  661. elif self._comptype in (b'alaw', b'ALAW'):
  662. self._convert = self._lin2alaw
  663. def _write_header(self, initlength):
  664. if self._aifc and self._comptype != b'NONE':
  665. self._init_compression()
  666. self._file.write(b'FORM')
  667. if not self._nframes:
  668. self._nframes = initlength // (self._nchannels * self._sampwidth)
  669. self._datalength = self._nframes * self._nchannels * self._sampwidth
  670. if self._datalength & 1:
  671. self._datalength = self._datalength + 1
  672. if self._aifc:
  673. if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'):
  674. self._datalength = self._datalength // 2
  675. if self._datalength & 1:
  676. self._datalength = self._datalength + 1
  677. elif self._comptype == b'G722':
  678. self._datalength = (self._datalength + 3) // 4
  679. if self._datalength & 1:
  680. self._datalength = self._datalength + 1
  681. self._form_length_pos = self._file.tell()
  682. commlength = self._write_form_length(self._datalength)
  683. if self._aifc:
  684. self._file.write(b'AIFC')
  685. self._file.write(b'FVER')
  686. _write_ulong(self._file, 4)
  687. _write_ulong(self._file, self._version)
  688. else:
  689. self._file.write(b'AIFF')
  690. self._file.write(b'COMM')
  691. _write_ulong(self._file, commlength)
  692. _write_short(self._file, self._nchannels)
  693. self._nframes_pos = self._file.tell()
  694. _write_ulong(self._file, self._nframes)
  695. _write_short(self._file, self._sampwidth * 8)
  696. _write_float(self._file, self._framerate)
  697. if self._aifc:
  698. self._file.write(self._comptype)
  699. _write_string(self._file, self._compname)
  700. self._file.write(b'SSND')
  701. self._ssnd_length_pos = self._file.tell()
  702. _write_ulong(self._file, self._datalength + 8)
  703. _write_ulong(self._file, 0)
  704. _write_ulong(self._file, 0)
  705. def _write_form_length(self, datalength):
  706. if self._aifc:
  707. commlength = 18 + 5 + len(self._compname)
  708. if commlength & 1:
  709. commlength = commlength + 1
  710. verslength = 12
  711. else:
  712. commlength = 18
  713. verslength = 0
  714. _write_ulong(self._file, 4 + verslength + self._marklength + \
  715. 8 + commlength + 16 + datalength)
  716. return commlength
  717. def _patchheader(self):
  718. curpos = self._file.tell()
  719. if self._datawritten & 1:
  720. datalength = self._datawritten + 1
  721. self._file.write(b'\x00')
  722. else:
  723. datalength = self._datawritten
  724. if datalength == self._datalength and \
  725. self._nframes == self._nframeswritten and \
  726. self._marklength == 0:
  727. self._file.seek(curpos, 0)
  728. return
  729. self._file.seek(self._form_length_pos, 0)
  730. dummy = self._write_form_length(datalength)
  731. self._file.seek(self._nframes_pos, 0)
  732. _write_ulong(self._file, self._nframeswritten)
  733. self._file.seek(self._ssnd_length_pos, 0)
  734. _write_ulong(self._file, datalength + 8)
  735. self._file.seek(curpos, 0)
  736. self._nframes = self._nframeswritten
  737. self._datalength = datalength
  738. def _writemarkers(self):
  739. if len(self._markers) == 0:
  740. return
  741. self._file.write(b'MARK')
  742. length = 2
  743. for marker in self._markers:
  744. id, pos, name = marker
  745. length = length + len(name) + 1 + 6
  746. if len(name) & 1 == 0:
  747. length = length + 1
  748. _write_ulong(self._file, length)
  749. self._marklength = length + 8
  750. _write_short(self._file, len(self._markers))
  751. for marker in self._markers:
  752. id, pos, name = marker
  753. _write_short(self._file, id)
  754. _write_ulong(self._file, pos)
  755. _write_string(self._file, name)
  756. def open(f, mode=None):
  757. if mode is None:
  758. if hasattr(f, 'mode'):
  759. mode = f.mode
  760. else:
  761. mode = 'rb'
  762. if mode in ('r', 'rb'):
  763. return Aifc_read(f)
  764. elif mode in ('w', 'wb'):
  765. return Aifc_write(f)
  766. else:
  767. raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
  768. openfp = open # B/W compatibility
  769. if __name__ == '__main__':
  770. import sys
  771. if not sys.argv[1:]:
  772. sys.argv.append('/usr/demos/data/audio/bach.aiff')
  773. fn = sys.argv[1]
  774. f = open(fn, 'r')
  775. print("Reading", fn)
  776. print("nchannels =", f.getnchannels())
  777. print("nframes =", f.getnframes())
  778. print("sampwidth =", f.getsampwidth())
  779. print("framerate =", f.getframerate())
  780. print("comptype =", f.getcomptype())
  781. print("compname =", f.getcompname())
  782. if sys.argv[2:]:
  783. gn = sys.argv[2]
  784. print("Writing", gn)
  785. g = open(gn, 'w')
  786. g.setparams(f.getparams())
  787. while 1:
  788. data = f.readframes(1024)
  789. if not data:
  790. break
  791. g.writeframes(data)
  792. g.close()
  793. f.close()
  794. print("Done.")