blob: 8ee2795a9eba04e9ee0322dfd5c495a70208f7bb [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`audioop` --- Manipulate raw audio data
3============================================
4
5.. module:: audioop
6 :synopsis: Manipulate raw audio data.
7
8
9The :mod:`audioop` module contains some useful operations on sound fragments.
10It operates on sound fragments consisting of signed integer samples 8, 16 or 32
11bits wide, stored in Python strings. All scalar items are integers, unless
12specified otherwise.
13
14.. index::
15 single: Intel/DVI ADPCM
16 single: ADPCM, Intel/DVI
17 single: a-LAW
18 single: u-LAW
19
20This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings.
21
Christian Heimes5b5e81c2007-12-31 16:14:33 +000022.. This para is mostly here to provide an excuse for the index entries...
Georg Brandl116aa622007-08-15 14:28:22 +000023
24A few of the more complicated operations only take 16-bit samples, otherwise the
25sample size (in bytes) is always a parameter of the operation.
26
27The module defines the following variables and functions:
28
29
30.. exception:: error
31
32 This exception is raised on all errors, such as unknown number of bytes per
33 sample, etc.
34
35
36.. function:: add(fragment1, fragment2, width)
37
38 Return a fragment which is the addition of the two samples passed as parameters.
39 *width* is the sample width in bytes, either ``1``, ``2`` or ``4``. Both
40 fragments should have the same length.
41
42
43.. function:: adpcm2lin(adpcmfragment, width, state)
44
45 Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See the
46 description of :func:`lin2adpcm` for details on ADPCM coding. Return a tuple
47 ``(sample, newstate)`` where the sample has the width specified in *width*.
48
49
50.. function:: alaw2lin(fragment, width)
51
52 Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.
53 a-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
54 width of the output fragment here.
55
Georg Brandl116aa622007-08-15 14:28:22 +000056
57.. function:: avg(fragment, width)
58
59 Return the average over all samples in the fragment.
60
61
62.. function:: avgpp(fragment, width)
63
64 Return the average peak-peak value over all samples in the fragment. No
65 filtering is done, so the usefulness of this routine is questionable.
66
67
68.. function:: bias(fragment, width, bias)
69
70 Return a fragment that is the original fragment with a bias added to each
71 sample.
72
73
74.. function:: cross(fragment, width)
75
76 Return the number of zero crossings in the fragment passed as an argument.
77
78
79.. function:: findfactor(fragment, reference)
80
81 Return a factor *F* such that ``rms(add(fragment, mul(reference, -F)))`` is
82 minimal, i.e., return the factor with which you should multiply *reference* to
83 make it match as well as possible to *fragment*. The fragments should both
84 contain 2-byte samples.
85
86 The time taken by this routine is proportional to ``len(fragment)``.
87
88
89.. function:: findfit(fragment, reference)
90
91 Try to match *reference* as well as possible to a portion of *fragment* (which
92 should be the longer fragment). This is (conceptually) done by taking slices
93 out of *fragment*, using :func:`findfactor` to compute the best match, and
94 minimizing the result. The fragments should both contain 2-byte samples.
95 Return a tuple ``(offset, factor)`` where *offset* is the (integer) offset into
96 *fragment* where the optimal match started and *factor* is the (floating-point)
97 factor as per :func:`findfactor`.
98
99
100.. function:: findmax(fragment, length)
101
102 Search *fragment* for a slice of length *length* samples (not bytes!) with
103 maximum energy, i.e., return *i* for which ``rms(fragment[i*2:(i+length)*2])``
104 is maximal. The fragments should both contain 2-byte samples.
105
106 The routine takes time proportional to ``len(fragment)``.
107
108
109.. function:: getsample(fragment, width, index)
110
111 Return the value of sample *index* from the fragment.
112
113
114.. function:: lin2adpcm(fragment, width, state)
115
116 Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an adaptive
117 coding scheme, whereby each 4 bit number is the difference between one sample
118 and the next, divided by a (varying) step. The Intel/DVI ADPCM algorithm has
119 been selected for use by the IMA, so it may well become a standard.
120
121 *state* is a tuple containing the state of the coder. The coder returns a tuple
122 ``(adpcmfrag, newstate)``, and the *newstate* should be passed to the next call
123 of :func:`lin2adpcm`. In the initial call, ``None`` can be passed as the state.
124 *adpcmfrag* is the ADPCM coded fragment packed 2 4-bit values per byte.
125
126
127.. function:: lin2alaw(fragment, width)
128
129 Convert samples in the audio fragment to a-LAW encoding and return this as a
130 Python string. a-LAW is an audio encoding format whereby you get a dynamic
131 range of about 13 bits using only 8 bit samples. It is used by the Sun audio
132 hardware, among others.
133
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135.. function:: lin2lin(fragment, width, newwidth)
136
137 Convert samples between 1-, 2- and 4-byte formats.
138
139
140.. function:: lin2ulaw(fragment, width)
141
142 Convert samples in the audio fragment to u-LAW encoding and return this as a
143 Python string. u-LAW is an audio encoding format whereby you get a dynamic
144 range of about 14 bits using only 8 bit samples. It is used by the Sun audio
145 hardware, among others.
146
147
148.. function:: minmax(fragment, width)
149
150 Return a tuple consisting of the minimum and maximum values of all samples in
151 the sound fragment.
152
153
154.. function:: max(fragment, width)
155
156 Return the maximum of the *absolute value* of all samples in a fragment.
157
158
159.. function:: maxpp(fragment, width)
160
161 Return the maximum peak-peak value in the sound fragment.
162
163
164.. function:: mul(fragment, width, factor)
165
166 Return a fragment that has all samples in the original fragment multiplied by
167 the floating-point value *factor*. Overflow is silently ignored.
168
169
170.. function:: ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])
171
172 Convert the frame rate of the input fragment.
173
174 *state* is a tuple containing the state of the converter. The converter returns
175 a tuple ``(newfragment, newstate)``, and *newstate* should be passed to the next
176 call of :func:`ratecv`. The initial call should pass ``None`` as the state.
177
178 The *weightA* and *weightB* arguments are parameters for a simple digital filter
179 and default to ``1`` and ``0`` respectively.
180
181
182.. function:: reverse(fragment, width)
183
184 Reverse the samples in a fragment and returns the modified fragment.
185
186
187.. function:: rms(fragment, width)
188
189 Return the root-mean-square of the fragment, i.e. ``sqrt(sum(S_i^2)/n)``.
190
191 This is a measure of the power in an audio signal.
192
193
194.. function:: tomono(fragment, width, lfactor, rfactor)
195
196 Convert a stereo fragment to a mono fragment. The left channel is multiplied by
197 *lfactor* and the right channel by *rfactor* before adding the two channels to
198 give a mono signal.
199
200
201.. function:: tostereo(fragment, width, lfactor, rfactor)
202
203 Generate a stereo fragment from a mono fragment. Each pair of samples in the
204 stereo fragment are computed from the mono sample, whereby left channel samples
205 are multiplied by *lfactor* and right channel samples by *rfactor*.
206
207
208.. function:: ulaw2lin(fragment, width)
209
210 Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.
211 u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
212 width of the output fragment here.
213
214Note that operations such as :func:`mul` or :func:`max` make no distinction
215between mono and stereo fragments, i.e. all samples are treated equal. If this
216is a problem the stereo fragment should be split into two mono fragments first
217and recombined later. Here is an example of how to do that::
218
219 def mul_stereo(sample, width, lfactor, rfactor):
220 lsample = audioop.tomono(sample, width, 1, 0)
221 rsample = audioop.tomono(sample, width, 0, 1)
222 lsample = audioop.mul(sample, width, lfactor)
223 rsample = audioop.mul(sample, width, rfactor)
224 lsample = audioop.tostereo(lsample, width, 1, 0)
225 rsample = audioop.tostereo(rsample, width, 0, 1)
226 return audioop.add(lsample, rsample, width)
227
228If you use the ADPCM coder to build network packets and you want your protocol
229to be stateless (i.e. to be able to tolerate packet loss) you should not only
230transmit the data but also the state. Note that you should send the *initial*
231state (the one you passed to :func:`lin2adpcm`) along to the decoder, not the
232final state (as returned by the coder). If you want to use
233:func:`struct.struct` to store the state in binary you can code the first
234element (the predicted value) in 16 bits and the second (the delta index) in 8.
235
236The ADPCM coders have never been tried against other ADPCM coders, only against
237themselves. It could well be that I misinterpreted the standards in which case
238they will not be interoperable with the respective standards.
239
240The :func:`find\*` routines might look a bit funny at first sight. They are
241primarily meant to do echo cancellation. A reasonably fast way to do this is to
242pick the most energetic piece of the output sample, locate that in the input
243sample and subtract the whole output sample from the input sample::
244
245 def echocancel(outputdata, inputdata):
246 pos = audioop.findmax(outputdata, 800) # one tenth second
247 out_test = outputdata[pos*2:]
248 in_test = inputdata[pos*2:]
249 ipos, factor = audioop.findfit(in_test, out_test)
250 # Optional (for better cancellation):
251 # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
252 # out_test)
253 prefill = '\0'*(pos+ipos)*2
254 postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
255 outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
256 return audioop.add(inputdata, outputdata, 2)
257