]> git.sesse.net Git - ffmpeg/blob - libavcodec/resample.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / resample.c
1 /*
2  * samplerate conversion for both audio and video
3  * Copyright (c) 2000 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * samplerate conversion for both audio and video
25  */
26
27 #include "avcodec.h"
28 #include "audioconvert.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/samplefmt.h"
31
32 #define MAX_CHANNELS 8
33
34 struct AVResampleContext;
35
36 static const char *context_to_name(void *ptr)
37 {
38     return "audioresample";
39 }
40
41 static const AVOption options[] = {{NULL}};
42 static const AVClass audioresample_context_class = {
43     "ReSampleContext", context_to_name, options, LIBAVUTIL_VERSION_INT
44 };
45
46 struct ReSampleContext {
47     struct AVResampleContext *resample_context;
48     short *temp[MAX_CHANNELS];
49     int temp_len;
50     float ratio;
51     /* channel convert */
52     int input_channels, output_channels, filter_channels;
53     AVAudioConvert *convert_ctx[2];
54     enum AVSampleFormat sample_fmt[2]; ///< input and output sample format
55     unsigned sample_size[2];           ///< size of one sample in sample_fmt
56     short *buffer[2];                  ///< buffers used for conversion to S16
57     unsigned buffer_size[2];           ///< sizes of allocated buffers
58 };
59
60 /* n1: number of samples */
61 static void stereo_to_mono(short *output, short *input, int n1)
62 {
63     short *p, *q;
64     int n = n1;
65
66     p = input;
67     q = output;
68     while (n >= 4) {
69         q[0] = (p[0] + p[1]) >> 1;
70         q[1] = (p[2] + p[3]) >> 1;
71         q[2] = (p[4] + p[5]) >> 1;
72         q[3] = (p[6] + p[7]) >> 1;
73         q += 4;
74         p += 8;
75         n -= 4;
76     }
77     while (n > 0) {
78         q[0] = (p[0] + p[1]) >> 1;
79         q++;
80         p += 2;
81         n--;
82     }
83 }
84
85 /* n1: number of samples */
86 static void mono_to_stereo(short *output, short *input, int n1)
87 {
88     short *p, *q;
89     int n = n1;
90     int v;
91
92     p = input;
93     q = output;
94     while (n >= 4) {
95         v = p[0]; q[0] = v; q[1] = v;
96         v = p[1]; q[2] = v; q[3] = v;
97         v = p[2]; q[4] = v; q[5] = v;
98         v = p[3]; q[6] = v; q[7] = v;
99         q += 8;
100         p += 4;
101         n -= 4;
102     }
103     while (n > 0) {
104         v = p[0]; q[0] = v; q[1] = v;
105         q += 2;
106         p += 1;
107         n--;
108     }
109 }
110
111 /*
112 5.1 to stereo input: [fl, fr, c, lfe, rl, rr]
113 - Left = front_left + rear_gain * rear_left + center_gain * center
114 - Right = front_right + rear_gain * rear_right + center_gain * center
115 Where rear_gain is usually around 0.5-1.0 and
116       center_gain is almost always 0.7 (-3 dB)
117 */
118 static void surround_to_stereo(short **output, short *input, int channels, int samples)
119 {
120     int i;
121     short l, r;
122
123     for (i = 0; i < samples; i++) {
124         int fl,fr,c,rl,rr;
125         fl = input[0];
126         fr = input[1];
127         c = input[2];
128         // lfe = input[3];
129         rl = input[4];
130         rr = input[5];
131
132         l = av_clip_int16(fl + (0.5 * rl) + (0.7 * c));
133         r = av_clip_int16(fr + (0.5 * rr) + (0.7 * c));
134
135         /* output l & r. */
136         *output[0]++ = l;
137         *output[1]++ = r;
138
139         /* increment input. */
140         input += channels;
141     }
142 }
143
144 static void deinterleave(short **output, short *input, int channels, int samples)
145 {
146     int i, j;
147
148     for (i = 0; i < samples; i++) {
149         for (j = 0; j < channels; j++) {
150             *output[j]++ = *input++;
151         }
152     }
153 }
154
155 static void interleave(short *output, short **input, int channels, int samples)
156 {
157     int i, j;
158
159     for (i = 0; i < samples; i++) {
160         for (j = 0; j < channels; j++) {
161             *output++ = *input[j]++;
162         }
163     }
164 }
165
166 static void ac3_5p1_mux(short *output, short *input1, short *input2, int n)
167 {
168     int i;
169     short l, r;
170
171     for (i = 0; i < n; i++) {
172         l = *input1++;
173         r = *input2++;
174         *output++ = l;                  /* left */
175         *output++ = (l / 2) + (r / 2);  /* center */
176         *output++ = r;                  /* right */
177         *output++ = 0;                  /* left surround */
178         *output++ = 0;                  /* right surroud */
179         *output++ = 0;                  /* low freq */
180     }
181 }
182
183 #define SUPPORT_RESAMPLE(ch1, ch2, ch3, ch4, ch5, ch6, ch7, ch8) \
184     ch8<<7 | ch7<<6 | ch6<<5 | ch5<<4 | ch4<<3 | ch3<<2 | ch2<<1 | ch1<<0
185
186 static const uint8_t supported_resampling[MAX_CHANNELS] = {
187     // output ch:    1  2  3  4  5  6  7  8
188     SUPPORT_RESAMPLE(1, 1, 0, 0, 0, 0, 0, 0), // 1 input channel
189     SUPPORT_RESAMPLE(1, 1, 0, 0, 0, 1, 0, 0), // 2 input channels
190     SUPPORT_RESAMPLE(0, 0, 1, 0, 0, 0, 0, 0), // 3 input channels
191     SUPPORT_RESAMPLE(0, 0, 0, 1, 0, 0, 0, 0), // 4 input channels
192     SUPPORT_RESAMPLE(0, 0, 0, 0, 1, 0, 0, 0), // 5 input channels
193     SUPPORT_RESAMPLE(0, 1, 0, 0, 0, 1, 0, 0), // 6 input channels
194     SUPPORT_RESAMPLE(0, 0, 0, 0, 0, 0, 1, 0), // 7 input channels
195     SUPPORT_RESAMPLE(0, 0, 0, 0, 0, 0, 0, 1), // 8 input channels
196 };
197
198 ReSampleContext *av_audio_resample_init(int output_channels, int input_channels,
199                                         int output_rate, int input_rate,
200                                         enum AVSampleFormat sample_fmt_out,
201                                         enum AVSampleFormat sample_fmt_in,
202                                         int filter_length, int log2_phase_count,
203                                         int linear, double cutoff)
204 {
205     ReSampleContext *s;
206
207     if (input_channels > MAX_CHANNELS) {
208         av_log(NULL, AV_LOG_ERROR,
209                "Resampling with input channels greater than %d is unsupported.\n",
210                MAX_CHANNELS);
211         return NULL;
212     }
213     if (!(supported_resampling[input_channels-1] & (1<<(output_channels-1)))) {
214         int i;
215         av_log(NULL, AV_LOG_ERROR, "Unsupported audio resampling. Allowed "
216                "output channels for %d input channel%s", input_channels,
217                input_channels > 1 ? "s:" : ":");
218         for (i = 0; i < MAX_CHANNELS; i++)
219             if (supported_resampling[input_channels-1] & (1<<i))
220                 av_log(NULL, AV_LOG_ERROR, " %d", i + 1);
221         av_log(NULL, AV_LOG_ERROR, "\n");
222         return NULL;
223     }
224
225     s = av_mallocz(sizeof(ReSampleContext));
226     if (!s) {
227         av_log(NULL, AV_LOG_ERROR, "Can't allocate memory for resample context.\n");
228         return NULL;
229     }
230
231     s->ratio = (float)output_rate / (float)input_rate;
232
233     s->input_channels = input_channels;
234     s->output_channels = output_channels;
235
236     s->filter_channels = s->input_channels;
237     if (s->output_channels < s->filter_channels)
238         s->filter_channels = s->output_channels;
239
240     s->sample_fmt[0]  = sample_fmt_in;
241     s->sample_fmt[1]  = sample_fmt_out;
242     s->sample_size[0] = av_get_bytes_per_sample(s->sample_fmt[0]);
243     s->sample_size[1] = av_get_bytes_per_sample(s->sample_fmt[1]);
244
245     if (s->sample_fmt[0] != AV_SAMPLE_FMT_S16) {
246         if (!(s->convert_ctx[0] = av_audio_convert_alloc(AV_SAMPLE_FMT_S16, 1,
247                                                          s->sample_fmt[0], 1, NULL, 0))) {
248             av_log(s, AV_LOG_ERROR,
249                    "Cannot convert %s sample format to s16 sample format\n",
250                    av_get_sample_fmt_name(s->sample_fmt[0]));
251             av_free(s);
252             return NULL;
253         }
254     }
255
256     if (s->sample_fmt[1] != AV_SAMPLE_FMT_S16) {
257         if (!(s->convert_ctx[1] = av_audio_convert_alloc(s->sample_fmt[1], 1,
258                                                          AV_SAMPLE_FMT_S16, 1, NULL, 0))) {
259             av_log(s, AV_LOG_ERROR,
260                    "Cannot convert s16 sample format to %s sample format\n",
261                    av_get_sample_fmt_name(s->sample_fmt[1]));
262             av_audio_convert_free(s->convert_ctx[0]);
263             av_free(s);
264             return NULL;
265         }
266     }
267
268 #define TAPS 16
269     s->resample_context = av_resample_init(output_rate, input_rate,
270                                            filter_length, log2_phase_count,
271                                            linear, cutoff);
272
273     *(const AVClass**)s->resample_context = &audioresample_context_class;
274
275     return s;
276 }
277
278 /* resample audio. 'nb_samples' is the number of input samples */
279 /* XXX: optimize it ! */
280 int audio_resample(ReSampleContext *s, short *output, short *input, int nb_samples)
281 {
282     int i, nb_samples1;
283     short *bufin[MAX_CHANNELS];
284     short *bufout[MAX_CHANNELS];
285     short *buftmp2[MAX_CHANNELS], *buftmp3[MAX_CHANNELS];
286     short *output_bak = NULL;
287     int lenout;
288
289     if (s->input_channels == s->output_channels && s->ratio == 1.0 && 0) {
290         /* nothing to do */
291         memcpy(output, input, nb_samples * s->input_channels * sizeof(short));
292         return nb_samples;
293     }
294
295     if (s->sample_fmt[0] != AV_SAMPLE_FMT_S16) {
296         int istride[1] = { s->sample_size[0] };
297         int ostride[1] = { 2 };
298         const void *ibuf[1] = { input };
299         void       *obuf[1];
300         unsigned input_size = nb_samples * s->input_channels * 2;
301
302         if (!s->buffer_size[0] || s->buffer_size[0] < input_size) {
303             av_free(s->buffer[0]);
304             s->buffer_size[0] = input_size;
305             s->buffer[0] = av_malloc(s->buffer_size[0]);
306             if (!s->buffer[0]) {
307                 av_log(s->resample_context, AV_LOG_ERROR, "Could not allocate buffer\n");
308                 return 0;
309             }
310         }
311
312         obuf[0] = s->buffer[0];
313
314         if (av_audio_convert(s->convert_ctx[0], obuf, ostride,
315                              ibuf, istride, nb_samples * s->input_channels) < 0) {
316             av_log(s->resample_context, AV_LOG_ERROR,
317                    "Audio sample format conversion failed\n");
318             return 0;
319         }
320
321         input = s->buffer[0];
322     }
323
324     lenout= 2*s->output_channels*nb_samples * s->ratio + 16;
325
326     if (s->sample_fmt[1] != AV_SAMPLE_FMT_S16) {
327         output_bak = output;
328
329         if (!s->buffer_size[1] || s->buffer_size[1] < lenout) {
330             av_free(s->buffer[1]);
331             s->buffer_size[1] = lenout;
332             s->buffer[1] = av_malloc(s->buffer_size[1]);
333             if (!s->buffer[1]) {
334                 av_log(s->resample_context, AV_LOG_ERROR, "Could not allocate buffer\n");
335                 return 0;
336             }
337         }
338
339         output = s->buffer[1];
340     }
341
342     /* XXX: move those malloc to resample init code */
343     for (i = 0; i < s->filter_channels; i++) {
344         bufin[i] = av_malloc((nb_samples + s->temp_len) * sizeof(short));
345         memcpy(bufin[i], s->temp[i], s->temp_len * sizeof(short));
346         buftmp2[i] = bufin[i] + s->temp_len;
347         bufout[i] = av_malloc(lenout * sizeof(short));
348     }
349
350     if (s->input_channels == 2 && s->output_channels == 1) {
351         buftmp3[0] = output;
352         stereo_to_mono(buftmp2[0], input, nb_samples);
353     } else if (s->output_channels >= 2 && s->input_channels == 1) {
354         buftmp3[0] = bufout[0];
355         memcpy(buftmp2[0], input, nb_samples * sizeof(short));
356     } else if (s->input_channels == 6 && s->output_channels ==2) {
357         buftmp3[0] = bufout[0];
358         buftmp3[1] = bufout[1];
359         surround_to_stereo(buftmp2, input, s->input_channels, nb_samples);
360     } else if (s->output_channels >= s->input_channels && s->input_channels >= 2) {
361         for (i = 0; i < s->input_channels; i++) {
362             buftmp3[i] = bufout[i];
363         }
364         deinterleave(buftmp2, input, s->input_channels, nb_samples);
365     } else {
366         buftmp3[0] = output;
367         memcpy(buftmp2[0], input, nb_samples * sizeof(short));
368     }
369
370     nb_samples += s->temp_len;
371
372     /* resample each channel */
373     nb_samples1 = 0; /* avoid warning */
374     for (i = 0; i < s->filter_channels; i++) {
375         int consumed;
376         int is_last = i + 1 == s->filter_channels;
377
378         nb_samples1 = av_resample(s->resample_context, buftmp3[i], bufin[i],
379                                   &consumed, nb_samples, lenout, is_last);
380         s->temp_len = nb_samples - consumed;
381         s->temp[i] = av_realloc(s->temp[i], s->temp_len * sizeof(short));
382         memcpy(s->temp[i], bufin[i] + consumed, s->temp_len * sizeof(short));
383     }
384
385     if (s->output_channels == 2 && s->input_channels == 1) {
386         mono_to_stereo(output, buftmp3[0], nb_samples1);
387     } else if (s->output_channels == 6 && s->input_channels == 2) {
388         ac3_5p1_mux(output, buftmp3[0], buftmp3[1], nb_samples1);
389     } else if ((s->output_channels == s->input_channels && s->input_channels >= 2) ||
390                (s->output_channels == 2 && s->input_channels == 6)) {
391         interleave(output, buftmp3, s->output_channels, nb_samples1);
392     }
393
394     if (s->sample_fmt[1] != AV_SAMPLE_FMT_S16) {
395         int istride[1] = { 2 };
396         int ostride[1] = { s->sample_size[1] };
397         const void *ibuf[1] = { output };
398         void       *obuf[1] = { output_bak };
399
400         if (av_audio_convert(s->convert_ctx[1], obuf, ostride,
401                              ibuf, istride, nb_samples1 * s->output_channels) < 0) {
402             av_log(s->resample_context, AV_LOG_ERROR,
403                    "Audio sample format convertion failed\n");
404             return 0;
405         }
406     }
407
408     for (i = 0; i < s->filter_channels; i++) {
409         av_free(bufin[i]);
410         av_free(bufout[i]);
411     }
412
413     return nb_samples1;
414 }
415
416 void audio_resample_close(ReSampleContext *s)
417 {
418     int i;
419     av_resample_close(s->resample_context);
420     for (i = 0; i < s->filter_channels; i++)
421         av_freep(&s->temp[i]);
422     av_freep(&s->buffer[0]);
423     av_freep(&s->buffer[1]);
424     av_audio_convert_free(s->convert_ctx[0]);
425     av_audio_convert_free(s->convert_ctx[1]);
426     av_free(s);
427 }