This is /home/pdm/install/Python-2.1/Doc/lib/python-lib.info, produced
by makeinfo version 4.0 from lib.texi.

   April 15, 2001		2.1


File: python-lib.info,  Node: xml.sax.saxutils,  Next: xml.sax.xmlreader,  Prev: xml.sax.handler,  Up: Structured Markup Processing Tools

SAX Utilities
=============

   Convenience functions and classes for use with SAX.

   This section was written by Martin v. L"owis
<loewis@informatik.hu-berlin.de>.
This module was documented by Lars Marius Garshol
<larsga@garshol.priv.no>.
_Added in Python version 2.0_

   The module `xml.sax.saxutils' contains a number of classes and
functions that are commonly useful when creating SAX applications,
either in direct use, or as base classes.

`escape(data[, entities])'
     Escape &, <, and > in a string of data.

     You can escape other strings of data by passing a dictionary as the
     optional entities parameter.  The keys and values must all be
     strings; each key will be replaced with its corresponding value.

`XMLGenerator([out[, encoding]])'
     This class implements the `ContentHandler' interface by writing
     SAX events back into an XML document. In other words, using an
     `XMLGenerator' as the content handler will reproduce the original
     document being parsed. OUT should be a file-like object which will
     default to SYS.STDOUT. ENCODING is the encoding of the output
     stream which defaults to `'iso-8859-1''.

`XMLFilterBase(base)'
     This class is designed to sit between an `XMLReader' and the
     client application's event handlers.  By default, it does nothing
     but pass requests up to the reader and events on to the handlers
     unmodified, but subclasses can override specific methods to modify
     the event stream or the configuration requests as they pass
     through.

`prepare_input_source(source[, base])'
     This function takes an input source and an optional base URL and
     returns a fully resolved `InputSource' object ready for reading.
     The input source can be given as a string, a file-like object, or
     an `InputSource' object; parsers will use this function to
     implement the polymorphic SOURCE argument to their `parse()'
     method.


File: python-lib.info,  Node: xml.sax.xmlreader,  Next: xmllib,  Prev: xml.sax.saxutils,  Up: Structured Markup Processing Tools

Interface for XML parsers
=========================

   Interface which SAX-compliant XML parsers must implement.

   This section was written by Martin v. L"owis
<loewis@informatik.hu-berlin.de>.
This module was documented by Lars Marius Garshol
<larsga@garshol.priv.no>.
_Added in Python version 2.0_

   SAX parsers implement the `XMLReader' interface. They are
implemented in a Python module, which must provide a function
`create_parser()'. This function is invoked by `xml.sax.make_parser()'
with no arguments to create a new parser object.

`XMLReader()'
     Base class which can be inherited by SAX parsers.

`IncrementalParser()'
     In some cases, it is desirable not to parse an input source at
     once, but to feed chunks of the document as they get available.
     Note that the reader will normally not read the entire file, but
     read it in chunks as well; still `parse()' won't return until the
     entire document is processed. So these interfaces should be used
     if the blocking behaviour of `parse()' is not desirable.

     When the parser is instantiated it is ready to begin accepting data
     from the feed method immediately. After parsing has been finished
     with a call to close the reset method must be called to make the
     parser ready to accept new data, either from feed or using the
     parse method.

     Note that these methods must _not_ be called during parsing, that
     is, after parse has been called and before it returns.

     By default, the class also implements the parse method of the
     XMLReader interface using the feed, close and reset methods of the
     IncrementalParser interface as a convenience to SAX 2.0 driver
     writers.

`Locator()'
     Interface for associating a SAX event with a document location. A
     locator object will return valid results only during calls to
     DocumentHandler methods; at any other time, the results are
     unpredictable. If information is not available, methods may return
     `None'.

`InputSource([systemId])'
     Encapsulation of the information needed by the `XMLReader' to read
     entities.

     This class may include information about the public identifier,
     system identifier, byte stream (possibly with character encoding
     information) and/or the character stream of an entity.

     Applications will create objects of this class for use in the
     `XMLReader.parse()' method and for returning from
     EntityResolver.resolveEntity.

     An `InputSource' belongs to the application, the `XMLReader' is
     not allowed to modify `InputSource' objects passed to it from the
     application, although it may make copies and modify those.

`AttributesImpl(attrs)'
     This is a dictionary-like object which represents the element
     attributes in a `startElement()' call. In addition to the most
     useful dictionary operations, it supports a number of other
     methods as described below. Objects of this class should be
     instantiated by readers; ATTRS must be a dictionary-like object.

`AttributesNSImpl(attrs, qnames)'
     Namespace-aware variant of attributes, which will be passed to
     `startElementNS()'. It is derived from `AttributesImpl', but
     understands attribute names as two-tuples of NAMESPACEURI and
     LOCALNAME. In addition, it provides a number of methods expecting
     qualified names as they appear in the original document.

* Menu:

* XMLReader Objects::
* IncrementalParser Objects::
* Locator Objects::
* InputSource Objects::
* AttributesImpl Objects::
* AttributesNSImpl Objects::


File: python-lib.info,  Node: XMLReader Objects,  Next: IncrementalParser Objects,  Prev: xml.sax.xmlreader,  Up: xml.sax.xmlreader

XMLReader Objects
-----------------

   The `XMLReader' interface supports the following methods:

`parse(source)'
     Process an input source, producing SAX events. The SOURCE object
     can be a system identifier (i.e. a string identifying the input
     source - typically a file name or an URL), a file-like object, or
     an `InputSource' object. When `parse()' returns, the input is
     completely processed, and the parser object can be discarded or
     reset. As a limitation, the current implementation only accepts
     byte streams; processing of character streams is for further study.

`getContentHandler()'
     Return the current `ContentHandler'.

`setContentHandler(handler)'
     Set the current `ContentHandler'.  If no `ContentHandler' is set,
     content events will be discarded.

`getDTDHandler()'
     Return the current `DTDHandler'.

`setDTDHandler(handler)'
     Set the current `DTDHandler'.  If no `DTDHandler' is set, DTD
     events will be discarded.

`getEntityResolver()'
     Return the current `EntityResolver'.

`setEntityResolver(handler)'
     Set the current `EntityResolver'.  If no `EntityResolver' is set,
     attempts to resolve an external entity will result in opening the
     system identifier for the entity, and fail if it is not available.

`getErrorHandler()'
     Return the current `ErrorHandler'.

`setErrorHandler(handler)'
     Set the current error handler.  If no `ErrorHandler' is set,
     errors will be raised as exceptions, and warnings will be printed.

`setLocale(locale)'
     Allow an application to set the locale for errors and warnings.

     SAX parsers are not required to provide localization for errors and
     warnings; if they cannot support the requested locale, however,
     they must throw a SAX exception.  Applications may request a
     locale change in the middle of a parse.

`getFeature(featurename)'
     Return the current setting for feature FEATURENAME.  If the
     feature is not recognized, `SAXNotRecognizedException' is raised.
     The well-known featurenames are listed in the module
     `xml.sax.handler'.

`setFeature(featurename, value)'
     Set the FEATURENAME to VALUE. If the feature is not recognized,
     `SAXNotRecognizedException' is raised. If the feature or its
     setting is not supported by the parser, SAXNOTSUPPORTEDEXCEPTION
     is raised.

`getProperty(propertyname)'
     Return the current setting for property PROPERTYNAME. If the
     property is not recognized, a `SAXNotRecognizedException' is
     raised. The well-known propertynames are listed in the module
     `xml.sax.handler'.

`setProperty(propertyname, value)'
     Set the PROPERTYNAME to VALUE. If the property is not recognized,
     `SAXNotRecognizedException' is raised. If the property or its
     setting is not supported by the parser, SAXNOTSUPPORTEDEXCEPTION
     is raised.


File: python-lib.info,  Node: IncrementalParser Objects,  Next: Locator Objects,  Prev: XMLReader Objects,  Up: xml.sax.xmlreader

IncrementalParser Objects
-------------------------

   Instances of `IncrementalParser' offer the following additional
methods:

`feed(data)'
     Process a chunk of DATA.

`close()'
     Assume the end of the document. That will check well-formedness
     conditions that can be checked only at the end, invoke handlers,
     and may clean up resources allocated during parsing.

`reset()'
     This method is called after close has been called to reset the
     parser so that it is ready to parse new documents. The results of
     calling parse or feed after close without calling reset are
     undefined."""


File: python-lib.info,  Node: Locator Objects,  Next: InputSource Objects,  Prev: IncrementalParser Objects,  Up: xml.sax.xmlreader

Locator Objects
---------------

   Instances of `Locator' provide these methods:

`getColumnNumber()'
     Return the column number where the current event ends.

`getLineNumber()'
     Return the line number where the current event ends.

`getPublicId()'
     Return the public identifier for the current event.

`getSystemId()'
     Return the system identifier for the current event.


File: python-lib.info,  Node: InputSource Objects,  Next: AttributesImpl Objects,  Prev: Locator Objects,  Up: xml.sax.xmlreader

InputSource Objects
-------------------

`setPublicId(id)'
     Sets the public identifier of this `InputSource'.

`getPublicId()'
     Returns the public identifier of this `InputSource'.

`setSystemId(id)'
     Sets the system identifier of this `InputSource'.

`getSystemId()'
     Returns the system identifier of this `InputSource'.

`setEncoding(encoding)'
     Sets the character encoding of this `InputSource'.

     The encoding must be a string acceptable for an XML encoding
     declaration (see section 4.3.3 of the XML recommendation).

     The encoding attribute of the `InputSource' is ignored if the
     `InputSource' also contains a character stream.

`getEncoding()'
     Get the character encoding of this InputSource.

`setByteStream(bytefile)'
     Set the byte stream (a Python file-like object which does not
     perform byte-to-character conversion) for this input source.

     The SAX parser will ignore this if there is also a character stream
     specified, but it will use a byte stream in preference to opening a
     URI connection itself.

     If the application knows the character encoding of the byte stream,
     it should set it with the setEncoding method.

`getByteStream()'
     Get the byte stream for this input source.

     The getEncoding method will return the character encoding for this
     byte stream, or None if unknown.

`setCharacterStream(charfile)'
     Set the character stream for this input source. (The stream must be
     a Python 1.6 Unicode-wrapped file-like that performs conversion to
     Unicode strings.)

     If there is a character stream specified, the SAX parser will
     ignore any byte stream and will not attempt to open a URI
     connection to the system identifier.

`getCharacterStream()'
     Get the character stream for this input source.


File: python-lib.info,  Node: AttributesImpl Objects,  Next: AttributesNSImpl Objects,  Prev: InputSource Objects,  Up: xml.sax.xmlreader

AttributesImpl Objects
----------------------

   `AttributesImpl' objects implement a portion of the mapping
protocol, and the methods `copy()', `get()', `has_key()', `items()',
`keys()', and `values()'.  The following methods are also provided:

`getLength()'
     Return the number of attributes.

`getNames()'
     Return the names of the attributes.

`getType(name)'
     Returns the type of the attribute NAME, which is normally
     `'CDATA''.

`getValue(name)'
     Return the value of attribute NAME.


File: python-lib.info,  Node: AttributesNSImpl Objects,  Prev: AttributesImpl Objects,  Up: xml.sax.xmlreader

AttributesNSImpl Objects
------------------------

`getValueByQName(name)'
     Return the value for a qualified name.

`getNameByQName(name)'
     Return the `(NAMESPACE, LOCALNAME)' pair for a qualified NAME.

`getQNameByName(name)'
     Return the qualified name for a `(NAMESPACE, LOCALNAME)' pair.

`getQNames()'
     Return the qualified names of all attributes.


File: python-lib.info,  Node: xmllib,  Prev: xml.sax.xmlreader,  Up: Structured Markup Processing Tools

A parser for XML documents
==========================

   A parser for XML documents.  This module was documented by Sjoerd
Mullender <Sjoerd.Mullender@cwi.nl>.
This section was written by Sjoerd Mullender <Sjoerd.Mullender@cwi.nl>.
_This is deprecated in Python 2.0.  Use `xml.sax' instead.  The newer
XML package includes full support for XML 1.0._

   _Changed in Python version 1.5.2_

   This module defines a class `XMLParser' which serves as the basis
for parsing text files formatted in XML (Extensible Markup Language).

`XMLParser()'
     The `XMLParser' class must be instantiated without arguments.(1)

   This class provides the following interface methods and instance
variables:

`attributes'
     A mapping of element names to mappings.  The latter mapping maps
     attribute names that are valid for the element to the default
     value of the attribute, or if there is no default to `None'.  The
     default value is the empty dictionary.  This variable is meant to
     be overridden, not extended since the default is shared by all
     instances of `XMLParser'.

`elements'
     A mapping of element names to tuples.  The tuples contain a
     function for handling the start and end tag respectively of the
     element, or `None' if the method `unknown_starttag()' or
     `unknown_endtag()' is to be called.  The default value is the
     empty dictionary.  This variable is meant to be overridden, not
     extended since the default is shared by all instances of
     `XMLParser'.

`entitydefs'
     A mapping of entitynames to their values.  The default value
     contains definitions for `'lt'', `'gt'', `'amp'', `'quot'', and
     `'apos''.

`reset()'
     Reset the instance.  Loses all unprocessed data.  This is called
     implicitly at the instantiation time.

`setnomoretags()'
     Stop processing tags.  Treat all following input as literal input
     (CDATA).

`setliteral()'
     Enter literal mode (CDATA mode).  This mode is automatically exited
     when the close tag matching the last unclosed open tag is
     encountered.

`feed(data)'
     Feed some text to the parser.  It is processed insofar as it
     consists of complete tags; incomplete data is buffered until more
     data is fed or `close()' is called.

`close()'
     Force processing of all buffered data as if it were followed by an
     end-of-file mark.  This method may be redefined by a derived class
     to define additional processing at the end of the input, but the
     redefined version should always call `close()'.

`translate_references(data)'
     Translate all entity and character references in DATA and return
     the translated string.

`getnamespace()'
     Return a mapping of namespace abbreviations to namespace URIs that
     are currently in effect.

`handle_xml(encoding, standalone)'
     This method is called when the `<?xml ...?>' tag is processed.
     The arguments are the values of the encoding and standalone
     attributes in the tag.  Both encoding and standalone are optional.
     The values passed to `handle_xml()' default to `None' and the
     string `'no'' respectively.

`handle_doctype(tag, pubid, syslit, data)'
     This method is called when the `<!DOCTYPE...>' declaration is
     processed.  The arguments are the tag name of the root element,
     the Formal Public Identifier (or `None' if not specified), the
     system identifier, and the uninterpreted contents of the internal
     DTD subset as a string (or `None' if not present).

`handle_starttag(tag, method, attributes)'
     This method is called to handle start tags for which a start tag
     handler is defined in the instance variable `elements'.  The TAG
     argument is the name of the tag, and the METHOD argument is the
     function (method) which should be used to support semantic
     interpretation of the start tag.  The ATTRIBUTES argument is a
     dictionary of attributes, the key being the NAME and the value
     being the VALUE of the attribute found inside the tag's `<>'
     brackets.  Character and entity references in the VALUE have been
     interpreted.  For instance, for the start tag `<A
     HREF="http://www.cwi.nl/">', this method would be called as
     `handle_starttag('A', self.elements['A'][0], {'HREF':
     'http://www.cwi.nl/'})'.  The base implementation simply calls
     METHOD with ATTRIBUTES as the only argument.

`handle_endtag(tag, method)'
     This method is called to handle endtags for which an end tag
     handler is defined in the instance variable `elements'.  The TAG
     argument is the name of the tag, and the METHOD argument is the
     function (method) which should be used to support semantic
     interpretation of the end tag.  For instance, for the endtag
     `</A>', this method would be called as `handle_endtag('A',
     self.elements['A'][1])'.  The base implementation simply calls
     METHOD.

`handle_data(data)'
     This method is called to process arbitrary data.  It is intended
     to be overridden by a derived class; the base class implementation
     does nothing.

`handle_charref(ref)'
     This method is called to process a character reference of the form
     `&#REF;'.  REF can either be a decimal number, or a hexadecimal
     number when preceded by an `x'.  In the base implementation, REF
     must be a number in the range 0-255.  It translates the character
     to ASCII and calls the method `handle_data()' with the character
     as argument.  If REF is invalid or out of range, the method
     `unknown_charref(REF)' is called to handle the error.  A subclass
     must override this method to provide support for character
     references outside of the ASCII range.

`handle_comment(comment)'
     This method is called when a comment is encountered.  The COMMENT
     argument is a string containing the text between the `<!--' and
     `-->' delimiters, but not the delimiters themselves.  For example,
     the comment `<!--text-->' will cause this method to be called with
     the argument `'text''.  The default method does nothing.

`handle_cdata(data)'
     This method is called when a CDATA element is encountered.  The
     DATA argument is a string containing the text between the
     `<![CDATA[' and `]]>' delimiters, but not the delimiters
     themselves.  For example, the entity `<![CDATA[text]]>' will cause
     this method to be called with the argument `'text''.  The default
     method does nothing, and is intended to be overridden.

`handle_proc(name, data)'
     This method is called when a processing instruction (PI) is
     encountered.  The NAME is the PI target, and the DATA argument is
     a string containing the text between the PI target and the closing
     delimiter, but not the delimiter itself.  For example, the
     instruction `<?XML text?>' will cause this method to be called
     with the arguments `'XML'' and `'text''.  The default method does
     nothing.  Note that if a document starts with `<?xml ..?>',
     `handle_xml()' is called to handle it.

`handle_special(data)'
     This method is called when a declaration is encountered.  The DATA
     argument is a string containing the text between the `<!' and `>'
     delimiters, but not the delimiters themselves.  For example, the
     entity declaration `<!ENTITY text>' will cause this method to be
     called with the argument `'ENTITY text''.  The default method does
     nothing.  Note that `<!DOCTYPE ...>' is handled separately if it
     is located at the start of the document.

`syntax_error(message)'
     This method is called when a syntax error is encountered.  The
     MESSAGE is a description of what was wrong.  The default method
     raises a `RuntimeError' exception.  If this method is overridden,
     it is permissible for it to return.  This method is only called
     when the error can be recovered from.  Unrecoverable errors raise
     a `RuntimeError' without first calling `syntax_error()'.

`unknown_starttag(tag, attributes)'
     This method is called to process an unknown start tag.  It is
     intended to be overridden by a derived class; the base class
     implementation does nothing.

`unknown_endtag(tag)'
     This method is called to process an unknown end tag.  It is
     intended to be overridden by a derived class; the base class
     implementation does nothing.

`unknown_charref(ref)'
     This method is called to process unresolvable numeric character
     references.  It is intended to be overridden by a derived class;
     the base class implementation does nothing.

`unknown_entityref(ref)'
     This method is called to process an unknown entity reference.  It
     is intended to be overridden by a derived class; the base class
     implementation calls `syntax_error()' to signal an error.

   See also:

   `Extensible Markup Language (XML) 1.0'{The XML specification,
published by the World Wide Web Consortium (W3C), defines the syntax
and processor requirements for XML.  References to additional material
on XML, including translations of the specification, are available at
<http://www.w3.org/XML/>.}

   `Python and XML Processing'{The Python XML Topic Guide provides a
great deal of information on using XML from Python and links to other
sources of information on XML.}

   `SIG for XML Processing in Python'{The Python XML Special Interest
Group is developing substantial support for processing XML from Python.}

* Menu:

* XML Namespaces::

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

   (1) Actually, a number of keyword arguments are recognized which
influence the parser to accept certain non-standard constructs.  The
following keyword arguments are currently recognized.  The defaults for
all of these is `0' (false) except for the last one for which the
default is `1' (true). ACCEPT_UNQUOTED_ATTRIBUTES (accept certain
attribute values without requiring quotes), ACCEPT_MISSING_ENDTAG_NAME
(accept end tags that look like `</>'), MAP_CASE (map upper case to
lower case in tags and attributes), ACCEPT_UTF8 (allow UTF-8 characters
in input; this is required according to the XML standard, but Python
does not as yet deal properly with these characters, so this is not the
default), TRANSLATE_ATTRIBUTE_REFERENCES (don't attempt to translate
character and entity references in attribute values).


File: python-lib.info,  Node: XML Namespaces,  Prev: xmllib,  Up: xmllib

XML Namespaces
--------------

   This module has support for XML namespaces as defined in the XML
Namespaces proposed recommendation.

   Tag and attribute names that are defined in an XML namespace are
handled as if the name of the tag or element consisted of the namespace
(i.e. the URL that defines the namespace) followed by a space and the
name of the tag or attribute.  For instance, the tag `<html
xmlns='http://www.w3.org/TR/REC-html40'>' is treated as if the tag name
was `'http://www.w3.org/TR/REC-html40 html'', and the tag `<html:a
href='http://frob.com'>' inside the above mentioned element is treated
as if the tag name were `'http://www.w3.org/TR/REC-html40 a'' and the
attribute name as if it were `'http://www.w3.org/TR/REC-html40 href''.

   An older draft of the XML Namespaces proposal is also recognized, but
triggers a warning.

   See also:

   `Namespaces in XML'{ This World-Wide Web Consortium recommendation
describes the proper syntax and processing requirements for namespaces
in XML.}


File: python-lib.info,  Node: Multimedia Services,  Next: Cryptographic Services,  Prev: Structured Markup Processing Tools,  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 fragment
     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 tuple `(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
     thresholding 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.  MODE must be `'r'' or
     `'rb'' when the file must be opened for reading, or `'w'' or
     `'wb'' when the file must be opened for writing.  If omitted,
     `FILE.mode' is used if it exists, otherwise `'rb'' is used.  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 <moshez@zadka.site.co.il>.
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'.

   An audio file consists of a header followed by the data.  The fields
of the header are:

Field                                Contents
------                               -----
magic word                           The four bytes `.snd'.
header size                          Size of the header, including info,
                                     in bytes.
data size                            Physical size of the data, in bytes.
encoding                             Indicates how the audio samples are
                                     encoded.
sample rate                          The sampling rate.
# of channels                        The number of channels in the
                                     samples.
info                                 ASCII string giving a description
                                     of the audio file (padded with null
                                     bytes).

   Apart from the info field, all header fields are 4 bytes in size.
They are all 32-bit unsigned integers encoded in big-endian byte order.

   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 items:

`AUDIO_FILE_MAGIC'
     An integer every valid Sun AU file begins with, stored in
     big-endian form.  This is the string `.snd' interpreted as an
     integer.

`AUDIO_FILE_ENCODING_MULAW_8'

`AUDIO_FILE_ENCODING_LINEAR_8'

`AUDIO_FILE_ENCODING_LINEAR_16'

`AUDIO_FILE_ENCODING_LINEAR_24'

`AUDIO_FILE_ENCODING_LINEAR_32'

`AUDIO_FILE_ENCODING_ALAW_8'
     Values of the encoding field from the AU header which are
     supported by this module.

`AUDIO_FILE_ENCODING_FLOAT'

`AUDIO_FILE_ENCODING_DOUBLE'

`AUDIO_FILE_ENCODING_ADPCM_G721'

`AUDIO_FILE_ENCODING_ADPCM_G722'

`AUDIO_FILE_ENCODING_ADPCM_G723_3'

`AUDIO_FILE_ENCODING_ADPCM_G723_5'
     Additional known values of the encoding field from the AU header,
     but which are not supported by this module.

* 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.
     The data will be returned in linear format.  If the original data
     is in u-LAW format, it will be converted.

`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 dependent.

`setpos(pos)'
     Set the file pointer to the specified position.  Only values
     returned from `tell()' should be used for POS.

`tell()'
     Return current file pointer position.  Note that the returned value
     has nothing to do with the actual position in the file.

   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.

