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