This is Info file /home/pdm/tmp/Python-1.5.2p1/Doc/lib/python-lib.info,
produced by Makeinfo version 1.68 from the input file lib.texi.

   July 6, 1999			1.5.2


File: python-lib.info,  Node: rexec,  Next: Bastion,  Prev: Restricted Execution,  Up: Restricted Execution

Restricted execution framework
==============================

   Basic restricted execution framework.

   This module contains the `RExec' class, which supports `r_eval()',
`r_execfile()', `r_exec()', and `r_import()' methods, which are
restricted versions of the standard Python functions `eval()',
`execfile()' and the `exec' and `import' statements.  Code executed in
this restricted environment will only have access to modules and
functions that are deemed safe; you can subclass `RExec' to add or
remove capabilities as desired.

   *Note:* The `RExec' class can prevent code from performing unsafe
operations like reading or writing disk files, or using TCP/IP sockets.
However, it does not protect against code using extremely large
amounts of memory or CPU time.

`RExec([hooks[, verbose]])'
     Returns an instance of the `RExec' class.

     HOOKS is an instance of the `RHooks' class or a subclass of it.
     If it is omitted or `None', the default `RHooks' class is
     instantiated.  Whenever the `rexec' module searches for a module
     (even a built-in one) or reads a module's code, it doesn't
     actually go out to the file system itself.  Rather, it calls
     methods of an `RHooks' instance that was passed to or created by
     its constructor.  (Actually, the `RExec' object doesn't make these
     calls -- they are made by a module loader object that's part of
     the `RExec' object.  This allows another level of flexibility,
     e.g. using packages.)

     By providing an alternate `RHooks' object, we can control the file
     system accesses made to import a module, without changing the
     actual algorithm that controls the order in which those accesses
     are made.  For instance, we could substitute an `RHooks' object
     that passes all filesystem requests to a file server elsewhere,
     via some RPC mechanism such as ILU.  Grail's applet loader uses
     this to support importing applets from a URL for a directory.

     If VERBOSE is true, additional debugging output may be sent to
     standard output.

   The `RExec' class has the following class attributes, which are used
by the `__init__()' method.  Changing them on an existing instance
won't have any effect; instead, create a subclass of `RExec' and assign
them new values in the class definition.  Instances of the new class
will then use those new values.  All these attributes are tuples of
strings.

`nok_builtin_names'
     Contains the names of built-in functions which will *not* be
     available to programs running in the restricted environment.  The
     value for `RExec' is `('open',' `'reload',' `'__import__')'.
     (This gives the exceptions, because by far the majority of
     built-in functions are harmless.  A subclass that wants to
     override this variable should probably start with the value from
     the base class and concatenate additional forbidden functions --
     when new dangerous built-in functions are added to Python, they
     will also be added to this module.)

`ok_builtin_modules'
     Contains the names of built-in modules which can be safely
     imported.  The value for `RExec' is `('audioop',' `'array','
     `'binascii',' `'cmath',' `'errno',' `'imageop',' `'marshal','
     `'math',' `'md5',' `'operator',' `'parser',' `'regex',' `'rotor','
     `'select',' `'strop',' `'struct',' `'time')'.  A similar remark
     about overriding this variable applies -- use the value from the
     base class as a starting point.

`ok_path'
     Contains the directories which will be searched when an `import'
     is performed in the restricted environment.  The value for `RExec'
     is the same as `sys.path' (at the time the module is loaded) for
     unrestricted code.

`ok_posix_names'
     Contains the names of the functions in the `os' module which will
     be available to programs running in the restricted environment.
     The value for `RExec' is `('error',' `'fstat',' `'listdir','
     `'lstat',' `'readlink',' `'stat',' `'times',' `'uname','
     `'getpid',' `'getppid',' `'getcwd',' `'getuid',' `'getgid','
     `'geteuid',' `'getegid')'.

`ok_sys_names'
     Contains the names of the functions and variables in the `sys'
     module which will be available to programs running in the
     restricted environment.  The value for `RExec' is `('ps1','
     `'ps2',' `'copyright',' `'version',' `'platform',' `'exit','
     `'maxint')'.

   `RExec' instances support the following methods:

`r_eval(code)'
     CODE must either be a string containing a Python expression, or a
     compiled code object, which will be evaluated in the restricted
     environment's `__main__' module.  The value of the expression or
     code object will be returned.

`r_exec(code)'
     CODE must either be a string containing one or more lines of
     Python code, or a compiled code object, which will be executed in
     the restricted environment's `__main__' module.

`r_execfile(filename)'
     Execute the Python code contained in the file FILENAME in the
     restricted environment's `__main__' module.

   Methods whose names begin with `s_' are similar to the functions
beginning with `r_', but the code will be granted access to restricted
versions of the standard I/O streams `sys.stdin', `sys.stderr', and
`sys.stdout'.

`s_eval(code)'
     CODE must be a string containing a Python expression, which will
     be evaluated in the restricted environment.

`s_exec(code)'
     CODE must be a string containing one or more lines of Python code,
     which will be executed in the restricted environment.

`s_execfile(code)'
     Execute the Python code contained in the file FILENAME in the
     restricted environment.

   `RExec' objects must also support various methods which will be
implicitly called by code executing in the restricted environment.
Overriding these methods in a subclass is used to change the policies
enforced by a restricted environment.

`r_import(modulename[, globals[, locals[, fromlist]]])'
     Import the module MODULENAME, raising an `ImportError' exception
     if the module is considered unsafe.

`r_open(filename[, mode[, bufsize]])'
     Method called when `open()' is called in the restricted
     environment.  The arguments are identical to those of `open()',
     and a file object (or a class instance compatible with file
     objects) should be returned.  `RExec''s default behaviour is allow
     opening any file for reading, but forbidding any attempt to write
     a file.  See the example below for an implementation of a less
     restrictive `r_open()'.

`r_reload(module)'
     Reload the module object MODULE, re-parsing and re-initializing it.

`r_unload(module)'
     Unload the module object MODULE (i.e., remove it from the
     restricted environment's `sys.modules' dictionary).

   And their equivalents with access to restricted standard I/O streams:

`s_import(modulename[, globals[, locals[, fromlist]]])'
     Import the module MODULENAME, raising an `ImportError' exception
     if the module is considered unsafe.

`s_reload(module)'
     Reload the module object MODULE, re-parsing and re-initializing it.

`s_unload(module)'
     Unload the module object MODULE.

* Menu:

* An example::


File: python-lib.info,  Node: An example,  Prev: rexec,  Up: rexec

An example
----------

   Let us say that we want a slightly more relaxed policy than the
standard `RExec' class.  For example, if we're willing to allow files
in `/tmp' to be written, we can subclass the `RExec' class:

     class TmpWriterRExec(rexec.RExec):
         def r_open(self, file, mode='r', buf=-1):
             if mode in ('r', 'rb'):
                 pass
             elif mode in ('w', 'wb', 'a', 'ab'):
                 # check filename : must begin with /tmp/
                 if file[:5]!='/tmp/':
                     raise IOError, "can't write outside /tmp"
                 elif (string.find(file, '/../') >= 0 or
                      file[:3] == '../' or file[-3:] == '/..'):
                     raise IOError, "'..' in filename forbidden"
             else: raise IOError, "Illegal open() mode"
             return open(file, mode, buf)

   Notice that the above code will occasionally forbid a perfectly valid
filename; for example, code in the restricted environment won't be able
to open a file called `/tmp/foo/../bar'.  To fix this, the `r_open()'
method would have to simplify the filename to `/tmp/bar', which would
require splitting apart the filename and performing various operations
on it.  In cases where security is at stake, it may be preferable to
write simple code which is sometimes overly restrictive, instead of
more general code that is also more complex and may harbor a subtle
security hole.


File: python-lib.info,  Node: Bastion,  Prev: rexec,  Up: Restricted Execution

Restricting access to objects
=============================

   Providing restricted access to objects.  This module was documented
by Barry Warsaw <bwarsaw@python.org>.
According to the dictionary, a bastion is "a fortified area or
position", or "something that is considered a stronghold."  It's a
suitable name for this module, which provides a way to forbid access to
certain attributes of an object.  It must always be used with the
`rexec' module, in order to allow restricted-mode programs access to
certain safe attributes of an object, while denying access to other,
unsafe attributes.

`Bastion(object[, filter[, name[, class]]])'
     Protect the object OBJECT, returning a bastion for the object.
     Any attempt to access one of the object's attributes will have to
     be approved by the FILTER function; if the access is denied an
     `AttributeError' exception will be raised.

     If present, FILTER must be a function that accepts a string
     containing an attribute name, and returns true if access to that
     attribute will be permitted; if FILTER returns false, the access
     is denied.  The default filter denies access to any function
     beginning with an underscore (`_').  The bastion's string
     representation will be `<Bastion for NAME>' if a value for NAME is
     provided; otherwise, `repr(OBJECT)' will be used.

     CLASS, if present, should be a subclass of `BastionClass'; see the
     code in `bastion.py' for the details.  Overriding the default
     `BastionClass' will rarely be required.

`BastionClass(getfunc, name)'
     Class which actually implements bastion objects.  This is the
     default class used by `Bastion()'.  The GETFUNC parameter is a
     function which returns the value of an attribute which should be
     exposed to the restricted execution environment when called with
     the name of the attribute as the only parameter.  NAME is used to
     construct the `repr()' of the `BastionClass' instance.


File: python-lib.info,  Node: Multimedia Services,  Next: Cryptographic Services,  Prev: Restricted Execution,  Up: Top

Multimedia Services
*******************

   The modules described in this chapter implement various algorithms or
interfaces that are mainly useful for multimedia applications.  They
are available at the discretion of the installation.  Here's an
overview:

* Menu:

* audioop::
* imageop::
* aifc::
* sunau::
* wave::
* chunk::
* colorsys::
* rgbimg::
* imghdr::
* sndhdr::


File: python-lib.info,  Node: audioop,  Next: imageop,  Prev: Multimedia Services,  Up: Multimedia Services

Manipulate raw audio data
=========================

   Manipulate raw audio data.

   The `audioop' module contains some useful operations on sound
fragments.  It operates on sound fragments consisting of signed integer
samples 8, 16 or 32 bits wide, stored in Python strings.  This is the
same format as used by the `al' and `sunaudiodev' modules.  All scalar
items are integers, unless specified otherwise.

   This module provides support for u-LAW and Intel/DVI ADPCM encodings.

   A few of the more complicated operations only take 16-bit samples,
otherwise the sample size (in bytes) is always a parameter of the
operation.

   The module defines the following variables and functions:

`error'
     This exception is raised on all errors, such as unknown number of
     bytes per sample, etc.

`add(fragment1, fragment2, width)'
     Return a fragment which is the addition of the two samples passed
     as parameters.  WIDTH is the sample width in bytes, either `1',
     `2' or `4'.  Both fragments should have the same length.

`adpcm2lin(adpcmfragment, width, state)'
     Decode an Intel/DVI ADPCM coded fragment to a linear fragment.  See
     the description of `lin2adpcm()' for details on ADPCM coding.
     Return a tuple `(SAMPLE, NEWSTATE)' where the sample has the width
     specified in WIDTH.

`adpcm32lin(adpcmfragment, width, state)'
     Decode an alternative 3-bit ADPCM code.  See `lin2adpcm3()' for
     details.

`avg(fragment, width)'
     Return the average over all samples in the fragment.

`avgpp(fragment, width)'
     Return the average peak-peak value over all samples in the
     fragment.  No filtering is done, so the usefulness of this routine
     is questionable.

`bias(fragment, width, bias)'
     Return a fragment that is the original fragment with a bias added
     to each sample.

`cross(fragment, width)'
     Return the number of zero crossings in the fragment passed as an
     argument.

`findfactor(fragment, reference)'
     Return a factor F such that `rms(add(FRAGMENT, mul(REFERENCE,
     -F)))' is minimal, i.e., return the factor with which you should
     multiply REFERENCE to make it match as well as possible to
     FRAGMENT.  The fragments should both contain 2-byte samples.

     The time taken by this routine is proportional to `len(FRAGMENT)'.

`findfit(fragment, reference)'
     Try to match REFERENCE as well as possible to a portion of
     FRAGMENT (which should be the longer fragment).  This is
     (conceptually) done by taking slices out of FRAGMENT, using
     `findfactor()' to compute the best match, and minimizing the
     result.  The fragments should both contain 2-byte samples.  Return
     a tuple `(OFFSET, FACTOR)' where OFFSET is the (integer) offset
     into FRAGMENT where the optimal match started and FACTOR is the
     (floating-point) factor as per `findfactor()'.

`findmax(fragment, length)'
     Search FRAGMENT for a slice of length LENGTH samples (not bytes!)
     with maximum energy, i.e., return I for which
     `rms(fragment[i*2:(i+length)*2])' is maximal.  The fragments
     should both contain 2-byte samples.

     The routine takes time proportional to `len(FRAGMENT)'.

`getsample(fragment, width, index)'
     Return the value of sample INDEX from the fragment.

`lin2lin(fragment, width, newwidth)'
     Convert samples between 1-, 2- and 4-byte formats.

`lin2adpcm(fragment, width, state)'
     Convert samples to 4 bit Intel/DVI ADPCM encoding.  ADPCM coding
     is an adaptive coding scheme, whereby each 4 bit number is the
     difference between one sample and the next, divided by a (varying)
     step.  The Intel/DVI ADPCM algorithm has been selected for use by
     the IMA, so it may well become a standard.

     STATE is a tuple containing the state of the coder.  The coder
     returns a tuple `(ADPCMFRAG, NEWSTATE)', and the NEWSTATE should
     be passed to the next call of `lin2adpcm()'.  In the initial call,
     `None' can be passed as the state.  ADPCMFRAG is the ADPCM coded
     fragment packed 2 4-bit values per byte.

`lin2adpcm3(fragment, width, state)'
     This is an alternative ADPCM coder that uses only 3 bits per
     sample.  It is not compatible with the Intel/DVI ADPCM coder and
     its output is not packed (due to laziness on the side of the
     author).  Its use is discouraged.

`lin2ulaw(fragment, width)'
     Convert samples in the audio fragment to u-LAW encoding and return
     this as a Python string.  u-LAW is an audio encoding format whereby
     you get a dynamic range of about 14 bits using only 8 bit samples.
     It is used by the Sun audio hardware, among others.

`minmax(fragment, width)'
     Return a tuple consisting of the minimum and maximum values of all
     samples in the sound fragment.

`max(fragment, width)'
     Return the maximum of the *absolute value* of all samples in a
     fragment.

`maxpp(fragment, width)'
     Return the maximum peak-peak value in the sound fragment.

`mul(fragment, width, factor)'
     Return a fragment that has all samples in the original framgent
     multiplied by the floating-point value FACTOR.  Overflow is
     silently ignored.

`ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])'
     Convert the frame rate of the input fragment.

     STATE is a tuple containing the state of the converter.  The
     converter returns a tupl `(NEWFRAGMENT, NEWSTATE)', and NEWSTATE
     should be passed to the next call of `ratecv()'.

     The WEIGHTA and WEIGHTB arguments are parameters for a simple
     digital filter and default to `1' and `0' respectively.

`reverse(fragment, width)'
     Reverse the samples in a fragment and returns the modified
     fragment.

`rms(fragment, width)'
     Return the root-mean-square of the fragment, i.e.
          \catcode`_=8
          \sqrt{\frac{\sum{{S_{i}}^{2}}}{n}}

     This is a measure of the power in an audio signal.

`tomono(fragment, width, lfactor, rfactor)'
     Convert a stereo fragment to a mono fragment.  The left channel is
     multiplied by LFACTOR and the right channel by RFACTOR before
     adding the two channels to give a mono signal.

`tostereo(fragment, width, lfactor, rfactor)'
     Generate a stereo fragment from a mono fragment.  Each pair of
     samples in the stereo fragment are computed from the mono sample,
     whereby left channel samples are multiplied by LFACTOR and right
     channel samples by RFACTOR.

`ulaw2lin(fragment, width)'
     Convert sound fragments in u-LAW encoding to linearly encoded sound
     fragments.  u-LAW encoding always uses 8 bits samples, so WIDTH
     refers only to the sample width of the output fragment here.

   Note that operations such as `mul()' or `max()' make no distinction
between mono and stereo fragments, i.e. all samples are treated equal.
If this is a problem the stereo fragment should be split into two mono
fragments first and recombined later.  Here is an example of how to do
that:

     def mul_stereo(sample, width, lfactor, rfactor):
         lsample = audioop.tomono(sample, width, 1, 0)
         rsample = audioop.tomono(sample, width, 0, 1)
         lsample = audioop.mul(sample, width, lfactor)
         rsample = audioop.mul(sample, width, rfactor)
         lsample = audioop.tostereo(lsample, width, 1, 0)
         rsample = audioop.tostereo(rsample, width, 0, 1)
         return audioop.add(lsample, rsample, width)

   If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e. to be able to tolerate packet loss) you
should not only transmit the data but also the state.  Note that you
should send the INITIAL state (the one you passed to `lin2adpcm()')
along to the decoder, not the final state (as returned by the coder).
If you want to use `struct.struct()' to store the state in binary you
can code the first element (the predicted value) in 16 bits and the
second (the delta index) in 8.

   The ADPCM coders have never been tried against other ADPCM coders,
only against themselves.  It could well be that I misinterpreted the
standards in which case they will not be interoperable with the
respective standards.

   The `find*()' routines might look a bit funny at first sight.  They
are primarily meant to do echo cancellation.  A reasonably fast way to
do this is to pick the most energetic piece of the output sample,
locate that in the input sample and subtract the whole output sample
from the input sample:

     def echocancel(outputdata, inputdata):
         pos = audioop.findmax(outputdata, 800)    # one tenth second
         out_test = outputdata[pos*2:]
         in_test = inputdata[pos*2:]
         ipos, factor = audioop.findfit(in_test, out_test)
         # Optional (for better cancellation):
         # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
         #              out_test)
         prefill = '\0'*(pos+ipos)*2
         postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
         outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
         return audioop.add(inputdata, outputdata, 2)


File: python-lib.info,  Node: imageop,  Next: aifc,  Prev: audioop,  Up: Multimedia Services

Manipulate raw image data
=========================

   Manipulate raw image data.

   The `imageop' module contains some useful operations on images.  It
operates on images consisting of 8 or 32 bit pixels stored in Python
strings.  This is the same format as used by `gl.lrectwrite()' and the
`imgfile' module.

   The module defines the following variables and functions:

`error'
     This exception is raised on all errors, such as unknown number of
     bits per pixel, etc.

`crop(image, psize, width, height, x0, y0, x1, y1)'
     Return the selected part of IMAGE, which should by WIDTH by HEIGHT
     in size and consist of pixels of PSIZE bytes. X0, Y0, X1 and Y1
     are like the `gl.lrectread()' parameters, i.e. the boundary is
     included in the new image.  The new boundaries need not be inside
     the picture.  Pixels that fall outside the old image will have
     their value set to zero.  If X0 is bigger than X1 the new image is
     mirrored.  The same holds for the y coordinates.

`scale(image, psize, width, height, newwidth, newheight)'
     Return IMAGE scaled to size NEWWIDTH by NEWHEIGHT.  No
     interpolation is done, scaling is done by simple-minded pixel
     duplication or removal.  Therefore, computer-generated images or
     dithered images will not look nice after scaling.

`tovideo(image, psize, width, height)'
     Run a vertical low-pass filter over an image.  It does so by
     computing each destination pixel as the average of two
     vertically-aligned source pixels.  The main use of this routine is
     to forestall excessive flicker if the image is displayed on a
     video device that uses interlacing, hence the name.

`grey2mono(image, width, height, threshold)'
     Convert a 8-bit deep greyscale image to a 1-bit deep image by
     tresholding all the pixels.  The resulting image is tightly packed
     and is probably only useful as an argument to `mono2grey()'.

`dither2mono(image, width, height)'
     Convert an 8-bit greyscale image to a 1-bit monochrome image using
     a (simple-minded) dithering algorithm.

`mono2grey(image, width, height, p0, p1)'
     Convert a 1-bit monochrome image to an 8 bit greyscale or color
     image.  All pixels that are zero-valued on input get value P0 on
     output and all one-value input pixels get value P1 on output.  To
     convert a monochrome black-and-white image to greyscale pass the
     values `0' and `255' respectively.

`grey2grey4(image, width, height)'
     Convert an 8-bit greyscale image to a 4-bit greyscale image without
     dithering.

`grey2grey2(image, width, height)'
     Convert an 8-bit greyscale image to a 2-bit greyscale image without
     dithering.

`dither2grey2(image, width, height)'
     Convert an 8-bit greyscale image to a 2-bit greyscale image with
     dithering.  As for `dither2mono()', the dithering algorithm is
     currently very simple.

`grey42grey(image, width, height)'
     Convert a 4-bit greyscale image to an 8-bit greyscale image.

`grey22grey(image, width, height)'
     Convert a 2-bit greyscale image to an 8-bit greyscale image.


File: python-lib.info,  Node: aifc,  Next: sunau,  Prev: imageop,  Up: Multimedia Services

Read and write AIFF and AIFC files
==================================

   Read and write audio files in AIFF or AIFC format.

   This module provides support for reading and writing AIFF and AIFF-C
files.  AIFF is Audio Interchange File Format, a format for storing
digital audio samples in a file.  AIFF-C is a newer version of the
format that includes the ability to compress the audio data.

   *Caveat:*  Some operations may only work under IRIX; these will
raise `ImportError' when attempting to import the `cl' module, which is
only available on IRIX.

   Audio files have a number of parameters that describe the audio data.
The sampling rate or frame rate is the number of times per second the
sound is sampled.  The number of channels indicate if the audio is
mono, stereo, or quadro.  Each frame consists of one sample per
channel.  The sample size is the size in bytes of each sample.  Thus a
frame consists of NCHANNELS*SAMPLESIZE bytes, and a second's worth of
audio consists of NCHANNELS*SAMPLESIZE*FRAMERATE bytes.

   For example, CD quality audio has a sample size of two bytes (16
bits), uses two channels (stereo) and has a frame rate of 44,100
frames/second.  This gives a frame size of 4 bytes (2*2), and a
second's worth occupies 2*2*44100 bytes, i.e. 176,400 bytes.

   Module `aifc' defines the following function:

`open(file, mode)'
     Open an AIFF or AIFF-C file and return an object instance with
     methods that are described below.  The argument file is either a
     string naming a file or a file object.  The mode is either the
     string `'r'' when the file must be opened for reading, or `'w''
     when the file must be opened for writing.  When used for writing,
     the file object should be seekable, unless you know ahead of time
     how many samples you are going to write in total and use
     `writeframesraw()' and `setnframes()'.

   Objects returned by `open()' when a file is opened for reading have
the following methods:

`getnchannels()'
     Return the number of audio channels (1 for mono, 2 for stereo).

`getsampwidth()'
     Return the size in bytes of individual samples.

`getframerate()'
     Return the sampling rate (number of audio frames per second).

`getnframes()'
     Return the number of audio frames in the file.

`getcomptype()'
     Return a four-character string describing the type of compression
     used in the audio file.  For AIFF files, the returned value is
     `'NONE''.

`getcompname()'
     Return a human-readable description of the type of compression
     used in the audio file.  For AIFF files, the returned value is
     `'not compressed''.

`getparams()'
     Return a tuple consisting of all of the above values in the above
     order.

`getmarkers()'
     Return a list of markers in the audio file.  A marker consists of a
     tuple of three elements.  The first is the mark ID (an integer),
     the second is the mark position in frames from the beginning of
     the data (an integer), the third is the name of the mark (a
     string).

`getmark(id)'
     Return the tuple as described in `getmarkers()' for the mark with
     the given ID.

`readframes(nframes)'
     Read and return the next NFRAMES frames from the audio file.  The
     returned data is a string containing for each frame the
     uncompressed samples of all channels.

`rewind()'
     Rewind the read pointer.  The next `readframes()' will start from
     the beginning.

`setpos(pos)'
     Seek to the specified frame number.

`tell()'
     Return the current frame number.

`close()'
     Close the AIFF file.  After calling this method, the object can no
     longer be used.

   Objects returned by `open()' when a file is opened for writing have
all the above methods, except for `readframes()' and `setpos()'.  In
addition the following methods exist.  The `get*()' methods can only be
called after the corresponding `set*()' methods have been called.
Before the first `writeframes()' or `writeframesraw()', all parameters
except for the number of frames must be filled in.

`aiff()'
     Create an AIFF file.  The default is that an AIFF-C file is
     created, unless the name of the file ends in `'.aiff'' in which
     case the default is an AIFF file.

`aifc()'
     Create an AIFF-C file.  The default is that an AIFF-C file is
     created, unless the name of the file ends in `'.aiff'' in which
     case the default is an AIFF file.

`setnchannels(nchannels)'
     Specify the number of channels in the audio file.

`setsampwidth(width)'
     Specify the size in bytes of audio samples.

`setframerate(rate)'
     Specify the sampling frequency in frames per second.

`setnframes(nframes)'
     Specify the number of frames that are to be written to the audio
     file.  If this parameter is not set, or not set correctly, the
     file needs to support seeking.

`setcomptype(type, name)'
     Specify the compression type.  If not specified, the audio data
     will not be compressed.  In AIFF files, compression is not
     possible.  The name parameter should be a human-readable
     description of the compression type, the type parameter should be
     a four-character string.  Currently the following compression
     types are supported: NONE, ULAW, ALAW, G722.

`setparams(nchannels, sampwidth, framerate, comptype, compname)'
     Set all the above parameters at once.  The argument is a tuple
     consisting of the various parameters.  This means that it is
     possible to use the result of a `getparams()' call as argument to
     `setparams()'.

`setmark(id, pos, name)'
     Add a mark with the given id (larger than 0), and the given name at
     the given position.  This method can be called at any time before
     `close()'.

`tell()'
     Return the current write position in the output file.  Useful in
     combination with `setmark()'.

`writeframes(data)'
     Write data to the output file.  This method can only be called
     after the audio file parameters have been set.

`writeframesraw(data)'
     Like `writeframes()', except that the header of the audio file is
     not updated.

`close()'
     Close the AIFF file.  The header of the file is updated to reflect
     the actual size of the audio data. After calling this method, the
     object can no longer be used.


File: python-lib.info,  Node: sunau,  Next: wave,  Prev: aifc,  Up: Multimedia Services

Read and write Sun AU files
===========================

   This section was written by Moshe Zadka <mzadka@geocities.com>.
Provide an interface to the Sun AU sound format.

   The `sunau' module provides a convenient interface to the Sun AU
sound format. Note that this module is interface-compatible with the
modules `aifc' and `wave'.

   The `sunau' module defines the following functions:

`open(file, mode)'
     If FILE is a string, open the file by that name, otherwise treat it
     as a seekable file-like object. MODE can be any of
    ``'r'''
          Read only mode.

    ``'w'''
          Write only mode.

     Note that it does not allow read/write files.

     A MODE of `'r'' returns a `AU_read' object, while a MODE of `'w''
     or `'wb'' returns a `AU_write' object.

`openfp(file, mode)'
     A synonym for `open', maintained for backwards compatibility.

   The `sunau' module defines the following exception:

`Error'
     An error raised when something is impossible because of Sun AU
     specs or implementation deficiency.

   The `sunau' module defines the following data item:

`AUDIO_FILE_MAGIC'
     An integer every valid Sun AU file begins with a big-endian
     encoding of.

* Menu:

* AU_read Objects::
* AU_write Objects::


File: python-lib.info,  Node: AU_read Objects,  Next: AU_write Objects,  Prev: sunau,  Up: sunau

AU_read Objects
---------------

   AU_read objects, as returned by `open()' above, have the following
methods:

`close()'
     Close the stream, and make the instance unusable. (This is called
     automatically on deletion.)

`getnchannels()'
     Returns number of audio channels (1 for mone, 2 for stereo).

`getsampwidth()'
     Returns sample width in bytes.

`getframerate()'
     Returns sampling frequency.

`getnframes()'
     Returns number of audio frames.

`getcomptype()'
     Returns compression type.  Supported compression types are
     `'ULAW'', `'ALAW'' and `'NONE''.

`getcompname()'
     Human-readable version of `getcomptype()'.  The supported types
     have the respective names `'CCITT G.711 u-law'', `'CCITT G.711
     A-law'' and `'not compressed''.

`getparams()'
     Returns a tuple `(NCHANNELS, SAMPWIDTH, FRAMERATE, NFRAMES,
     COMPTYPE, COMPNAME)', equivalent to output of the `get*()' methods.

`readframes(n)'
     Reads and returns at most N frames of audio, as a string of bytes.

`rewind()'
     Rewind the file pointer to the beginning of the audio stream.

   The following two methods define a term "position" which is
compatible between them, and is otherwise implementation dependant.

`setpos(pos)'
     Set the file pointer to the specified position.

`tell()'
     Return current file pointer position.

   The following two functions are defined for compatibility with the
`aifc', and don't do anything interesting.

`getmarkers()'
     Returns `None'.

`getmark(id)'
     Raise an error.


File: python-lib.info,  Node: AU_write Objects,  Prev: AU_read Objects,  Up: sunau

AU_write Objects
----------------

   AU_write objects, as returned by `open()' above, have the following
methods:

`setnchannels(n)'
     Set the number of channels.

`setsampwidth(n)'
     Set the sample width (in bytes.)

`setframerate(n)'
     Set the frame rate.

`setnframes(n)'
     Set the number of frames. This can be later changed, when and if
     more frames are written.

`setcomptype(type, name)'
     Set the compression type and description.  Only `'NONE'' and
     `'ULAW'' are supported on output.

`setparams(tuple)'
     The TUPLE should be `(NCHANNELS, SAMPWIDTH, FRAMERATE, NFRAMES,
     COMPTYPE, COMPNAME)', with values valid for the `set*()' methods.
     Set all parameters.

`tell()'
     Return current position in the file, with the same disclaimer for
     the `AU_read.tell()' and `AU_read.setpos()' methods.

`writeframesraw(data)'
     Write audio frames, without correcting NFRAMES.

`writeframes(data)'
     Write audio frames and make sure NFRAMES is correct.

`close()'
     Make sure NFRAMES is correct, and close the file.

     This method is called upon deletion.

   Note that it is invalid to set any parameters after calling
`writeframes()' or `writeframesraw()'.


File: python-lib.info,  Node: wave,  Next: chunk,  Prev: sunau,  Up: Multimedia Services

Read and write WAV files
========================

   This section was written by Moshe Zadka <mzadka@geocities.com>.
Provide an interface to the WAV sound format.

   The `wave' module provides a convenient interface to the WAV sound
format. It does not support compression/decompression, but it does
support mono/stereo.

   The `wave' module defines the following function and exception:

`open(file, mode)'
     If FILE is a string, open the file by that name, other treat it as
     a seekable file-like object. MODE can be any of
    ``'r'', `'rb'''
          Read only mode.

    ``'w'', `'wb'''
          Write only mode.

     Note that it does not allow read/write WAV files.

     A MODE of `'r'' or `'rb'' returns a `Wave_read' object, while a
     MODE of `'w'' or `'wb'' returns a `Wave_write' object.

`openfp(file, mode)'
     A synonym for `open()', maintained for backwards compatibility.

`Error'
     An error raised when something is impossible because it violates
     the WAV specification or hits an implementation deficiency.

* Menu:

* Wave_read Objects::
* Wave_write Objects::


File: python-lib.info,  Node: Wave_read Objects,  Next: Wave_write Objects,  Prev: wave,  Up: wave

Wave_read Objects
-----------------

   Wave_read objects, as returned by `open()', have the following
methods:

`close()'
     Close the stream, and make the instance unusable. This is called
     automatically on object collection.

`getnchannels()'
     Returns number of audio channels (`1' for mono, `2' for stereo).

`getsampwidth()'
     Returns sample width in bytes.

`getframerate()'
     Returns sampling frequency.

`getnframes()'
     Returns number of audio frames.

`getcomptype()'
     Returns compression type (`'NONE'' is the only supported type).

`getcompname()'
     Human-readable version of `getcomptype()'.  Usually `'not
     compressed'' parallels `'NONE''.

`getparams()'
     Returns a tuple `(NCHANNELS, SAMPWIDTH, FRAMERATE, NFRAMES,
     COMPTYPE, COMPNAME)', equivalent to output of the `get*()' methods.

`readframes(n)'
     Reads and returns at most N frames of audio, as a string of bytes.

`rewind()'
     Rewind the file pointer to the beginning of the audio stream.

   The following two methods are defined for compatibility with the
`aifc' module, and don't do anything interesting.

`getmarkers()'
     Returns `None'.

`getmark(id)'
     Raise an error.

   The following two methods define a term "position" which is
compatible between them, and is otherwise implementation dependant.

`setpos(pos)'
     Set the file pointer to the specified position.

`tell()'
     Return current file pointer position.


File: python-lib.info,  Node: Wave_write Objects,  Prev: Wave_read Objects,  Up: wave

Wave_write Objects
------------------

   Wave_write objects, as returned by `open()', have the following
methods:

`close()'
     Make sure NFRAMES is correct, and close the file.  This method is
     called upon deletion.

`setnchannels(n)'
     Set the number of channels.

`setsampwidth(n)'
     Set the sample width to N bytes.

`setframerate(n)'
     Set the frame rate to N.

`setnframes(n)'
     Set the number of frames to N. This will be changed later if more
     frames are written.

`setcomptype(type, name)'
     Set the compression type and description.

`setparams(tuple)'
     The TUPLE should be `(NCHANNELS, SAMPWIDTH, FRAMERATE, NFRAMES,
     COMPTYPE, COMPNAME)', with values valid for the `set*()' methods.
     Sets all parameters.

`tell()'
     Return current position in the file, with the same disclaimer for
     the `Wave_read.tell()' and `Wave_read.setpos()' methods.

`writeframesraw(data)'
     Write audio frames, without correcting NFRAMES.

`writeframes(data)'
     Write audio frames and make sure NFRAMES is correct.

   Note that it is invalid to set any parameters after calling
`writeframes()' or `writeframesraw()', and any attempt to do so will
raise `wave.Error'.


File: python-lib.info,  Node: chunk,  Next: colorsys,  Prev: wave,  Up: Multimedia Services

Read IFF chunked data
=====================

   Module to read IFF chunks.  This module was documented by Sjoerd
Mullender <sjoerd@acm.org>.
This section was written by Sjoerd Mullender <sjoerd@acm.org>.
This module provides an interface for reading files that use EA IFF 85
chunks.(1)  This format is used in at least the Audio Interchange File
Format (AIFF/AIFF-C), the Real Media File Format (RMFF), and the Tagged
Image File Format(TIFF).

   A chunk has the following structure:

Offset                   Length                   Contents                 
------                   -----                    -----                    
0                        4                        Chunk ID                 
4                        4                        Size of chunk in         
                                                  big-endian byte order,   
                                                  including the  header    
8                        N                        Data bytes, where N is   
                                                  the size given in the    
                                                  preceeding field         
8 + N                    0 or 1                   Pad byte needed if N is  
                                                  odd and chunk alignment  
                                                  is used                  

   The ID is a 4-byte string which identifies the type of chunk.

   The size field (a 32-bit value, encoded using big-endian byte order)
gives the size of the whole chunk, including the 8-byte header.

   Usually an IFF-type file consists of one or more chunks.  The
proposed usage of the `Chunk' class defined here is to instantiate an
instance at the start of each chunk and read from the instance until it
reaches the end, after which a new instance can be instantiated.  At
the end of the file, creating a new instance will fail with a
`EOFError' exception.

`Chunk(file[, align])'
     Class which represents a chunk.  The FILE argument is expected to
     be a file-like object.  An instance of this class is specifically
     allowed.  The only method that is needed is `read()'.  If the
     methods `seek()' and `tell()' are present and don't raise an
     exception, they are also used.  If these methods are present and
     raise an exception, they are expected to not have altered the
     object.  If the optional argument ALIGN is true, chunks are
     assumed to be aligned on 2-byte boundaries.  If ALIGN is false, no
     alignment is assumed.  The default value is true.

   A `Chunk' object supports the following methods:

`getname()'
     Returns the name (ID) of the chunk.  This is the first 4 bytes of
     the chunk.

`close()'
     Close and skip to the end of the chunk.  This does not close the
     underlying file.

   The remaining methods will raise `IOError' if called after the
`close()' method has been called.

`isatty()'
     Returns `0'.

`seek(pos[, whence])'
     Set the chunk's current position.  The WHENCE argument is optional
     and defaults to `0' (absolute file positioning); other values are
     `1' (seek relative to the current position) and `2' (seek relative
     to the file's end).  There is no return value.  If the underlying
     file does not allow seek, only forward seeks are allowed.

`tell()'
     Return the current position into the chunk.

`read([size])'
     Read at most SIZE bytes from the chunk (less if the read hits the
     end of the chunk before obtaining SIZE bytes).  If the SIZE
     argument is negative or omitted, read all data until the end of
     the chunk.  The bytes are returned as a string object.  An empty
     string is returned when the end of the chunk is encountered
     immediately.

`skip()'
     Skip to the end of the chunk.  All further calls to `read()' for
     the chunk will return `'''.  If you are not interested in the
     contents of the chunk, this method should be called so that the
     file points to the start of the next chunk.

   ---------- Footnotes ----------

   (1) "EA IFF 85" Standard for Interchange Format Files, Jerry
Morrison, Electronic Arts, January 1985.


File: python-lib.info,  Node: colorsys,  Next: rgbimg,  Prev: chunk,  Up: Multimedia Services

Conversions between color systems
=================================

   Conversion functions between RGB and other color systems.

   This section was written by David Ascher <da@python.net>.
The `colorsys' module defines bidirectional conversions of color values
between colors expressed in the RGB (Red Green Blue) color space used
in computer monitors and three other coordinate systems: YIQ, HLS (Hue
Lightness Saturation) and HSV (Hue Saturation Value).  Coordinates in
all of these color spaces are floating point values.  In the YIQ space,
the Y coordinate is between 0 and 1, but the I and Q coordinates can be
positive or negative.  In all other spaces, the coordinates are all
between 0 and 1.

   More information about color spaces can be found at
`http://www.inforamp.net/%7epoynton/ColorFAQ.html'.

   The `colorsys' module defines the following functions:

`rgb_to_yiq(r, g, b)'
     Convert the color from RGB coordinates to YIQ coordinates.

`yiq_to_rgb(y, i, q)'
     Convert the color from YIQ coordinates to RGB coordinates.

`rgb_to_hls(r, g, b)'
     Convert the color from RGB coordinates to HLS coordinates.

`hls_to_rgb(h, l, s)'
     Convert the color from HLS coordinates to RGB coordinates.

`rgb_to_hsv(r, g, b)'
     Convert the color from RGB coordinates to HSV coordinates.

`hsv_to_rgb(h, s, v)'
     Convert the color from HSV coordinates to RGB coordinates.

   Example:

     >>> import colorsys
     >>> colorsys.rgb_to_hsv(.3, .4, .2)
     (0.25, 0.5, 0.4)
     >>> colorsys.hsv_to_rgb(0.25, 0.5, 0.4)
     (0.3, 0.4, 0.2)


File: python-lib.info,  Node: rgbimg,  Next: imghdr,  Prev: colorsys,  Up: Multimedia Services

Read and write "SGI RGB" files
==============================

   Read and write image files in "SGI RGB" format (the module is *not*
SGI specific though!).

   The `rgbimg' module allows Python programs to access SGI imglib image
files (also known as `.rgb' files).  The module is far from complete,
but is provided anyway since the functionality that there is enough in
some cases.  Currently, colormap files are not supported.

   The module defines the following variables and functions:

`error'
     This exception is raised on all errors, such as unsupported file
     type, etc.

`sizeofimage(file)'
     This function returns a tuple `(X, Y)' where X and Y are the size
     of the image in pixels.  Only 4 byte RGBA pixels, 3 byte RGB
     pixels, and 1 byte greyscale pixels are currently supported.

`longimagedata(file)'
     This function reads and decodes the image on the specified file,
     and returns it as a Python string. The string has 4 byte RGBA
     pixels.  The bottom left pixel is the first in the string. This
     format is suitable to pass to `gl.lrectwrite()', for instance.

`longstoimage(data, x, y, z, file)'
     This function writes the RGBA data in DATA to image file FILE. X
     and Y give the size of the image.  Z is 1 if the saved image
     should be 1 byte greyscale, 3 if the saved image should be 3 byte
     RGB data, or 4 if the saved images should be 4 byte RGBA data.
     The input data always contains 4 bytes per pixel.  These are the
     formats returned by `gl.lrectread()'.

`ttob(flag)'
     This function sets a global flag which defines whether the scan
     lines of the image are read or written from bottom to top (flag is
     zero, compatible with SGI GL) or from top to bottom(flag is one,
     compatible with X).  The default is zero.


File: python-lib.info,  Node: imghdr,  Next: sndhdr,  Prev: rgbimg,  Up: Multimedia Services

Determine the type of an image.
===============================

   Determine the type of image contained in a file or byte stream.

   The `imghdr' module determines the type of image contained in a file
or byte stream.

   The `imghdr' module defines the following function:

`what(filename[, h])'
     Tests the image data contained in the file named by FILENAME, and
     returns a string describing the image type.  If optional H is
     provided, the FILENAME is ignored and H is assumed to contain the
     byte stream to test.

   The following image types are recognized, as listed below with the
return value from `what()':

Value                                Image format                         
------                               -----                                
'rgb'                                SGI ImgLib Files                     
'gif'                                GIF 87a and 89a Files                
'pbm'                                Portable Bitmap Files                
'pgm'                                Portable Graymap Files               
'ppm'                                Portable Pixmap Files                
'tiff'                               TIFF Files                           
'rast'                               Sun Raster Files                     
'xbm'                                X Bitmap Files                       
'jpeg'                               JPEG data in JFIF format             
'bmp'                                BMP files                            
'png'                                Portable Network Graphics            

   You can extend the list of file types `imghdr' can recognize by
appending to this variable:

`tests'
     A list of functions performing the individual tests.  Each function
     takes two arguments: the byte-stream and an open file-like object.
     When `what()' is called with a byte-stream, the file-like object
     will be `None'.

     The test function should return a string describing the image type
     if the test succeeded, or `None' if it failed.

   Example:

     >>> import imghdr
     >>> imghdr.what('/tmp/bass.gif')
     'gif'

