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