allow sample spec/channel map to be queried for pa_resampler objects
[platform/upstream/pulseaudio.git] / src / pulsecore / resampler.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5
6   PulseAudio is free software; you can redistribute it and/or modify
7   it under the terms of the GNU Lesser General Public License as published
8   by the Free Software Foundation; either version 2 of the License,
9   or (at your option) any later version.
10
11   PulseAudio is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with PulseAudio; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <string.h>
27
28 #ifdef HAVE_LIBSAMPLERATE
29 #include <samplerate.h>
30 #endif
31
32 #include <speex/speex_resampler.h>
33
34 #include <liboil/liboilfuncs.h>
35 #include <liboil/liboil.h>
36
37 #include <pulse/xmalloc.h>
38 #include <pulsecore/sconv.h>
39 #include <pulsecore/log.h>
40 #include <pulsecore/macro.h>
41 #include <pulsecore/strbuf.h>
42
43 #include "ffmpeg/avcodec.h"
44
45 #include "resampler.h"
46
47 /* Number of samples of extra space we allow the resamplers to return */
48 #define EXTRA_FRAMES 128
49
50 struct pa_resampler {
51     pa_resample_method_t method;
52     pa_resample_flags_t flags;
53
54     pa_sample_spec i_ss, o_ss;
55     pa_channel_map i_cm, o_cm;
56     size_t i_fz, o_fz, w_sz;
57     pa_mempool *mempool;
58
59     pa_memchunk buf1, buf2, buf3, buf4;
60     unsigned buf1_samples, buf2_samples, buf3_samples, buf4_samples;
61
62     pa_sample_format_t work_format;
63
64     pa_convert_func_t to_work_format_func;
65     pa_convert_func_t from_work_format_func;
66
67     float map_table[PA_CHANNELS_MAX][PA_CHANNELS_MAX];
68     pa_bool_t map_required;
69
70     void (*impl_free)(pa_resampler *r);
71     void (*impl_update_rates)(pa_resampler *r);
72     void (*impl_resample)(pa_resampler *r, const pa_memchunk *in, unsigned in_samples, pa_memchunk *out, unsigned *out_samples);
73     void (*impl_reset)(pa_resampler *r);
74
75     struct { /* data specific to the trivial resampler */
76         unsigned o_counter;
77         unsigned i_counter;
78     } trivial;
79
80     struct { /* data specific to the peak finder pseudo resampler */
81         unsigned o_counter;
82         unsigned i_counter;
83
84         float max_f[PA_CHANNELS_MAX];
85         int16_t max_i[PA_CHANNELS_MAX];
86
87     } peaks;
88
89 #ifdef HAVE_LIBSAMPLERATE
90     struct { /* data specific to libsamplerate */
91         SRC_STATE *state;
92     } src;
93 #endif
94
95     struct { /* data specific to speex */
96         SpeexResamplerState* state;
97     } speex;
98
99     struct { /* data specific to ffmpeg */
100         struct AVResampleContext *state;
101         pa_memchunk buf[PA_CHANNELS_MAX];
102     } ffmpeg;
103 };
104
105 static int copy_init(pa_resampler *r);
106 static int trivial_init(pa_resampler*r);
107 static int speex_init(pa_resampler*r);
108 static int ffmpeg_init(pa_resampler*r);
109 static int peaks_init(pa_resampler*r);
110 #ifdef HAVE_LIBSAMPLERATE
111 static int libsamplerate_init(pa_resampler*r);
112 #endif
113
114 static void calc_map_table(pa_resampler *r);
115
116 static int (* const init_table[])(pa_resampler*r) = {
117 #ifdef HAVE_LIBSAMPLERATE
118     [PA_RESAMPLER_SRC_SINC_BEST_QUALITY]   = libsamplerate_init,
119     [PA_RESAMPLER_SRC_SINC_MEDIUM_QUALITY] = libsamplerate_init,
120     [PA_RESAMPLER_SRC_SINC_FASTEST]        = libsamplerate_init,
121     [PA_RESAMPLER_SRC_ZERO_ORDER_HOLD]     = libsamplerate_init,
122     [PA_RESAMPLER_SRC_LINEAR]              = libsamplerate_init,
123 #else
124     [PA_RESAMPLER_SRC_SINC_BEST_QUALITY]   = NULL,
125     [PA_RESAMPLER_SRC_SINC_MEDIUM_QUALITY] = NULL,
126     [PA_RESAMPLER_SRC_SINC_FASTEST]        = NULL,
127     [PA_RESAMPLER_SRC_ZERO_ORDER_HOLD]     = NULL,
128     [PA_RESAMPLER_SRC_LINEAR]              = NULL,
129 #endif
130     [PA_RESAMPLER_TRIVIAL]                 = trivial_init,
131     [PA_RESAMPLER_SPEEX_FLOAT_BASE+0]      = speex_init,
132     [PA_RESAMPLER_SPEEX_FLOAT_BASE+1]      = speex_init,
133     [PA_RESAMPLER_SPEEX_FLOAT_BASE+2]      = speex_init,
134     [PA_RESAMPLER_SPEEX_FLOAT_BASE+3]      = speex_init,
135     [PA_RESAMPLER_SPEEX_FLOAT_BASE+4]      = speex_init,
136     [PA_RESAMPLER_SPEEX_FLOAT_BASE+5]      = speex_init,
137     [PA_RESAMPLER_SPEEX_FLOAT_BASE+6]      = speex_init,
138     [PA_RESAMPLER_SPEEX_FLOAT_BASE+7]      = speex_init,
139     [PA_RESAMPLER_SPEEX_FLOAT_BASE+8]      = speex_init,
140     [PA_RESAMPLER_SPEEX_FLOAT_BASE+9]      = speex_init,
141     [PA_RESAMPLER_SPEEX_FLOAT_BASE+10]     = speex_init,
142     [PA_RESAMPLER_SPEEX_FIXED_BASE+0]      = speex_init,
143     [PA_RESAMPLER_SPEEX_FIXED_BASE+1]      = speex_init,
144     [PA_RESAMPLER_SPEEX_FIXED_BASE+2]      = speex_init,
145     [PA_RESAMPLER_SPEEX_FIXED_BASE+3]      = speex_init,
146     [PA_RESAMPLER_SPEEX_FIXED_BASE+4]      = speex_init,
147     [PA_RESAMPLER_SPEEX_FIXED_BASE+5]      = speex_init,
148     [PA_RESAMPLER_SPEEX_FIXED_BASE+6]      = speex_init,
149     [PA_RESAMPLER_SPEEX_FIXED_BASE+7]      = speex_init,
150     [PA_RESAMPLER_SPEEX_FIXED_BASE+8]      = speex_init,
151     [PA_RESAMPLER_SPEEX_FIXED_BASE+9]      = speex_init,
152     [PA_RESAMPLER_SPEEX_FIXED_BASE+10]     = speex_init,
153     [PA_RESAMPLER_FFMPEG]                  = ffmpeg_init,
154     [PA_RESAMPLER_AUTO]                    = NULL,
155     [PA_RESAMPLER_COPY]                    = copy_init,
156     [PA_RESAMPLER_PEAKS]                   = peaks_init,
157 };
158
159 static inline size_t sample_size(pa_sample_format_t f) {
160     pa_sample_spec ss = {
161         .format = f,
162         .rate = 0,
163         .channels = 1
164     };
165
166     return pa_sample_size(&ss);
167 }
168
169 pa_resampler* pa_resampler_new(
170         pa_mempool *pool,
171         const pa_sample_spec *a,
172         const pa_channel_map *am,
173         const pa_sample_spec *b,
174         const pa_channel_map *bm,
175         pa_resample_method_t method,
176         pa_resample_flags_t flags) {
177
178     pa_resampler *r = NULL;
179
180     pa_assert(pool);
181     pa_assert(a);
182     pa_assert(b);
183     pa_assert(pa_sample_spec_valid(a));
184     pa_assert(pa_sample_spec_valid(b));
185     pa_assert(method >= 0);
186     pa_assert(method < PA_RESAMPLER_MAX);
187
188     /* Fix method */
189
190     if (!(flags & PA_RESAMPLER_VARIABLE_RATE) && a->rate == b->rate) {
191         pa_log_info("Forcing resampler 'copy', because of fixed, identical sample rates.");
192         method = PA_RESAMPLER_COPY;
193     }
194
195     if (!pa_resample_method_supported(method)) {
196         pa_log_warn("Support for resampler '%s' not compiled in, reverting to 'auto'.", pa_resample_method_to_string(method));
197         method = PA_RESAMPLER_AUTO;
198     }
199
200     if (method == PA_RESAMPLER_FFMPEG && (flags & PA_RESAMPLER_VARIABLE_RATE)) {
201         pa_log_info("Resampler 'ffmpeg' cannot do variable rate, reverting to resampler 'auto'.");
202         method = PA_RESAMPLER_AUTO;
203     }
204
205     if (method == PA_RESAMPLER_COPY && ((flags & PA_RESAMPLER_VARIABLE_RATE) || a->rate != b->rate)) {
206         pa_log_info("Resampler 'copy' cannot change sampling rate, reverting to resampler 'auto'.");
207         method = PA_RESAMPLER_AUTO;
208     }
209
210     if (method == PA_RESAMPLER_AUTO)
211         method = PA_RESAMPLER_SPEEX_FLOAT_BASE + 3;
212
213     r = pa_xnew(pa_resampler, 1);
214     r->mempool = pool;
215     r->method = method;
216     r->flags = flags;
217
218     r->impl_free = NULL;
219     r->impl_update_rates = NULL;
220     r->impl_resample = NULL;
221     r->impl_reset = NULL;
222
223     /* Fill sample specs */
224     r->i_ss = *a;
225     r->o_ss = *b;
226
227     if (am)
228         r->i_cm = *am;
229     else if (!pa_channel_map_init_auto(&r->i_cm, r->i_ss.channels, PA_CHANNEL_MAP_DEFAULT))
230         goto fail;
231
232     if (bm)
233         r->o_cm = *bm;
234     else if (!pa_channel_map_init_auto(&r->o_cm, r->o_ss.channels, PA_CHANNEL_MAP_DEFAULT))
235         goto fail;
236
237     r->i_fz = pa_frame_size(a);
238     r->o_fz = pa_frame_size(b);
239
240     pa_memchunk_reset(&r->buf1);
241     pa_memchunk_reset(&r->buf2);
242     pa_memchunk_reset(&r->buf3);
243     pa_memchunk_reset(&r->buf4);
244
245     r->buf1_samples = r->buf2_samples = r->buf3_samples = r->buf4_samples = 0;
246
247     calc_map_table(r);
248
249     pa_log_info("Using resampler '%s'", pa_resample_method_to_string(method));
250
251     if ((method >= PA_RESAMPLER_SPEEX_FIXED_BASE && method <= PA_RESAMPLER_SPEEX_FIXED_MAX) ||
252         (method == PA_RESAMPLER_FFMPEG))
253         r->work_format = PA_SAMPLE_S16NE;
254     else if (method == PA_RESAMPLER_TRIVIAL || method == PA_RESAMPLER_COPY || method == PA_RESAMPLER_PEAKS) {
255
256         if (r->map_required || a->format != b->format || method == PA_RESAMPLER_PEAKS) {
257
258             if (a->format == PA_SAMPLE_S32NE || a->format == PA_SAMPLE_S32RE ||
259                 a->format == PA_SAMPLE_FLOAT32NE || a->format == PA_SAMPLE_FLOAT32RE ||
260                 a->format == PA_SAMPLE_S24NE || a->format == PA_SAMPLE_S24RE ||
261                 a->format == PA_SAMPLE_S24_32NE || a->format == PA_SAMPLE_S24_32RE ||
262                 b->format == PA_SAMPLE_S32NE || b->format == PA_SAMPLE_S32RE ||
263                 b->format == PA_SAMPLE_FLOAT32NE || b->format == PA_SAMPLE_FLOAT32RE ||
264                 b->format == PA_SAMPLE_S24NE || b->format == PA_SAMPLE_S24RE ||
265                 b->format == PA_SAMPLE_S24_32NE || b->format == PA_SAMPLE_S24_32RE)
266                 r->work_format = PA_SAMPLE_FLOAT32NE;
267             else
268                 r->work_format = PA_SAMPLE_S16NE;
269
270         } else
271             r->work_format = a->format;
272
273     } else
274         r->work_format = PA_SAMPLE_FLOAT32NE;
275
276     pa_log_info("Using %s as working format.", pa_sample_format_to_string(r->work_format));
277
278     r->w_sz = sample_size(r->work_format);
279
280     if (r->i_ss.format == r->work_format)
281         r->to_work_format_func = NULL;
282     else if (r->work_format == PA_SAMPLE_FLOAT32NE) {
283         if (!(r->to_work_format_func = pa_get_convert_to_float32ne_function(r->i_ss.format)))
284             goto fail;
285     } else {
286         pa_assert(r->work_format == PA_SAMPLE_S16NE);
287         if (!(r->to_work_format_func = pa_get_convert_to_s16ne_function(r->i_ss.format)))
288             goto fail;
289     }
290
291     if (r->o_ss.format == r->work_format)
292         r->from_work_format_func = NULL;
293     else if (r->work_format == PA_SAMPLE_FLOAT32NE) {
294         if (!(r->from_work_format_func = pa_get_convert_from_float32ne_function(r->o_ss.format)))
295             goto fail;
296     } else {
297         pa_assert(r->work_format == PA_SAMPLE_S16NE);
298         if (!(r->from_work_format_func = pa_get_convert_from_s16ne_function(r->o_ss.format)))
299             goto fail;
300     }
301
302     /* initialize implementation */
303     if (init_table[method](r) < 0)
304         goto fail;
305
306     return r;
307
308 fail:
309     if (r)
310         pa_xfree(r);
311
312     return NULL;
313 }
314
315 void pa_resampler_free(pa_resampler *r) {
316     pa_assert(r);
317
318     if (r->impl_free)
319         r->impl_free(r);
320
321     if (r->buf1.memblock)
322         pa_memblock_unref(r->buf1.memblock);
323     if (r->buf2.memblock)
324         pa_memblock_unref(r->buf2.memblock);
325     if (r->buf3.memblock)
326         pa_memblock_unref(r->buf3.memblock);
327     if (r->buf4.memblock)
328         pa_memblock_unref(r->buf4.memblock);
329
330     pa_xfree(r);
331 }
332
333 void pa_resampler_set_input_rate(pa_resampler *r, uint32_t rate) {
334     pa_assert(r);
335     pa_assert(rate > 0);
336
337     if (r->i_ss.rate == rate)
338         return;
339
340     r->i_ss.rate = rate;
341
342     r->impl_update_rates(r);
343 }
344
345 void pa_resampler_set_output_rate(pa_resampler *r, uint32_t rate) {
346     pa_assert(r);
347     pa_assert(rate > 0);
348
349     if (r->o_ss.rate == rate)
350         return;
351
352     r->o_ss.rate = rate;
353
354     r->impl_update_rates(r);
355 }
356
357 size_t pa_resampler_request(pa_resampler *r, size_t out_length) {
358     pa_assert(r);
359
360     return (((out_length / r->o_fz)*r->i_ss.rate)/r->o_ss.rate) * r->i_fz;
361 }
362
363 size_t pa_resampler_result(pa_resampler *r, size_t in_length) {
364     pa_assert(r);
365
366     return (((in_length / r->i_fz)*r->o_ss.rate)/r->i_ss.rate) * r->o_fz;
367 }
368
369 size_t pa_resampler_max_block_size(pa_resampler *r) {
370     size_t block_size_max;
371     pa_sample_spec ss;
372     size_t fs;
373
374     pa_assert(r);
375
376     block_size_max = pa_mempool_block_size_max(r->mempool);
377
378     /* We deduce the "largest" sample spec we're using during the
379      * conversion */
380     ss.channels = (uint8_t) (PA_MAX(r->i_ss.channels, r->o_ss.channels));
381
382     /* We silently assume that the format enum is ordered by size */
383     ss.format = PA_MAX(r->i_ss.format, r->o_ss.format);
384     ss.format = PA_MAX(ss.format, r->work_format);
385
386     ss.rate = PA_MAX(r->i_ss.rate, r->o_ss.rate);
387
388     fs = pa_frame_size(&ss);
389
390     return (((block_size_max/fs - EXTRA_FRAMES)*r->i_ss.rate)/ss.rate)*r->i_fz;
391 }
392
393 void pa_resampler_reset(pa_resampler *r) {
394     pa_assert(r);
395
396     if (r->impl_reset)
397         r->impl_reset(r);
398 }
399
400 pa_resample_method_t pa_resampler_get_method(pa_resampler *r) {
401     pa_assert(r);
402
403     return r->method;
404 }
405
406 const pa_channel_map* pa_resampler_input_channel_map(pa_resampler *r) {
407     pa_assert(r);
408
409     return &r->i_cm;
410 }
411
412 const pa_sample_spec* pa_resampler_input_sample_spec(pa_resampler *r) {
413     pa_assert(r);
414
415     return &r->i_ss;
416 }
417
418 const pa_channel_map* pa_resampler_output_channel_map(pa_resampler *r) {
419     pa_assert(r);
420
421     return &r->o_cm;
422 }
423
424 const pa_sample_spec* pa_resampler_output_sample_spec(pa_resampler *r) {
425     pa_assert(r);
426
427     return &r->o_ss;
428 }
429
430 static const char * const resample_methods[] = {
431     "src-sinc-best-quality",
432     "src-sinc-medium-quality",
433     "src-sinc-fastest",
434     "src-zero-order-hold",
435     "src-linear",
436     "trivial",
437     "speex-float-0",
438     "speex-float-1",
439     "speex-float-2",
440     "speex-float-3",
441     "speex-float-4",
442     "speex-float-5",
443     "speex-float-6",
444     "speex-float-7",
445     "speex-float-8",
446     "speex-float-9",
447     "speex-float-10",
448     "speex-fixed-0",
449     "speex-fixed-1",
450     "speex-fixed-2",
451     "speex-fixed-3",
452     "speex-fixed-4",
453     "speex-fixed-5",
454     "speex-fixed-6",
455     "speex-fixed-7",
456     "speex-fixed-8",
457     "speex-fixed-9",
458     "speex-fixed-10",
459     "ffmpeg",
460     "auto",
461     "copy",
462     "peaks"
463 };
464
465 const char *pa_resample_method_to_string(pa_resample_method_t m) {
466
467     if (m < 0 || m >= PA_RESAMPLER_MAX)
468         return NULL;
469
470     return resample_methods[m];
471 }
472
473 int pa_resample_method_supported(pa_resample_method_t m) {
474
475     if (m < 0 || m >= PA_RESAMPLER_MAX)
476         return 0;
477
478 #ifndef HAVE_LIBSAMPLERATE
479     if (m <= PA_RESAMPLER_SRC_LINEAR)
480         return 0;
481 #endif
482
483     return 1;
484 }
485
486 pa_resample_method_t pa_parse_resample_method(const char *string) {
487     pa_resample_method_t m;
488
489     pa_assert(string);
490
491     for (m = 0; m < PA_RESAMPLER_MAX; m++)
492         if (!strcmp(string, resample_methods[m]))
493             return m;
494
495     if (!strcmp(string, "speex-fixed"))
496         return PA_RESAMPLER_SPEEX_FIXED_BASE + 3;
497
498     if (!strcmp(string, "speex-float"))
499         return PA_RESAMPLER_SPEEX_FLOAT_BASE + 3;
500
501     return PA_RESAMPLER_INVALID;
502 }
503
504 static pa_bool_t on_left(pa_channel_position_t p) {
505
506     return
507         p == PA_CHANNEL_POSITION_FRONT_LEFT ||
508         p == PA_CHANNEL_POSITION_REAR_LEFT ||
509         p == PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER ||
510         p == PA_CHANNEL_POSITION_SIDE_LEFT ||
511         p == PA_CHANNEL_POSITION_TOP_FRONT_LEFT ||
512         p == PA_CHANNEL_POSITION_TOP_REAR_LEFT;
513 }
514
515 static pa_bool_t on_right(pa_channel_position_t p) {
516
517     return
518         p == PA_CHANNEL_POSITION_FRONT_RIGHT ||
519         p == PA_CHANNEL_POSITION_REAR_RIGHT ||
520         p == PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER ||
521         p == PA_CHANNEL_POSITION_SIDE_RIGHT ||
522         p == PA_CHANNEL_POSITION_TOP_FRONT_RIGHT ||
523         p == PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
524 }
525
526 static pa_bool_t on_center(pa_channel_position_t p) {
527
528     return
529         p == PA_CHANNEL_POSITION_FRONT_CENTER ||
530         p == PA_CHANNEL_POSITION_REAR_CENTER ||
531         p == PA_CHANNEL_POSITION_TOP_CENTER ||
532         p == PA_CHANNEL_POSITION_TOP_FRONT_CENTER ||
533         p == PA_CHANNEL_POSITION_TOP_REAR_CENTER;
534 }
535
536 static pa_bool_t on_lfe(pa_channel_position_t p) {
537     return
538         p == PA_CHANNEL_POSITION_LFE;
539 }
540
541 static pa_bool_t on_front(pa_channel_position_t p) {
542     return
543         p == PA_CHANNEL_POSITION_FRONT_LEFT ||
544         p == PA_CHANNEL_POSITION_FRONT_RIGHT ||
545         p == PA_CHANNEL_POSITION_FRONT_CENTER ||
546         p == PA_CHANNEL_POSITION_TOP_FRONT_LEFT ||
547         p == PA_CHANNEL_POSITION_TOP_FRONT_RIGHT ||
548         p == PA_CHANNEL_POSITION_TOP_FRONT_CENTER ||
549         p == PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER ||
550         p == PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
551 }
552
553 static pa_bool_t on_rear(pa_channel_position_t p) {
554     return
555         p == PA_CHANNEL_POSITION_REAR_LEFT ||
556         p == PA_CHANNEL_POSITION_REAR_RIGHT ||
557         p == PA_CHANNEL_POSITION_REAR_CENTER ||
558         p == PA_CHANNEL_POSITION_TOP_REAR_LEFT ||
559         p == PA_CHANNEL_POSITION_TOP_REAR_RIGHT ||
560         p == PA_CHANNEL_POSITION_TOP_REAR_CENTER;
561 }
562
563 static pa_bool_t on_side(pa_channel_position_t p) {
564     return
565         p == PA_CHANNEL_POSITION_SIDE_LEFT ||
566         p == PA_CHANNEL_POSITION_SIDE_RIGHT ||
567         p == PA_CHANNEL_POSITION_TOP_CENTER;
568 }
569
570 enum {
571     ON_FRONT,
572     ON_REAR,
573     ON_SIDE,
574     ON_OTHER
575 };
576
577 static int front_rear_side(pa_channel_position_t p) {
578     if (on_front(p))
579         return ON_FRONT;
580     if (on_rear(p))
581         return ON_REAR;
582     if (on_side(p))
583         return ON_SIDE;
584     return ON_OTHER;
585 }
586
587 static void calc_map_table(pa_resampler *r) {
588     unsigned oc, ic;
589     pa_bool_t ic_connected[PA_CHANNELS_MAX];
590     pa_bool_t remix;
591     pa_strbuf *s;
592     char *t;
593
594     pa_assert(r);
595
596     if (!(r->map_required = (r->i_ss.channels != r->o_ss.channels || (!(r->flags & PA_RESAMPLER_NO_REMAP) && !pa_channel_map_equal(&r->i_cm, &r->o_cm)))))
597         return;
598
599     memset(r->map_table, 0, sizeof(r->map_table));
600     memset(ic_connected, 0, sizeof(ic_connected));
601     remix = (r->flags & (PA_RESAMPLER_NO_REMAP|PA_RESAMPLER_NO_REMIX)) == 0;
602
603     for (oc = 0; oc < r->o_ss.channels; oc++) {
604         pa_bool_t oc_connected = FALSE;
605         pa_channel_position_t b = r->o_cm.map[oc];
606
607         for (ic = 0; ic < r->i_ss.channels; ic++) {
608             pa_channel_position_t a = r->i_cm.map[ic];
609
610             if (r->flags & PA_RESAMPLER_NO_REMAP) {
611                 /* We shall not do any remapping. Hence, just check by index */
612
613                 if (ic == oc)
614                     r->map_table[oc][ic] = 1.0;
615
616                 continue;
617             }
618
619             if (r->flags & PA_RESAMPLER_NO_REMIX) {
620                 /* We shall not do any remixing. Hence, just check by name */
621
622                 if (a == b)
623                     r->map_table[oc][ic] = 1.0;
624
625                 continue;
626             }
627
628             pa_assert(remix);
629
630             /* OK, we shall do the full monty: upmixing and
631              * downmixing. Our algorithm is relatively simple, does
632              * not do spacialization, delay elements or apply lowpass
633              * filters for LFE. Patches are always welcome,
634              * though. Oh, and it doesn't do any matrix
635              * decoding. (Which probably wouldn't make any sense
636              * anyway.)
637              *
638              * This code is not idempotent: downmixing an upmixed
639              * stereo stream is not identical to the original. The
640              * volume will not match, and the two channels will be a
641              * linear combination of both.
642              *
643              * This is losely based on random suggestions found on the
644              * Internet, such as this:
645              * http://www.halfgaar.net/surround-sound-in-linux and the
646              * alsa upmix plugin.
647              *
648              * The algorithm works basically like this:
649              *
650              * 1) Connect all channels with matching names.
651              *
652              * 2) Mono Handling:
653              *    S:Mono: Copy into all D:channels
654              *    D:Mono: Copy in all S:channels
655              *
656              * 3) Mix D:Left, D:Right:
657              *    D:Left: If not connected, avg all S:Left
658              *    D:Right: If not connected, avg all S:Right
659              *
660              * 4) Mix D:Center
661              *       If not connected, avg all S:Center
662              *       If still not connected, avg all S:Left, S:Right
663              *
664              * 5) Mix D:LFE
665              *       If not connected, avg all S:*
666              *
667              * 6) Make sure S:Left/S:Right is used: S:Left/S:Right: If
668              *    not connected, mix into all D:left and all D:right
669              *    channels. Gain is 0.1, the current left and right
670              *    should be multiplied by 0.9.
671              *
672              * 7) Make sure S:Center, S:LFE is used:
673              *
674              *    S:Center, S:LFE: If not connected, mix into all
675              *    D:left, all D:right, all D:center channels, gain is
676              *    0.375. The current (as result of 1..6) factors
677              *    should be multiplied by 0.75. (Alt. suggestion: 0.25
678              *    vs. 0.5) If C-front is only mixed into
679              *    L-front/R-front if available, otherwise into all L/R
680              *    channels. Similarly for C-rear.
681              *
682              * S: and D: shall relate to the source resp. destination channels.
683              *
684              * Rationale: 1, 2 are probably obvious. For 3: this
685              * copies front to rear if needed. For 4: we try to find
686              * some suitable C source for C, if we don't find any, we
687              * avg L and R. For 5: LFE is mixed from all channels. For
688              * 6: the rear channels should not be dropped entirely,
689              * however have only minimal impact. For 7: movies usually
690              * encode speech on the center channel. Thus we have to
691              * make sure this channel is distributed to L and R if not
692              * available in the output. Also, LFE is used to achieve a
693              * greater dynamic range, and thus we should try to do our
694              * best to pass it to L+R.
695              */
696
697             if (a == b || a == PA_CHANNEL_POSITION_MONO || b == PA_CHANNEL_POSITION_MONO) {
698                 r->map_table[oc][ic] = 1.0;
699
700                 oc_connected = TRUE;
701                 ic_connected[ic] = TRUE;
702             }
703         }
704
705         if (!oc_connected && remix) {
706             /* OK, we shall remix */
707
708             /* Try to find matching input ports for this output port */
709
710             if (on_left(b)) {
711                 unsigned n = 0;
712
713                 /* We are not connected and on the left side, let's
714                  * average all left side input channels. */
715
716                 for (ic = 0; ic < r->i_ss.channels; ic++)
717                     if (on_left(r->i_cm.map[ic]))
718                         n++;
719
720                 if (n > 0)
721                     for (ic = 0; ic < r->i_ss.channels; ic++)
722                         if (on_left(r->i_cm.map[ic])) {
723                             r->map_table[oc][ic] = 1.0f / (float) n;
724                             ic_connected[ic] = TRUE;
725                         }
726
727                 /* We ignore the case where there is no left input
728                  * channel. Something is really wrong in this case
729                  * anyway. */
730
731             } else if (on_right(b)) {
732                 unsigned n = 0;
733
734                 /* We are not connected and on the right side, let's
735                  * average all right side input channels. */
736
737                 for (ic = 0; ic < r->i_ss.channels; ic++)
738                     if (on_right(r->i_cm.map[ic]))
739                         n++;
740
741                 if (n > 0)
742                     for (ic = 0; ic < r->i_ss.channels; ic++)
743                         if (on_right(r->i_cm.map[ic])) {
744                             r->map_table[oc][ic] = 1.0f / (float) n;
745                             ic_connected[ic] = TRUE;
746                         }
747
748                 /* We ignore the case where there is no right input
749                  * channel. Something is really wrong in this case
750                  * anyway. */
751
752             } else if (on_center(b)) {
753                 unsigned n = 0;
754
755                 /* We are not connected and at the center. Let's
756                  * average all center input channels. */
757
758                 for (ic = 0; ic < r->i_ss.channels; ic++)
759                     if (on_center(r->i_cm.map[ic]))
760                         n++;
761
762                 if (n > 0) {
763                     for (ic = 0; ic < r->i_ss.channels; ic++)
764                         if (on_center(r->i_cm.map[ic])) {
765                             r->map_table[oc][ic] = 1.0f / (float) n;
766                             ic_connected[ic] = TRUE;
767                         }
768                 } else {
769
770                     /* Hmm, no center channel around, let's synthesize
771                      * it by mixing L and R.*/
772
773                     n = 0;
774
775                     for (ic = 0; ic < r->i_ss.channels; ic++)
776                         if (on_left(r->i_cm.map[ic]) || on_right(r->i_cm.map[ic]))
777                             n++;
778
779                     if (n > 0)
780                         for (ic = 0; ic < r->i_ss.channels; ic++)
781                             if (on_left(r->i_cm.map[ic]) || on_right(r->i_cm.map[ic])) {
782                                 r->map_table[oc][ic] = 1.0f / (float) n;
783                                 ic_connected[ic] = TRUE;
784                             }
785
786                     /* We ignore the case where there is not even a
787                      * left or right input channel. Something is
788                      * really wrong in this case anyway. */
789                 }
790
791             } else if (on_lfe(b)) {
792
793                 /* We are not connected and an LFE. Let's average all
794                  * channels for LFE. */
795
796                 for (ic = 0; ic < r->i_ss.channels; ic++) {
797
798                     if (!(r->flags & PA_RESAMPLER_NO_LFE))
799                         r->map_table[oc][ic] = 1.0f / (float) r->i_ss.channels;
800                     else
801                         r->map_table[oc][ic] = 0;
802
803                     /* Please note that a channel connected to LFE
804                      * doesn't really count as connected. */
805                 }
806             }
807         }
808     }
809
810     if (remix) {
811         unsigned
812             ic_unconnected_left = 0,
813             ic_unconnected_right = 0,
814             ic_unconnected_center = 0,
815             ic_unconnected_lfe = 0;
816
817         for (ic = 0; ic < r->i_ss.channels; ic++) {
818             pa_channel_position_t a = r->i_cm.map[ic];
819
820             if (ic_connected[ic])
821                 continue;
822
823             if (on_left(a))
824                 ic_unconnected_left++;
825             else if (on_right(a))
826                 ic_unconnected_right++;
827             else if (on_center(a))
828                 ic_unconnected_center++;
829             else if (on_lfe(a))
830                 ic_unconnected_lfe++;
831         }
832
833         if (ic_unconnected_left > 0) {
834
835             /* OK, so there are unconnected input channels on the
836              * left. Let's multiply all already connected channels on
837              * the left side by .9 and add in our averaged unconnected
838              * channels multplied by .1 */
839
840             for (oc = 0; oc < r->o_ss.channels; oc++) {
841
842                 if (!on_left(r->o_cm.map[oc]))
843                     continue;
844
845                 for (ic = 0; ic < r->i_ss.channels; ic++) {
846
847                     if (ic_connected[ic]) {
848                         r->map_table[oc][ic] *= .9f;
849                         continue;
850                     }
851
852                     if (on_left(r->i_cm.map[ic]))
853                         r->map_table[oc][ic] = .1f / (float) ic_unconnected_left;
854                 }
855             }
856         }
857
858         if (ic_unconnected_right > 0) {
859
860             /* OK, so there are unconnected input channels on the
861              * right. Let's multiply all already connected channels on
862              * the right side by .9 and add in our averaged unconnected
863              * channels multplied by .1 */
864
865             for (oc = 0; oc < r->o_ss.channels; oc++) {
866
867                 if (!on_right(r->o_cm.map[oc]))
868                     continue;
869
870                 for (ic = 0; ic < r->i_ss.channels; ic++) {
871
872                     if (ic_connected[ic]) {
873                         r->map_table[oc][ic] *= .9f;
874                         continue;
875                     }
876
877                     if (on_right(r->i_cm.map[ic]))
878                         r->map_table[oc][ic] = .1f / (float) ic_unconnected_right;
879                 }
880             }
881         }
882
883         if (ic_unconnected_center > 0) {
884             pa_bool_t mixed_in = FALSE;
885
886             /* OK, so there are unconnected input channels on the
887              * center. Let's multiply all already connected channels on
888              * the center side by .9 and add in our averaged unconnected
889              * channels multplied by .1 */
890
891             for (oc = 0; oc < r->o_ss.channels; oc++) {
892
893                 if (!on_center(r->o_cm.map[oc]))
894                     continue;
895
896                 for (ic = 0; ic < r->i_ss.channels; ic++)  {
897
898                     if (ic_connected[ic]) {
899                         r->map_table[oc][ic] *= .9f;
900                         continue;
901                     }
902
903                     if (on_center(r->i_cm.map[ic])) {
904                         r->map_table[oc][ic] = .1f / (float) ic_unconnected_center;
905                         mixed_in = TRUE;
906                     }
907                 }
908             }
909
910             if (!mixed_in) {
911                 unsigned ncenter[PA_CHANNELS_MAX];
912                 pa_bool_t found_frs[PA_CHANNELS_MAX];
913
914                 memset(ncenter, 0, sizeof(ncenter));
915                 memset(found_frs, 0, sizeof(found_frs));
916
917                 /* Hmm, as it appears there was no center channel we
918                    could mix our center channel in. In this case, mix
919                    it into left and right. Using .375 and 0.75 as
920                    factors. */
921
922                 for (ic = 0; ic < r->i_ss.channels; ic++) {
923
924                     if (ic_connected[ic])
925                         continue;
926
927                     if (!on_center(r->i_cm.map[ic]))
928                         continue;
929
930                     for (oc = 0; oc < r->o_ss.channels; oc++) {
931
932                         if (!on_left(r->o_cm.map[oc]) && !on_right(r->o_cm.map[oc]))
933                             continue;
934
935                         if (front_rear_side(r->i_cm.map[ic]) == front_rear_side(r->o_cm.map[oc])) {
936                             found_frs[ic] = TRUE;
937                             break;
938                         }
939                     }
940
941                     for (oc = 0; oc < r->o_ss.channels; oc++) {
942
943                         if (!on_left(r->o_cm.map[oc]) && !on_right(r->o_cm.map[oc]))
944                             continue;
945
946                         if (!found_frs[ic] || front_rear_side(r->i_cm.map[ic]) == front_rear_side(r->o_cm.map[oc]))
947                             ncenter[oc]++;
948                     }
949                 }
950
951                 for (oc = 0; oc < r->o_ss.channels; oc++) {
952
953                     if (!on_left(r->o_cm.map[oc]) && !on_right(r->o_cm.map[oc]))
954                         continue;
955
956                     if (ncenter[oc] <= 0)
957                         continue;
958
959                     for (ic = 0; ic < r->i_ss.channels; ic++)  {
960
961                         if (ic_connected[ic]) {
962                             r->map_table[oc][ic] *= .75f;
963                             continue;
964                         }
965
966                         if (!on_center(r->i_cm.map[ic]))
967                             continue;
968
969                         if (!found_frs[ic] || front_rear_side(r->i_cm.map[ic]) == front_rear_side(r->o_cm.map[oc]))
970                             r->map_table[oc][ic] = .375f / (float) ncenter[oc];
971                     }
972                 }
973             }
974         }
975
976         if (ic_unconnected_lfe > 0 && !(r->flags & PA_RESAMPLER_NO_LFE)) {
977
978             /* OK, so there is an unconnected LFE channel. Let's mix
979              * it into all channels, with factor 0.375 */
980
981             for (ic = 0; ic < r->i_ss.channels; ic++)  {
982
983                 if (!on_lfe(r->i_cm.map[ic]))
984                     continue;
985
986                 for (oc = 0; oc < r->o_ss.channels; oc++)
987                     r->map_table[oc][ic] = 0.375f / (float) ic_unconnected_lfe;
988             }
989         }
990     }
991
992
993     s = pa_strbuf_new();
994
995     pa_strbuf_printf(s, "     ");
996     for (ic = 0; ic < r->i_ss.channels; ic++)
997         pa_strbuf_printf(s, "  I%02u ", ic);
998     pa_strbuf_puts(s, "\n    +");
999
1000     for (ic = 0; ic < r->i_ss.channels; ic++)
1001         pa_strbuf_printf(s, "------");
1002     pa_strbuf_puts(s, "\n");
1003
1004     for (oc = 0; oc < r->o_ss.channels; oc++) {
1005         pa_strbuf_printf(s, "O%02u |", oc);
1006
1007         for (ic = 0; ic < r->i_ss.channels; ic++)
1008             pa_strbuf_printf(s, " %1.3f", r->map_table[oc][ic]);
1009
1010         pa_strbuf_puts(s, "\n");
1011     }
1012
1013     pa_log_debug("Channel matrix:\n%s", t = pa_strbuf_tostring_free(s));
1014     pa_xfree(t);
1015 }
1016
1017 static pa_memchunk* convert_to_work_format(pa_resampler *r, pa_memchunk *input) {
1018     unsigned n_samples;
1019     void *src, *dst;
1020
1021     pa_assert(r);
1022     pa_assert(input);
1023     pa_assert(input->memblock);
1024
1025     /* Convert the incoming sample into the work sample format and place them in buf1 */
1026
1027     if (!r->to_work_format_func || !input->length)
1028         return input;
1029
1030     n_samples = (unsigned) ((input->length / r->i_fz) * r->i_ss.channels);
1031
1032     r->buf1.index = 0;
1033     r->buf1.length = r->w_sz * n_samples;
1034
1035     if (!r->buf1.memblock || r->buf1_samples < n_samples) {
1036         if (r->buf1.memblock)
1037             pa_memblock_unref(r->buf1.memblock);
1038
1039         r->buf1_samples = n_samples;
1040         r->buf1.memblock = pa_memblock_new(r->mempool, r->buf1.length);
1041     }
1042
1043     src = (uint8_t*) pa_memblock_acquire(input->memblock) + input->index;
1044     dst = (uint8_t*) pa_memblock_acquire(r->buf1.memblock);
1045
1046     r->to_work_format_func(n_samples, src, dst);
1047
1048     pa_memblock_release(input->memblock);
1049     pa_memblock_release(r->buf1.memblock);
1050
1051     return &r->buf1;
1052 }
1053
1054 static void vectoradd_s16_with_fraction(
1055         int16_t *d, int dstr,
1056         const int16_t *s1, int sstr1,
1057         const int16_t *s2, int sstr2,
1058         int n,
1059         float s3, float s4) {
1060
1061     int32_t i3, i4;
1062
1063     i3 = (int32_t) (s3 * 0x10000);
1064     i4 = (int32_t) (s4 * 0x10000);
1065
1066     for (; n > 0; n--) {
1067         int32_t a, b;
1068
1069         a = *s1;
1070         b = *s2;
1071
1072         a = (a * i3) / 0x10000;
1073         b = (b * i4) / 0x10000;
1074
1075         *d = (int16_t) (a + b);
1076
1077         s1 = (const int16_t*) ((const uint8_t*) s1 + sstr1);
1078         s2 = (const int16_t*) ((const uint8_t*) s2 + sstr2);
1079         d = (int16_t*) ((uint8_t*) d + dstr);
1080
1081     }
1082 }
1083
1084 static pa_memchunk *remap_channels(pa_resampler *r, pa_memchunk *input) {
1085     unsigned in_n_samples, out_n_samples, n_frames;
1086     int i_skip, o_skip;
1087     unsigned oc;
1088     void *src, *dst;
1089
1090     pa_assert(r);
1091     pa_assert(input);
1092     pa_assert(input->memblock);
1093
1094     /* Remap channels and place the result int buf2 */
1095
1096     if (!r->map_required || !input->length)
1097         return input;
1098
1099     in_n_samples = (unsigned) (input->length / r->w_sz);
1100     n_frames = in_n_samples / r->i_ss.channels;
1101     out_n_samples = n_frames * r->o_ss.channels;
1102
1103     r->buf2.index = 0;
1104     r->buf2.length = r->w_sz * out_n_samples;
1105
1106     if (!r->buf2.memblock || r->buf2_samples < out_n_samples) {
1107         if (r->buf2.memblock)
1108             pa_memblock_unref(r->buf2.memblock);
1109
1110         r->buf2_samples = out_n_samples;
1111         r->buf2.memblock = pa_memblock_new(r->mempool, r->buf2.length);
1112     }
1113
1114     src = ((uint8_t*) pa_memblock_acquire(input->memblock) + input->index);
1115     dst = pa_memblock_acquire(r->buf2.memblock);
1116
1117     memset(dst, 0, r->buf2.length);
1118
1119     o_skip = (int) (r->w_sz * r->o_ss.channels);
1120     i_skip = (int) (r->w_sz * r->i_ss.channels);
1121
1122     switch (r->work_format) {
1123         case PA_SAMPLE_FLOAT32NE:
1124
1125             for (oc = 0; oc < r->o_ss.channels; oc++) {
1126                 unsigned ic;
1127                 static const float one = 1.0;
1128
1129                 for (ic = 0; ic < r->i_ss.channels; ic++) {
1130
1131                     if (r->map_table[oc][ic] <= 0.0)
1132                         continue;
1133
1134                     oil_vectoradd_f32(
1135                             (float*) dst + oc, o_skip,
1136                             (float*) dst + oc, o_skip,
1137                             (float*) src + ic, i_skip,
1138                             (int) n_frames,
1139                             &one, &r->map_table[oc][ic]);
1140                 }
1141             }
1142
1143             break;
1144
1145         case PA_SAMPLE_S16NE:
1146
1147             for (oc = 0; oc < r->o_ss.channels; oc++) {
1148                 unsigned ic;
1149
1150                 for (ic = 0; ic < r->i_ss.channels; ic++) {
1151
1152                     if (r->map_table[oc][ic] <= 0.0)
1153                         continue;
1154
1155                     if (r->map_table[oc][ic] >= 1.0) {
1156                         static const int16_t one = 1;
1157
1158                         oil_vectoradd_s16(
1159                                 (int16_t*) dst + oc, o_skip,
1160                                 (int16_t*) dst + oc, o_skip,
1161                                 (int16_t*) src + ic, i_skip,
1162                                 (int) n_frames,
1163                                 &one, &one);
1164
1165                     } else
1166
1167                         vectoradd_s16_with_fraction(
1168                                 (int16_t*) dst + oc, o_skip,
1169                                 (int16_t*) dst + oc, o_skip,
1170                                 (int16_t*) src + ic, i_skip,
1171                                 (int) n_frames,
1172                                 1.0f, r->map_table[oc][ic]);
1173                 }
1174             }
1175
1176             break;
1177
1178         default:
1179             pa_assert_not_reached();
1180     }
1181
1182     pa_memblock_release(input->memblock);
1183     pa_memblock_release(r->buf2.memblock);
1184
1185     r->buf2.length = out_n_samples * r->w_sz;
1186
1187     return &r->buf2;
1188 }
1189
1190 static pa_memchunk *resample(pa_resampler *r, pa_memchunk *input) {
1191     unsigned in_n_frames, in_n_samples;
1192     unsigned out_n_frames, out_n_samples;
1193
1194     pa_assert(r);
1195     pa_assert(input);
1196
1197     /* Resample the data and place the result in buf3 */
1198
1199     if (!r->impl_resample || !input->length)
1200         return input;
1201
1202     in_n_samples = (unsigned) (input->length / r->w_sz);
1203     in_n_frames = (unsigned) (in_n_samples / r->o_ss.channels);
1204
1205     out_n_frames = ((in_n_frames*r->o_ss.rate)/r->i_ss.rate)+EXTRA_FRAMES;
1206     out_n_samples = out_n_frames * r->o_ss.channels;
1207
1208     r->buf3.index = 0;
1209     r->buf3.length = r->w_sz * out_n_samples;
1210
1211     if (!r->buf3.memblock || r->buf3_samples < out_n_samples) {
1212         if (r->buf3.memblock)
1213             pa_memblock_unref(r->buf3.memblock);
1214
1215         r->buf3_samples = out_n_samples;
1216         r->buf3.memblock = pa_memblock_new(r->mempool, r->buf3.length);
1217     }
1218
1219     r->impl_resample(r, input, in_n_frames, &r->buf3, &out_n_frames);
1220     r->buf3.length = out_n_frames * r->w_sz * r->o_ss.channels;
1221
1222     return &r->buf3;
1223 }
1224
1225 static pa_memchunk *convert_from_work_format(pa_resampler *r, pa_memchunk *input) {
1226     unsigned n_samples, n_frames;
1227     void *src, *dst;
1228
1229     pa_assert(r);
1230     pa_assert(input);
1231
1232     /* Convert the data into the correct sample type and place the result in buf4 */
1233
1234     if (!r->from_work_format_func || !input->length)
1235         return input;
1236
1237     n_samples = (unsigned) (input->length / r->w_sz);
1238     n_frames = n_samples / r->o_ss.channels;
1239
1240     r->buf4.index = 0;
1241     r->buf4.length = r->o_fz * n_frames;
1242
1243     if (!r->buf4.memblock || r->buf4_samples < n_samples) {
1244         if (r->buf4.memblock)
1245             pa_memblock_unref(r->buf4.memblock);
1246
1247         r->buf4_samples = n_samples;
1248         r->buf4.memblock = pa_memblock_new(r->mempool, r->buf4.length);
1249     }
1250
1251     src = (uint8_t*) pa_memblock_acquire(input->memblock) + input->index;
1252     dst = pa_memblock_acquire(r->buf4.memblock);
1253     r->from_work_format_func(n_samples, src, dst);
1254     pa_memblock_release(input->memblock);
1255     pa_memblock_release(r->buf4.memblock);
1256
1257     r->buf4.length = r->o_fz * n_frames;
1258
1259     return &r->buf4;
1260 }
1261
1262 void pa_resampler_run(pa_resampler *r, const pa_memchunk *in, pa_memchunk *out) {
1263     pa_memchunk *buf;
1264
1265     pa_assert(r);
1266     pa_assert(in);
1267     pa_assert(out);
1268     pa_assert(in->length);
1269     pa_assert(in->memblock);
1270     pa_assert(in->length % r->i_fz == 0);
1271
1272     buf = (pa_memchunk*) in;
1273     buf = convert_to_work_format(r, buf);
1274     buf = remap_channels(r, buf);
1275     buf = resample(r, buf);
1276
1277     if (buf->length) {
1278         buf = convert_from_work_format(r, buf);
1279         *out = *buf;
1280
1281         if (buf == in)
1282             pa_memblock_ref(buf->memblock);
1283         else
1284             pa_memchunk_reset(buf);
1285     } else
1286         pa_memchunk_reset(out);
1287 }
1288
1289 /*** libsamplerate based implementation ***/
1290
1291 #ifdef HAVE_LIBSAMPLERATE
1292 static void libsamplerate_resample(pa_resampler *r, const pa_memchunk *input, unsigned in_n_frames, pa_memchunk *output, unsigned *out_n_frames) {
1293     SRC_DATA data;
1294
1295     pa_assert(r);
1296     pa_assert(input);
1297     pa_assert(output);
1298     pa_assert(out_n_frames);
1299
1300     memset(&data, 0, sizeof(data));
1301
1302     data.data_in = (float*) ((uint8_t*) pa_memblock_acquire(input->memblock) + input->index);
1303     data.input_frames = (long int) in_n_frames;
1304
1305     data.data_out = (float*) ((uint8_t*) pa_memblock_acquire(output->memblock) + output->index);
1306     data.output_frames = (long int) *out_n_frames;
1307
1308     data.src_ratio = (double) r->o_ss.rate / r->i_ss.rate;
1309     data.end_of_input = 0;
1310
1311     pa_assert_se(src_process(r->src.state, &data) == 0);
1312     pa_assert((unsigned) data.input_frames_used == in_n_frames);
1313
1314     pa_memblock_release(input->memblock);
1315     pa_memblock_release(output->memblock);
1316
1317     *out_n_frames = (unsigned) data.output_frames_gen;
1318 }
1319
1320 static void libsamplerate_update_rates(pa_resampler *r) {
1321     pa_assert(r);
1322
1323     pa_assert_se(src_set_ratio(r->src.state, (double) r->o_ss.rate / r->i_ss.rate) == 0);
1324 }
1325
1326 static void libsamplerate_reset(pa_resampler *r) {
1327     pa_assert(r);
1328
1329     pa_assert_se(src_reset(r->src.state) == 0);
1330 }
1331
1332 static void libsamplerate_free(pa_resampler *r) {
1333     pa_assert(r);
1334
1335     if (r->src.state)
1336         src_delete(r->src.state);
1337 }
1338
1339 static int libsamplerate_init(pa_resampler *r) {
1340     int err;
1341
1342     pa_assert(r);
1343
1344     if (!(r->src.state = src_new(r->method, r->o_ss.channels, &err)))
1345         return -1;
1346
1347     r->impl_free = libsamplerate_free;
1348     r->impl_update_rates = libsamplerate_update_rates;
1349     r->impl_resample = libsamplerate_resample;
1350     r->impl_reset = libsamplerate_reset;
1351
1352     return 0;
1353 }
1354 #endif
1355
1356 /*** speex based implementation ***/
1357
1358 static void speex_resample_float(pa_resampler *r, const pa_memchunk *input, unsigned in_n_frames, pa_memchunk *output, unsigned *out_n_frames) {
1359     float *in, *out;
1360     uint32_t inf = in_n_frames, outf = *out_n_frames;
1361
1362     pa_assert(r);
1363     pa_assert(input);
1364     pa_assert(output);
1365     pa_assert(out_n_frames);
1366
1367     in = (float*) ((uint8_t*) pa_memblock_acquire(input->memblock) + input->index);
1368     out = (float*) ((uint8_t*) pa_memblock_acquire(output->memblock) + output->index);
1369
1370     pa_assert_se(speex_resampler_process_interleaved_float(r->speex.state, in, &inf, out, &outf) == 0);
1371
1372     pa_memblock_release(input->memblock);
1373     pa_memblock_release(output->memblock);
1374
1375     pa_assert(inf == in_n_frames);
1376     *out_n_frames = outf;
1377 }
1378
1379 static void speex_resample_int(pa_resampler *r, const pa_memchunk *input, unsigned in_n_frames, pa_memchunk *output, unsigned *out_n_frames) {
1380     int16_t *in, *out;
1381     uint32_t inf = in_n_frames, outf = *out_n_frames;
1382
1383     pa_assert(r);
1384     pa_assert(input);
1385     pa_assert(output);
1386     pa_assert(out_n_frames);
1387
1388     in = (int16_t*) ((uint8_t*) pa_memblock_acquire(input->memblock) + input->index);
1389     out = (int16_t*) ((uint8_t*) pa_memblock_acquire(output->memblock) + output->index);
1390
1391     pa_assert_se(speex_resampler_process_interleaved_int(r->speex.state, in, &inf, out, &outf) == 0);
1392
1393     pa_memblock_release(input->memblock);
1394     pa_memblock_release(output->memblock);
1395
1396     pa_assert(inf == in_n_frames);
1397     *out_n_frames = outf;
1398 }
1399
1400 static void speex_update_rates(pa_resampler *r) {
1401     pa_assert(r);
1402
1403     pa_assert_se(speex_resampler_set_rate(r->speex.state, r->i_ss.rate, r->o_ss.rate) == 0);
1404 }
1405
1406 static void speex_reset(pa_resampler *r) {
1407     pa_assert(r);
1408
1409     pa_assert_se(speex_resampler_reset_mem(r->speex.state) == 0);
1410 }
1411
1412 static void speex_free(pa_resampler *r) {
1413     pa_assert(r);
1414
1415     if (!r->speex.state)
1416         return;
1417
1418     speex_resampler_destroy(r->speex.state);
1419 }
1420
1421 static int speex_init(pa_resampler *r) {
1422     int q, err;
1423
1424     pa_assert(r);
1425
1426     r->impl_free = speex_free;
1427     r->impl_update_rates = speex_update_rates;
1428     r->impl_reset = speex_reset;
1429
1430     if (r->method >= PA_RESAMPLER_SPEEX_FIXED_BASE && r->method <= PA_RESAMPLER_SPEEX_FIXED_MAX) {
1431
1432         q = r->method - PA_RESAMPLER_SPEEX_FIXED_BASE;
1433         r->impl_resample = speex_resample_int;
1434
1435     } else {
1436         pa_assert(r->method >= PA_RESAMPLER_SPEEX_FLOAT_BASE && r->method <= PA_RESAMPLER_SPEEX_FLOAT_MAX);
1437
1438         q = r->method - PA_RESAMPLER_SPEEX_FLOAT_BASE;
1439         r->impl_resample = speex_resample_float;
1440     }
1441
1442     pa_log_info("Choosing speex quality setting %i.", q);
1443
1444     if (!(r->speex.state = speex_resampler_init(r->o_ss.channels, r->i_ss.rate, r->o_ss.rate, q, &err)))
1445         return -1;
1446
1447     return 0;
1448 }
1449
1450 /* Trivial implementation */
1451
1452 static void trivial_resample(pa_resampler *r, const pa_memchunk *input, unsigned in_n_frames, pa_memchunk *output, unsigned *out_n_frames) {
1453     size_t fz;
1454     unsigned o_index;
1455     void *src, *dst;
1456
1457     pa_assert(r);
1458     pa_assert(input);
1459     pa_assert(output);
1460     pa_assert(out_n_frames);
1461
1462     fz = r->w_sz * r->o_ss.channels;
1463
1464     src = (uint8_t*) pa_memblock_acquire(input->memblock) + input->index;
1465     dst = (uint8_t*) pa_memblock_acquire(output->memblock) + output->index;
1466
1467     for (o_index = 0;; o_index++, r->trivial.o_counter++) {
1468         unsigned j;
1469
1470         j = ((r->trivial.o_counter * r->i_ss.rate) / r->o_ss.rate);
1471         j = j > r->trivial.i_counter ? j - r->trivial.i_counter : 0;
1472
1473         if (j >= in_n_frames)
1474             break;
1475
1476         pa_assert(o_index * fz < pa_memblock_get_length(output->memblock));
1477
1478         oil_memcpy((uint8_t*) dst + fz * o_index,
1479                    (uint8_t*) src + fz * j, (int) fz);
1480     }
1481
1482     pa_memblock_release(input->memblock);
1483     pa_memblock_release(output->memblock);
1484
1485     *out_n_frames = o_index;
1486
1487     r->trivial.i_counter += in_n_frames;
1488
1489     /* Normalize counters */
1490     while (r->trivial.i_counter >= r->i_ss.rate) {
1491         pa_assert(r->trivial.o_counter >= r->o_ss.rate);
1492
1493         r->trivial.i_counter -= r->i_ss.rate;
1494         r->trivial.o_counter -= r->o_ss.rate;
1495     }
1496 }
1497
1498 static void trivial_update_rates_or_reset(pa_resampler *r) {
1499     pa_assert(r);
1500
1501     r->trivial.i_counter = 0;
1502     r->trivial.o_counter = 0;
1503 }
1504
1505 static int trivial_init(pa_resampler*r) {
1506     pa_assert(r);
1507
1508     r->trivial.o_counter = r->trivial.i_counter = 0;
1509
1510     r->impl_resample = trivial_resample;
1511     r->impl_update_rates = trivial_update_rates_or_reset;
1512     r->impl_reset = trivial_update_rates_or_reset;
1513
1514     return 0;
1515 }
1516
1517 /* Peak finder implementation */
1518
1519 static void peaks_resample(pa_resampler *r, const pa_memchunk *input, unsigned in_n_frames, pa_memchunk *output, unsigned *out_n_frames) {
1520     size_t fz;
1521     unsigned o_index;
1522     void *src, *dst;
1523     unsigned start = 0;
1524
1525     pa_assert(r);
1526     pa_assert(input);
1527     pa_assert(output);
1528     pa_assert(out_n_frames);
1529
1530     fz = r->w_sz * r->o_ss.channels;
1531
1532     src = (uint8_t*) pa_memblock_acquire(input->memblock) + input->index;
1533     dst = (uint8_t*) pa_memblock_acquire(output->memblock) + output->index;
1534
1535     for (o_index = 0;; o_index++, r->peaks.o_counter++) {
1536         unsigned j;
1537
1538         j = ((r->peaks.o_counter * r->i_ss.rate) / r->o_ss.rate);
1539
1540         if (j > r->peaks.i_counter)
1541             j -= r->peaks.i_counter;
1542         else
1543             j = 0;
1544
1545         pa_assert(o_index * fz < pa_memblock_get_length(output->memblock));
1546
1547         if (r->work_format == PA_SAMPLE_S16NE) {
1548             unsigned i, c;
1549             int16_t *s = (int16_t*) ((uint8_t*) src + fz * start);
1550             int16_t *d = (int16_t*) ((uint8_t*) dst + fz * o_index);
1551
1552             for (i = start; i <= j && i < in_n_frames; i++)
1553
1554                 for (c = 0; c < r->o_ss.channels; c++, s++) {
1555                     int16_t n;
1556
1557                     n = (int16_t) (*s < 0 ? -*s : *s);
1558
1559                     if (PA_UNLIKELY(n > r->peaks.max_i[c]))
1560                         r->peaks.max_i[c] = n;
1561                 }
1562
1563             if (i >= in_n_frames)
1564                 break;
1565
1566             for (c = 0; c < r->o_ss.channels; c++, d++) {
1567                 *d = r->peaks.max_i[c];
1568                 r->peaks.max_i[c] = 0;
1569             }
1570
1571         } else {
1572             unsigned i, c;
1573             float *s = (float*) ((uint8_t*) src + fz * start);
1574             float *d = (float*) ((uint8_t*) dst + fz * o_index);
1575
1576             pa_assert(r->work_format == PA_SAMPLE_FLOAT32NE);
1577
1578             for (i = start; i <= j && i < in_n_frames; i++)
1579                 for (c = 0; c < r->o_ss.channels; c++, s++) {
1580                     float n = fabsf(*s);
1581
1582                     if (n > r->peaks.max_f[c])
1583                         r->peaks.max_f[c] = n;
1584                 }
1585
1586             if (i >= in_n_frames)
1587                 break;
1588
1589             for (c = 0; c < r->o_ss.channels; c++, d++) {
1590                 *d = r->peaks.max_f[c];
1591                 r->peaks.max_f[c] = 0;
1592             }
1593         }
1594
1595         start = j;
1596     }
1597
1598     pa_memblock_release(input->memblock);
1599     pa_memblock_release(output->memblock);
1600
1601     *out_n_frames = o_index;
1602
1603     r->peaks.i_counter += in_n_frames;
1604
1605     /* Normalize counters */
1606     while (r->peaks.i_counter >= r->i_ss.rate) {
1607         pa_assert(r->peaks.o_counter >= r->o_ss.rate);
1608
1609         r->peaks.i_counter -= r->i_ss.rate;
1610         r->peaks.o_counter -= r->o_ss.rate;
1611     }
1612 }
1613
1614 static void peaks_update_rates_or_reset(pa_resampler *r) {
1615     pa_assert(r);
1616
1617     r->peaks.i_counter = 0;
1618     r->peaks.o_counter = 0;
1619 }
1620
1621 static int peaks_init(pa_resampler*r) {
1622     pa_assert(r);
1623
1624     r->peaks.o_counter = r->peaks.i_counter = 0;
1625     memset(r->peaks.max_i, 0, sizeof(r->peaks.max_i));
1626     memset(r->peaks.max_f, 0, sizeof(r->peaks.max_f));
1627
1628     r->impl_resample = peaks_resample;
1629     r->impl_update_rates = peaks_update_rates_or_reset;
1630     r->impl_reset = peaks_update_rates_or_reset;
1631
1632     return 0;
1633 }
1634
1635 /*** ffmpeg based implementation ***/
1636
1637 static void ffmpeg_resample(pa_resampler *r, const pa_memchunk *input, unsigned in_n_frames, pa_memchunk *output, unsigned *out_n_frames) {
1638     unsigned used_frames = 0, c;
1639
1640     pa_assert(r);
1641     pa_assert(input);
1642     pa_assert(output);
1643     pa_assert(out_n_frames);
1644
1645     for (c = 0; c < r->o_ss.channels; c++) {
1646         unsigned u;
1647         pa_memblock *b, *w;
1648         int16_t *p, *t, *k, *q, *s;
1649         int consumed_frames;
1650         unsigned in, l;
1651
1652         /* Allocate a new block */
1653         b = pa_memblock_new(r->mempool, r->ffmpeg.buf[c].length + in_n_frames * sizeof(int16_t));
1654         p = pa_memblock_acquire(b);
1655
1656         /* Copy the remaining data into it */
1657         l = (unsigned) r->ffmpeg.buf[c].length;
1658         if (r->ffmpeg.buf[c].memblock) {
1659             t = (int16_t*) ((uint8_t*) pa_memblock_acquire(r->ffmpeg.buf[c].memblock) + r->ffmpeg.buf[c].index);
1660             memcpy(p, t, l);
1661             pa_memblock_release(r->ffmpeg.buf[c].memblock);
1662             pa_memblock_unref(r->ffmpeg.buf[c].memblock);
1663             pa_memchunk_reset(&r->ffmpeg.buf[c]);
1664         }
1665
1666         /* Now append the new data, splitting up channels */
1667         t = ((int16_t*) ((uint8_t*) pa_memblock_acquire(input->memblock) + input->index)) + c;
1668         k = (int16_t*) ((uint8_t*) p + l);
1669         for (u = 0; u < in_n_frames; u++) {
1670             *k = *t;
1671             t += r->o_ss.channels;
1672             k ++;
1673         }
1674         pa_memblock_release(input->memblock);
1675
1676         /* Calculate the resulting number of frames */
1677         in = (unsigned) in_n_frames + l / (unsigned) sizeof(int16_t);
1678
1679         /* Allocate buffer for the result */
1680         w = pa_memblock_new(r->mempool, *out_n_frames * sizeof(int16_t));
1681         q = pa_memblock_acquire(w);
1682
1683         /* Now, resample */
1684         used_frames = (unsigned) av_resample(r->ffmpeg.state,
1685                                              q, p,
1686                                              &consumed_frames,
1687                                              (int) in, (int) *out_n_frames,
1688                                              c >= (unsigned) (r->o_ss.channels-1));
1689
1690         pa_memblock_release(b);
1691
1692         /* Now store the remaining samples away */
1693         pa_assert(consumed_frames <= (int) in);
1694         if (consumed_frames < (int) in) {
1695             r->ffmpeg.buf[c].memblock = b;
1696             r->ffmpeg.buf[c].index = (size_t) consumed_frames * sizeof(int16_t);
1697             r->ffmpeg.buf[c].length = (size_t) (in - (unsigned) consumed_frames) * sizeof(int16_t);
1698         } else
1699             pa_memblock_unref(b);
1700
1701         /* And place the results in the output buffer */
1702         s = (short*) ((uint8_t*) pa_memblock_acquire(output->memblock) + output->index) + c;
1703         for (u = 0; u < used_frames; u++) {
1704             *s = *q;
1705             q++;
1706             s += r->o_ss.channels;
1707         }
1708         pa_memblock_release(output->memblock);
1709         pa_memblock_release(w);
1710         pa_memblock_unref(w);
1711     }
1712
1713     *out_n_frames = used_frames;
1714 }
1715
1716 static void ffmpeg_free(pa_resampler *r) {
1717     unsigned c;
1718
1719     pa_assert(r);
1720
1721     if (r->ffmpeg.state)
1722         av_resample_close(r->ffmpeg.state);
1723
1724     for (c = 0; c < PA_ELEMENTSOF(r->ffmpeg.buf); c++)
1725         if (r->ffmpeg.buf[c].memblock)
1726             pa_memblock_unref(r->ffmpeg.buf[c].memblock);
1727 }
1728
1729 static int ffmpeg_init(pa_resampler *r) {
1730     unsigned c;
1731
1732     pa_assert(r);
1733
1734     /* We could probably implement different quality levels by
1735      * adjusting the filter parameters here. However, ffmpeg
1736      * internally only uses these hardcoded values, so let's use them
1737      * here for now as well until ffmpeg makes this configurable. */
1738
1739     if (!(r->ffmpeg.state = av_resample_init((int) r->o_ss.rate, (int) r->i_ss.rate, 16, 10, 0, 0.8)))
1740         return -1;
1741
1742     r->impl_free = ffmpeg_free;
1743     r->impl_resample = ffmpeg_resample;
1744
1745     for (c = 0; c < PA_ELEMENTSOF(r->ffmpeg.buf); c++)
1746         pa_memchunk_reset(&r->ffmpeg.buf[c]);
1747
1748     return 0;
1749 }
1750
1751 /*** copy (noop) implementation ***/
1752
1753 static int copy_init(pa_resampler *r) {
1754     pa_assert(r);
1755
1756     pa_assert(r->o_ss.rate == r->i_ss.rate);
1757
1758     return 0;
1759 }