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.

886 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_string(file):
  144. length = ord(file.read(1))
  145. if length == 0:
  146. data = b''
  147. else:
  148. data = file.read(length)
  149. if length & 1 == 0:
  150. dummy = file.read(1)
  151. return data
  152. _HUGE_VAL = 1.79769313486231e+308 # See <limits.h>
  153. def _read_float(f): # 10 bytes
  154. expon = _read_short(f) # 2 bytes
  155. sign = 1
  156. if expon < 0:
  157. sign = -1
  158. expon = expon + 0x8000
  159. himant = _read_ulong(f) # 4 bytes
  160. lomant = _read_ulong(f) # 4 bytes
  161. if expon == himant == lomant == 0:
  162. f = 0.0
  163. elif expon == 0x7FFF:
  164. f = _HUGE_VAL
  165. else:
  166. expon = expon - 16383
  167. f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63)
  168. return sign * f
  169. def _write_short(f, x):
  170. f.write(struct.pack('>h', x))
  171. def _write_long(f, x):
  172. f.write(struct.pack('>L', x))
  173. def _write_string(f, s):
  174. if len(s) > 255:
  175. raise ValueError("string exceeds maximum pstring length")
  176. f.write(struct.pack('b', len(s)))
  177. f.write(s)
  178. if len(s) & 1 == 0:
  179. f.write(b'\x00')
  180. def _write_float(f, x):
  181. import math
  182. if x < 0:
  183. sign = 0x8000
  184. x = x * -1
  185. else:
  186. sign = 0
  187. if x == 0:
  188. expon = 0
  189. himant = 0
  190. lomant = 0
  191. else:
  192. fmant, expon = math.frexp(x)
  193. if expon > 16384 or fmant >= 1: # Infinity or NaN
  194. expon = sign|0x7FFF
  195. himant = 0
  196. lomant = 0
  197. else: # Finite
  198. expon = expon + 16382
  199. if expon < 0: # denormalized
  200. fmant = math.ldexp(fmant, expon)
  201. expon = 0
  202. expon = expon | sign
  203. fmant = math.ldexp(fmant, 32)
  204. fsmant = math.floor(fmant)
  205. himant = int(fsmant)
  206. fmant = math.ldexp(fmant - fsmant, 32)
  207. fsmant = math.floor(fmant)
  208. lomant = int(fsmant)
  209. _write_short(f, expon)
  210. _write_long(f, himant)
  211. _write_long(f, lomant)
  212. from chunk import Chunk
  213. class Aifc_read:
  214. # Variables used in this class:
  215. #
  216. # These variables are available to the user though appropriate
  217. # methods of this class:
  218. # _file -- the open file with methods read(), close(), and seek()
  219. # set through the __init__() method
  220. # _nchannels -- the number of audio channels
  221. # available through the getnchannels() method
  222. # _nframes -- the number of audio frames
  223. # available through the getnframes() method
  224. # _sampwidth -- the number of bytes per audio sample
  225. # available through the getsampwidth() method
  226. # _framerate -- the sampling frequency
  227. # available through the getframerate() method
  228. # _comptype -- the AIFF-C compression type ('NONE' if AIFF)
  229. # available through the getcomptype() method
  230. # _compname -- the human-readable AIFF-C compression type
  231. # available through the getcomptype() method
  232. # _markers -- the marks in the audio file
  233. # available through the getmarkers() and getmark()
  234. # methods
  235. # _soundpos -- the position in the audio stream
  236. # available through the tell() method, set through the
  237. # setpos() method
  238. #
  239. # These variables are used internally only:
  240. # _version -- the AIFF-C version number
  241. # _decomp -- the decompressor from builtin module cl
  242. # _comm_chunk_read -- 1 iff the COMM chunk has been read
  243. # _aifc -- 1 iff reading an AIFF-C file
  244. # _ssnd_seek_needed -- 1 iff positioned correctly in audio
  245. # file for readframes()
  246. # _ssnd_chunk -- instantiation of a chunk class for the SSND chunk
  247. # _framesize -- size of one frame in the file
  248. def initfp(self, file):
  249. self._version = 0
  250. self._convert = None
  251. self._markers = []
  252. self._soundpos = 0
  253. self._file = file
  254. chunk = Chunk(file)
  255. if chunk.getname() != b'FORM':
  256. raise Error('file does not start with FORM id')
  257. formdata = chunk.read(4)
  258. if formdata == b'AIFF':
  259. self._aifc = 0
  260. elif formdata == b'AIFC':
  261. self._aifc = 1
  262. else:
  263. raise Error('not an AIFF or AIFF-C file')
  264. self._comm_chunk_read = 0
  265. while 1:
  266. self._ssnd_seek_needed = 1
  267. try:
  268. chunk = Chunk(self._file)
  269. except EOFError:
  270. break
  271. chunkname = chunk.getname()
  272. if chunkname == b'COMM':
  273. self._read_comm_chunk(chunk)
  274. self._comm_chunk_read = 1
  275. elif chunkname == b'SSND':
  276. self._ssnd_chunk = chunk
  277. dummy = chunk.read(8)
  278. self._ssnd_seek_needed = 0
  279. elif chunkname == b'FVER':
  280. self._version = _read_ulong(chunk)
  281. elif chunkname == b'MARK':
  282. self._readmark(chunk)
  283. chunk.skip()
  284. if not self._comm_chunk_read or not self._ssnd_chunk:
  285. raise Error('COMM chunk and/or SSND chunk missing')
  286. def __init__(self, f):
  287. if isinstance(f, str):
  288. f = builtins.open(f, 'rb')
  289. # else, assume it is an open file object already
  290. self.initfp(f)
  291. #
  292. # User visible methods.
  293. #
  294. def getfp(self):
  295. return self._file
  296. def rewind(self):
  297. self._ssnd_seek_needed = 1
  298. self._soundpos = 0
  299. def close(self):
  300. self._file.close()
  301. def tell(self):
  302. return self._soundpos
  303. def getnchannels(self):
  304. return self._nchannels
  305. def getnframes(self):
  306. return self._nframes
  307. def getsampwidth(self):
  308. return self._sampwidth
  309. def getframerate(self):
  310. return self._framerate
  311. def getcomptype(self):
  312. return self._comptype
  313. def getcompname(self):
  314. return self._compname
  315. ## def getversion(self):
  316. ## return self._version
  317. def getparams(self):
  318. return self.getnchannels(), self.getsampwidth(), \
  319. self.getframerate(), self.getnframes(), \
  320. self.getcomptype(), self.getcompname()
  321. def getmarkers(self):
  322. if len(self._markers) == 0:
  323. return None
  324. return self._markers
  325. def getmark(self, id):
  326. for marker in self._markers:
  327. if id == marker[0]:
  328. return marker
  329. raise Error('marker {0!r} does not exist'.format(id))
  330. def setpos(self, pos):
  331. if pos < 0 or pos > self._nframes:
  332. raise Error('position not in range')
  333. self._soundpos = pos
  334. self._ssnd_seek_needed = 1
  335. def readframes(self, nframes):
  336. if self._ssnd_seek_needed:
  337. self._ssnd_chunk.seek(0)
  338. dummy = self._ssnd_chunk.read(8)
  339. pos = self._soundpos * self._framesize
  340. if pos:
  341. self._ssnd_chunk.seek(pos + 8)
  342. self._ssnd_seek_needed = 0
  343. if nframes == 0:
  344. return b''
  345. data = self._ssnd_chunk.read(nframes * self._framesize)
  346. if self._convert and data:
  347. data = self._convert(data)
  348. self._soundpos = self._soundpos + len(data) // (self._nchannels
  349. * self._sampwidth)
  350. return data
  351. #
  352. # Internal methods.
  353. #
  354. def _alaw2lin(self, data):
  355. import audioop
  356. return audioop.alaw2lin(data, 2)
  357. def _ulaw2lin(self, data):
  358. import audioop
  359. return audioop.ulaw2lin(data, 2)
  360. def _adpcm2lin(self, data):
  361. import audioop
  362. if not hasattr(self, '_adpcmstate'):
  363. # first time
  364. self._adpcmstate = None
  365. data, self._adpcmstate = audioop.adpcm2lin(data, 2, self._adpcmstate)
  366. return data
  367. def _read_comm_chunk(self, chunk):
  368. self._nchannels = _read_short(chunk)
  369. self._nframes = _read_long(chunk)
  370. self._sampwidth = (_read_short(chunk) + 7) // 8
  371. self._framerate = int(_read_float(chunk))
  372. self._framesize = self._nchannels * self._sampwidth
  373. if self._aifc:
  374. #DEBUG: SGI's soundeditor produces a bad size :-(
  375. kludge = 0
  376. if chunk.chunksize == 18:
  377. kludge = 1
  378. print('Warning: bad COMM chunk size')
  379. chunk.chunksize = 23
  380. #DEBUG end
  381. self._comptype = chunk.read(4)
  382. #DEBUG start
  383. if kludge:
  384. length = ord(chunk.file.read(1))
  385. if length & 1 == 0:
  386. length = length + 1
  387. chunk.chunksize = chunk.chunksize + length
  388. chunk.file.seek(-1, 1)
  389. #DEBUG end
  390. self._compname = _read_string(chunk)
  391. if self._comptype != b'NONE':
  392. if self._comptype == b'G722':
  393. self._convert = self._adpcm2lin
  394. self._framesize = self._framesize // 4
  395. elif self._comptype in (b'ulaw', b'ULAW'):
  396. self._convert = self._ulaw2lin
  397. self._framesize = self._framesize // 2
  398. elif self._comptype in (b'alaw', b'ALAW'):
  399. self._convert = self._alaw2lin
  400. self._framesize = self._framesize // 2
  401. else:
  402. raise Error('unsupported compression type')
  403. else:
  404. self._comptype = b'NONE'
  405. self._compname = b'not compressed'
  406. def _readmark(self, chunk):
  407. nmarkers = _read_short(chunk)
  408. # Some files appear to contain invalid counts.
  409. # Cope with this by testing for EOF.
  410. try:
  411. for i in range(nmarkers):
  412. id = _read_short(chunk)
  413. pos = _read_long(chunk)
  414. name = _read_string(chunk)
  415. if pos or name:
  416. # some files appear to have
  417. # dummy markers consisting of
  418. # a position 0 and name ''
  419. self._markers.append((id, pos, name))
  420. except EOFError:
  421. print('Warning: MARK chunk contains only', end=' ')
  422. print(len(self._markers), end=' ')
  423. if len(self._markers) == 1: print('marker', end=' ')
  424. else: print('markers', end=' ')
  425. print('instead of', nmarkers)
  426. class Aifc_write:
  427. # Variables used in this class:
  428. #
  429. # These variables are user settable through appropriate methods
  430. # of this class:
  431. # _file -- the open file with methods write(), close(), tell(), seek()
  432. # set through the __init__() method
  433. # _comptype -- the AIFF-C compression type ('NONE' in AIFF)
  434. # set through the setcomptype() or setparams() method
  435. # _compname -- the human-readable AIFF-C compression type
  436. # set through the setcomptype() or setparams() method
  437. # _nchannels -- the number of audio channels
  438. # set through the setnchannels() or setparams() method
  439. # _sampwidth -- the number of bytes per audio sample
  440. # set through the setsampwidth() or setparams() method
  441. # _framerate -- the sampling frequency
  442. # set through the setframerate() or setparams() method
  443. # _nframes -- the number of audio frames written to the header
  444. # set through the setnframes() or setparams() method
  445. # _aifc -- whether we're writing an AIFF-C file or an AIFF file
  446. # set through the aifc() method, reset through the
  447. # aiff() method
  448. #
  449. # These variables are used internally only:
  450. # _version -- the AIFF-C version number
  451. # _comp -- the compressor from builtin module cl
  452. # _nframeswritten -- the number of audio frames actually written
  453. # _datalength -- the size of the audio samples written to the header
  454. # _datawritten -- the size of the audio samples actually written
  455. def __init__(self, f):
  456. if isinstance(f, str):
  457. filename = f
  458. f = builtins.open(f, 'wb')
  459. else:
  460. # else, assume it is an open file object already
  461. filename = '???'
  462. self.initfp(f)
  463. if filename[-5:] == '.aiff':
  464. self._aifc = 0
  465. else:
  466. self._aifc = 1
  467. def initfp(self, file):
  468. self._file = file
  469. self._version = _AIFC_version
  470. self._comptype = b'NONE'
  471. self._compname = b'not compressed'
  472. self._convert = None
  473. self._nchannels = 0
  474. self._sampwidth = 0
  475. self._framerate = 0
  476. self._nframes = 0
  477. self._nframeswritten = 0
  478. self._datawritten = 0
  479. self._datalength = 0
  480. self._markers = []
  481. self._marklength = 0
  482. self._aifc = 1 # AIFF-C is default
  483. def __del__(self):
  484. if self._file:
  485. self.close()
  486. #
  487. # User visible methods.
  488. #
  489. def aiff(self):
  490. if self._nframeswritten:
  491. raise Error('cannot change parameters after starting to write')
  492. self._aifc = 0
  493. def aifc(self):
  494. if self._nframeswritten:
  495. raise Error('cannot change parameters after starting to write')
  496. self._aifc = 1
  497. def setnchannels(self, nchannels):
  498. if self._nframeswritten:
  499. raise Error('cannot change parameters after starting to write')
  500. if nchannels < 1:
  501. raise Error('bad # of channels')
  502. self._nchannels = nchannels
  503. def getnchannels(self):
  504. if not self._nchannels:
  505. raise Error('number of channels not set')
  506. return self._nchannels
  507. def setsampwidth(self, sampwidth):
  508. if self._nframeswritten:
  509. raise Error('cannot change parameters after starting to write')
  510. if sampwidth < 1 or sampwidth > 4:
  511. raise Error('bad sample width')
  512. self._sampwidth = sampwidth
  513. def getsampwidth(self):
  514. if not self._sampwidth:
  515. raise Error('sample width not set')
  516. return self._sampwidth
  517. def setframerate(self, framerate):
  518. if self._nframeswritten:
  519. raise Error('cannot change parameters after starting to write')
  520. if framerate <= 0:
  521. raise Error('bad frame rate')
  522. self._framerate = framerate
  523. def getframerate(self):
  524. if not self._framerate:
  525. raise Error('frame rate not set')
  526. return self._framerate
  527. def setnframes(self, nframes):
  528. if self._nframeswritten:
  529. raise Error('cannot change parameters after starting to write')
  530. self._nframes = nframes
  531. def getnframes(self):
  532. return self._nframeswritten
  533. def setcomptype(self, comptype, compname):
  534. if self._nframeswritten:
  535. raise Error('cannot change parameters after starting to write')
  536. if comptype not in (b'NONE', b'ulaw', b'ULAW',
  537. b'alaw', b'ALAW', b'G722'):
  538. raise Error('unsupported compression type')
  539. self._comptype = comptype
  540. self._compname = compname
  541. def getcomptype(self):
  542. return self._comptype
  543. def getcompname(self):
  544. return self._compname
  545. ## def setversion(self, version):
  546. ## if self._nframeswritten:
  547. ## raise Error, 'cannot change parameters after starting to write'
  548. ## self._version = version
  549. def setparams(self, params):
  550. nchannels, sampwidth, framerate, nframes, comptype, compname = params
  551. if self._nframeswritten:
  552. raise Error('cannot change parameters after starting to write')
  553. if comptype not in (b'NONE', b'ulaw', b'ULAW',
  554. b'alaw', b'ALAW', b'G722'):
  555. raise Error('unsupported compression type')
  556. self.setnchannels(nchannels)
  557. self.setsampwidth(sampwidth)
  558. self.setframerate(framerate)
  559. self.setnframes(nframes)
  560. self.setcomptype(comptype, compname)
  561. def getparams(self):
  562. if not self._nchannels or not self._sampwidth or not self._framerate:
  563. raise Error('not all parameters set')
  564. return self._nchannels, self._sampwidth, self._framerate, \
  565. self._nframes, self._comptype, self._compname
  566. def setmark(self, id, pos, name):
  567. if id <= 0:
  568. raise Error('marker ID must be > 0')
  569. if pos < 0:
  570. raise Error('marker position must be >= 0')
  571. if not isinstance(name, str):
  572. raise Error('marker name must be a string')
  573. for i in range(len(self._markers)):
  574. if id == self._markers[i][0]:
  575. self._markers[i] = id, pos, name
  576. return
  577. self._markers.append((id, pos, name))
  578. def getmark(self, id):
  579. for marker in self._markers:
  580. if id == marker[0]:
  581. return marker
  582. raise Error('marker {0!r} does not exist'.format(id))
  583. def getmarkers(self):
  584. if len(self._markers) == 0:
  585. return None
  586. return self._markers
  587. def tell(self):
  588. return self._nframeswritten
  589. def writeframesraw(self, data):
  590. self._ensure_header_written(len(data))
  591. nframes = len(data) // (self._sampwidth * self._nchannels)
  592. if self._convert:
  593. data = self._convert(data)
  594. self._file.write(data)
  595. self._nframeswritten = self._nframeswritten + nframes
  596. self._datawritten = self._datawritten + len(data)
  597. def writeframes(self, data):
  598. self.writeframesraw(data)
  599. if self._nframeswritten != self._nframes or \
  600. self._datalength != self._datawritten:
  601. self._patchheader()
  602. def close(self):
  603. self._ensure_header_written(0)
  604. if self._datawritten & 1:
  605. # quick pad to even size
  606. self._file.write(b'\x00')
  607. self._datawritten = self._datawritten + 1
  608. self._writemarkers()
  609. if self._nframeswritten != self._nframes or \
  610. self._datalength != self._datawritten or \
  611. self._marklength:
  612. self._patchheader()
  613. # Prevent ref cycles
  614. self._convert = None
  615. self._file.close()
  616. #
  617. # Internal methods.
  618. #
  619. def _lin2alaw(self, data):
  620. import audioop
  621. return audioop.lin2alaw(data, 2)
  622. def _lin2ulaw(self, data):
  623. import audioop
  624. return audioop.lin2ulaw(data, 2)
  625. def _lin2adpcm(self, data):
  626. import audioop
  627. if not hasattr(self, '_adpcmstate'):
  628. self._adpcmstate = None
  629. data, self._adpcmstate = audioop.lin2adpcm(data, 2, self._adpcmstate)
  630. return data
  631. def _ensure_header_written(self, datasize):
  632. if not self._nframeswritten:
  633. if self._comptype in (b'ULAW', b'ALAW'):
  634. if not self._sampwidth:
  635. self._sampwidth = 2
  636. if self._sampwidth != 2:
  637. raise Error('sample width must be 2 when compressing '
  638. 'with ulaw/ULAW or alaw/ALAW')
  639. if self._comptype == b'G722':
  640. if not self._sampwidth:
  641. self._sampwidth = 2
  642. if self._sampwidth != 2:
  643. raise Error('sample width must be 2 when compressing '
  644. 'with G7.22 (ADPCM)')
  645. if not self._nchannels:
  646. raise Error('# channels not specified')
  647. if not self._sampwidth:
  648. raise Error('sample width not specified')
  649. if not self._framerate:
  650. raise Error('sampling rate not specified')
  651. self._write_header(datasize)
  652. def _init_compression(self):
  653. if self._comptype == b'G722':
  654. self._convert = self._lin2adpcm
  655. elif self._comptype in (b'ulaw', b'ULAW'):
  656. self._convert = self._lin2ulaw
  657. elif self._comptype in (b'alaw', b'ALAW'):
  658. self._convert = self._lin2alaw
  659. else:
  660. raise Error('unsupported compression type')
  661. def _write_header(self, initlength):
  662. if self._aifc and self._comptype != b'NONE':
  663. self._init_compression()
  664. self._file.write(b'FORM')
  665. if not self._nframes:
  666. self._nframes = initlength // (self._nchannels * self._sampwidth)
  667. self._datalength = self._nframes * self._nchannels * self._sampwidth
  668. if self._datalength & 1:
  669. self._datalength = self._datalength + 1
  670. if self._aifc:
  671. if self._comptype in (b'ulaw', b'ULAW', b'alaw', b'ALAW'):
  672. self._datalength = self._datalength // 2
  673. if self._datalength & 1:
  674. self._datalength = self._datalength + 1
  675. elif self._comptype == b'G722':
  676. self._datalength = (self._datalength + 3) // 4
  677. if self._datalength & 1:
  678. self._datalength = self._datalength + 1
  679. self._form_length_pos = self._file.tell()
  680. commlength = self._write_form_length(self._datalength)
  681. if self._aifc:
  682. self._file.write(b'AIFC')
  683. self._file.write(b'FVER')
  684. _write_long(self._file, 4)
  685. _write_long(self._file, self._version)
  686. else:
  687. self._file.write(b'AIFF')
  688. self._file.write(b'COMM')
  689. _write_long(self._file, commlength)
  690. _write_short(self._file, self._nchannels)
  691. self._nframes_pos = self._file.tell()
  692. _write_long(self._file, self._nframes)
  693. _write_short(self._file, self._sampwidth * 8)
  694. _write_float(self._file, self._framerate)
  695. if self._aifc:
  696. self._file.write(self._comptype)
  697. _write_string(self._file, self._compname)
  698. self._file.write(b'SSND')
  699. self._ssnd_length_pos = self._file.tell()
  700. _write_long(self._file, self._datalength + 8)
  701. _write_long(self._file, 0)
  702. _write_long(self._file, 0)
  703. def _write_form_length(self, datalength):
  704. if self._aifc:
  705. commlength = 18 + 5 + len(self._compname)
  706. if commlength & 1:
  707. commlength = commlength + 1
  708. verslength = 12
  709. else:
  710. commlength = 18
  711. verslength = 0
  712. _write_long(self._file, 4 + verslength + self._marklength + \
  713. 8 + commlength + 16 + datalength)
  714. return commlength
  715. def _patchheader(self):
  716. curpos = self._file.tell()
  717. if self._datawritten & 1:
  718. datalength = self._datawritten + 1
  719. self._file.write(b'\x00')
  720. else:
  721. datalength = self._datawritten
  722. if datalength == self._datalength and \
  723. self._nframes == self._nframeswritten and \
  724. self._marklength == 0:
  725. self._file.seek(curpos, 0)
  726. return
  727. self._file.seek(self._form_length_pos, 0)
  728. dummy = self._write_form_length(datalength)
  729. self._file.seek(self._nframes_pos, 0)
  730. _write_long(self._file, self._nframeswritten)
  731. self._file.seek(self._ssnd_length_pos, 0)
  732. _write_long(self._file, datalength + 8)
  733. self._file.seek(curpos, 0)
  734. self._nframes = self._nframeswritten
  735. self._datalength = datalength
  736. def _writemarkers(self):
  737. if len(self._markers) == 0:
  738. return
  739. self._file.write(b'MARK')
  740. length = 2
  741. for marker in self._markers:
  742. id, pos, name = marker
  743. length = length + len(name) + 1 + 6
  744. if len(name) & 1 == 0:
  745. length = length + 1
  746. _write_long(self._file, length)
  747. self._marklength = length + 8
  748. _write_short(self._file, len(self._markers))
  749. for marker in self._markers:
  750. id, pos, name = marker
  751. _write_short(self._file, id)
  752. _write_long(self._file, pos)
  753. _write_string(self._file, name)
  754. def open(f, mode=None):
  755. if mode is None:
  756. if hasattr(f, 'mode'):
  757. mode = f.mode
  758. else:
  759. mode = 'rb'
  760. if mode in ('r', 'rb'):
  761. return Aifc_read(f)
  762. elif mode in ('w', 'wb'):
  763. return Aifc_write(f)
  764. else:
  765. raise Error("mode must be 'r', 'rb', 'w', or 'wb'")
  766. openfp = open # B/W compatibility
  767. if __name__ == '__main__':
  768. import sys
  769. if not sys.argv[1:]:
  770. sys.argv.append('/usr/demos/data/audio/bach.aiff')
  771. fn = sys.argv[1]
  772. f = open(fn, 'r')
  773. print("Reading", fn)
  774. print("nchannels =", f.getnchannels())
  775. print("nframes =", f.getnframes())
  776. print("sampwidth =", f.getsampwidth())
  777. print("framerate =", f.getframerate())
  778. print("comptype =", f.getcomptype())
  779. print("compname =", f.getcompname())
  780. if sys.argv[2:]:
  781. gn = sys.argv[2]
  782. print("Writing", gn)
  783. g = open(gn, 'w')
  784. g.setparams(f.getparams())
  785. while 1:
  786. data = f.readframes(1024)
  787. if not data:
  788. break
  789. g.writeframes(data)
  790. g.close()
  791. f.close()
  792. print("Done.")