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