"audioloop" — Manipulation de données audio brutes
**************************************************

======================================================================

Le module "audioop" permet d'effectuer des opérations utiles sur des
fragments sonores. Ceux-ci sont constitués d'échantillons audio, suite
d'entiers signés de taille 8, 16, 24 ou 32 bits. Ils sont sauvegardés
dans des *objets octet-compatibles*. Tous les nombres sont des
entiers, sauf mention particulière.

Modifié dans la version 3.4: Ajout de la prise en charge
d'échantillons 24 bits. Toutes les fonctions acceptent maintenant les
*objets octet-compatibles*. Une chaîne de caractères reçue en entrée
lève immédiatement une erreur.

Ce module prend en charge les encodages de la loi A, de la loi u et
les encodages Intel/DVI ADPCM.

Mis à part quelques opérations plus complexes ne prenant que des
échantillons de 16 bits, la taille de l'échantillon (en octets) est
toujours un paramètre de l'opération.

Le module définit les fonctions et variables suivantes :

exception audioop.error

   Cette exception est levée pour toutes les erreurs, comme un nombre
   inconnu d'octets par échantillon, etc.

audioop.add(fragment1, fragment2, width)

   Renvoie un fragment constitué de l'addition des deux échantillons
   fournis comme paramètres. *width* est la largeur de l'échantillon
   en octets, soit "1", "2", "3" ou "4". Les deux fragments doivent
   avoir la même longueur. Les échantillons sont tronqués en cas de
   débordement.

audioop.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*.

audioop.alaw2lin(fragment, width)

   Convert sound fragments in a-LAW encoding to linearly encoded sound
   fragments. a-LAW encoding always uses 8 bits samples, so *width*
   refers only to the sample width of the output fragment here.

audioop.avg(fragment, width)

   Renvoie la moyenne prise sur l'ensemble des échantillons du
   fragment.

audioop.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.

audioop.bias(fragment, width, bias)

   Return a fragment that is the original fragment with a bias added
   to each sample.  Samples wrap around in case of overflow.

audioop.byteswap(fragment, width)

   "Byteswap" all samples in a fragment and returns the modified
   fragment. Converts big-endian samples to little-endian and vice
   versa.

   Nouveau dans la version 3.4.

audioop.cross(fragment, width)

   Return the number of zero crossings in the fragment passed as an
   argument.

audioop.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.

   Le temps pris par cette routine est proportionnel à
   "len(fragment)".

audioop.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()".

audioop.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.

   La routine s'exécute en un temps proportionnel à "len(fragment)".

audioop.getsample(fragment, width, index)

   Renvoie la valeur de l'échantillon à l'indice *index* dans le
   fragment.

audioop.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.

audioop.lin2alaw(fragment, width)

   Convert samples in the audio fragment to a-LAW encoding and return
   this as a bytes object.  a-LAW is an audio encoding format whereby
   you get a dynamic range of about 13 bits using only 8 bit samples.
   It is used by the Sun audio hardware, among others.

audioop.lin2lin(fragment, width, newwidth)

   Convertit des échantillons pour les formats à 1, 2, 3, et 4 octets.

   Note:

     In some audio formats, such as .WAV files, 16, 24 and 32 bit
     samples are signed, but 8 bit samples are unsigned.  So when
     converting to 8 bit wide samples for these formats, you need to
     also add 128 to the result:

        new_frames = audioop.lin2lin(frames, old_width, 1)
        new_frames = audioop.bias(new_frames, 1, 128)

     Le même procédé, mais inversé, doit être suivi lorsqu'on exécute
     une conversion d'échantillons de 8 bits à 16, 24 ou 32 bits.

audioop.lin2ulaw(fragment, width)

   Convert samples in the audio fragment to u-LAW encoding and return
   this as a bytes object.  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.

audioop.max(fragment, width)

   Renvoie la *valeur absolue* maximale de tous les échantillons du
   fragment.

audioop.maxpp(fragment, width)

   Return the maximum peak-peak value in the sound fragment.

audioop.minmax(fragment, width)

   Renvoie un *n*-uplet contenant les valeurs maximale et minimale de
   tous les échantillons du fragment sonore.

audioop.mul(fragment, width, factor)

   Renvoie un fragment contenant tous les échantillons du fragment
   original multipliés par la valeur à décimale *factor*. Les
   échantillons sont tronqués en cas de débordement.

audioop.ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])

   Transforme la fréquence d'échantillonnage du fragment d'entrée.

   *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 initial call
   should pass "None" as the state.

   Les arguments *weightA* et *weightB* sont les paramètres d'un
   filtre numérique simple et ont comme valeur par défaut "1" et "0",
   respectivement.

audioop.reverse(fragment, width)

   Inverse les échantillons dans un fragment et renvoie le fragment
   modifié.

audioop.rms(fragment, width)

   Renvoie la moyenne quadratique du fragment, c'est-à-dire
   "sqrt(sum(S_i^2)/n)".

   C'est une mesure de la puissance dans un signal audio.

audioop.tomono(fragment, width, lfactor, rfactor)

   Transforme un fragment stéréo en fragment mono. Le canal de gauche
   est multiplié par *lfactor* et le canal de droite par *rfactor*
   avant d'additionner les deux canaux afin d'obtenir un signal mono.

audioop.tostereo(fragment, width, lfactor, rfactor)

   Génère un fragment stéréo à partir d'un fragment mono. Chaque paire
   d'échantillons dans le fragment stéréo est obtenue à partir de
   l'échantillon mono de la façon suivante : les échantillons du canal
   de gauche sont multipliés par *lfactor* et les échantillons du
   canal de droite, par *rfactor*.

audioop.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(lsample, width, lfactor)
       rsample = audioop.mul(rsample, 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)
