daemon: add nice value in service file to improve performance
[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, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <string.h>
25
26 #include <pulse/xmalloc.h>
27 #include <pulsecore/log.h>
28 #include <pulsecore/macro.h>
29 #include <pulsecore/strbuf.h>
30 #include <pulsecore/core-util.h>
31
32 #include "resampler.h"
33
34 /* Number of samples of extra space we allow the resamplers to return */
35 #define EXTRA_FRAMES 128
36
37 struct ffmpeg_data { /* data specific to ffmpeg */
38     struct AVResampleContext *state;
39 };
40
41 static int copy_init(pa_resampler *r);
42
43 static void setup_remap(const pa_resampler *r, pa_remap_t *m, bool *lfe_remixed);
44 static void free_remap(pa_remap_t *m);
45
46 static int (* const init_table[])(pa_resampler *r) = {
47 #ifdef HAVE_LIBSAMPLERATE
48     [PA_RESAMPLER_SRC_SINC_BEST_QUALITY]   = pa_resampler_libsamplerate_init,
49     [PA_RESAMPLER_SRC_SINC_MEDIUM_QUALITY] = pa_resampler_libsamplerate_init,
50     [PA_RESAMPLER_SRC_SINC_FASTEST]        = pa_resampler_libsamplerate_init,
51     [PA_RESAMPLER_SRC_ZERO_ORDER_HOLD]     = pa_resampler_libsamplerate_init,
52     [PA_RESAMPLER_SRC_LINEAR]              = pa_resampler_libsamplerate_init,
53 #else
54     [PA_RESAMPLER_SRC_SINC_BEST_QUALITY]   = NULL,
55     [PA_RESAMPLER_SRC_SINC_MEDIUM_QUALITY] = NULL,
56     [PA_RESAMPLER_SRC_SINC_FASTEST]        = NULL,
57     [PA_RESAMPLER_SRC_ZERO_ORDER_HOLD]     = NULL,
58     [PA_RESAMPLER_SRC_LINEAR]              = NULL,
59 #endif
60     [PA_RESAMPLER_TRIVIAL]                 = pa_resampler_trivial_init,
61 #ifdef HAVE_SPEEX
62     [PA_RESAMPLER_SPEEX_FLOAT_BASE+0]      = pa_resampler_speex_init,
63     [PA_RESAMPLER_SPEEX_FLOAT_BASE+1]      = pa_resampler_speex_init,
64     [PA_RESAMPLER_SPEEX_FLOAT_BASE+2]      = pa_resampler_speex_init,
65     [PA_RESAMPLER_SPEEX_FLOAT_BASE+3]      = pa_resampler_speex_init,
66     [PA_RESAMPLER_SPEEX_FLOAT_BASE+4]      = pa_resampler_speex_init,
67     [PA_RESAMPLER_SPEEX_FLOAT_BASE+5]      = pa_resampler_speex_init,
68     [PA_RESAMPLER_SPEEX_FLOAT_BASE+6]      = pa_resampler_speex_init,
69     [PA_RESAMPLER_SPEEX_FLOAT_BASE+7]      = pa_resampler_speex_init,
70     [PA_RESAMPLER_SPEEX_FLOAT_BASE+8]      = pa_resampler_speex_init,
71     [PA_RESAMPLER_SPEEX_FLOAT_BASE+9]      = pa_resampler_speex_init,
72     [PA_RESAMPLER_SPEEX_FLOAT_BASE+10]     = pa_resampler_speex_init,
73     [PA_RESAMPLER_SPEEX_FIXED_BASE+0]      = pa_resampler_speex_init,
74     [PA_RESAMPLER_SPEEX_FIXED_BASE+1]      = pa_resampler_speex_init,
75     [PA_RESAMPLER_SPEEX_FIXED_BASE+2]      = pa_resampler_speex_init,
76     [PA_RESAMPLER_SPEEX_FIXED_BASE+3]      = pa_resampler_speex_init,
77     [PA_RESAMPLER_SPEEX_FIXED_BASE+4]      = pa_resampler_speex_init,
78     [PA_RESAMPLER_SPEEX_FIXED_BASE+5]      = pa_resampler_speex_init,
79     [PA_RESAMPLER_SPEEX_FIXED_BASE+6]      = pa_resampler_speex_init,
80     [PA_RESAMPLER_SPEEX_FIXED_BASE+7]      = pa_resampler_speex_init,
81     [PA_RESAMPLER_SPEEX_FIXED_BASE+8]      = pa_resampler_speex_init,
82     [PA_RESAMPLER_SPEEX_FIXED_BASE+9]      = pa_resampler_speex_init,
83     [PA_RESAMPLER_SPEEX_FIXED_BASE+10]     = pa_resampler_speex_init,
84 #else
85     [PA_RESAMPLER_SPEEX_FLOAT_BASE+0]      = NULL,
86     [PA_RESAMPLER_SPEEX_FLOAT_BASE+1]      = NULL,
87     [PA_RESAMPLER_SPEEX_FLOAT_BASE+2]      = NULL,
88     [PA_RESAMPLER_SPEEX_FLOAT_BASE+3]      = NULL,
89     [PA_RESAMPLER_SPEEX_FLOAT_BASE+4]      = NULL,
90     [PA_RESAMPLER_SPEEX_FLOAT_BASE+5]      = NULL,
91     [PA_RESAMPLER_SPEEX_FLOAT_BASE+6]      = NULL,
92     [PA_RESAMPLER_SPEEX_FLOAT_BASE+7]      = NULL,
93     [PA_RESAMPLER_SPEEX_FLOAT_BASE+8]      = NULL,
94     [PA_RESAMPLER_SPEEX_FLOAT_BASE+9]      = NULL,
95     [PA_RESAMPLER_SPEEX_FLOAT_BASE+10]     = NULL,
96     [PA_RESAMPLER_SPEEX_FIXED_BASE+0]      = NULL,
97     [PA_RESAMPLER_SPEEX_FIXED_BASE+1]      = NULL,
98     [PA_RESAMPLER_SPEEX_FIXED_BASE+2]      = NULL,
99     [PA_RESAMPLER_SPEEX_FIXED_BASE+3]      = NULL,
100     [PA_RESAMPLER_SPEEX_FIXED_BASE+4]      = NULL,
101     [PA_RESAMPLER_SPEEX_FIXED_BASE+5]      = NULL,
102     [PA_RESAMPLER_SPEEX_FIXED_BASE+6]      = NULL,
103     [PA_RESAMPLER_SPEEX_FIXED_BASE+7]      = NULL,
104     [PA_RESAMPLER_SPEEX_FIXED_BASE+8]      = NULL,
105     [PA_RESAMPLER_SPEEX_FIXED_BASE+9]      = NULL,
106     [PA_RESAMPLER_SPEEX_FIXED_BASE+10]     = NULL,
107 #endif
108     [PA_RESAMPLER_FFMPEG]                  = pa_resampler_ffmpeg_init,
109     [PA_RESAMPLER_AUTO]                    = NULL,
110     [PA_RESAMPLER_COPY]                    = copy_init,
111     [PA_RESAMPLER_PEAKS]                   = pa_resampler_peaks_init,
112 #ifdef HAVE_SOXR
113     [PA_RESAMPLER_SOXR_MQ]                 = pa_resampler_soxr_init,
114     [PA_RESAMPLER_SOXR_HQ]                 = pa_resampler_soxr_init,
115     [PA_RESAMPLER_SOXR_VHQ]                = pa_resampler_soxr_init,
116 #else
117     [PA_RESAMPLER_SOXR_MQ]                 = NULL,
118     [PA_RESAMPLER_SOXR_HQ]                 = NULL,
119     [PA_RESAMPLER_SOXR_VHQ]                = NULL,
120 #endif
121 };
122
123 static pa_resample_method_t choose_auto_resampler(pa_resample_flags_t flags) {
124     pa_resample_method_t method;
125
126     if (pa_resample_method_supported(PA_RESAMPLER_SPEEX_FLOAT_BASE + 1))
127         method = PA_RESAMPLER_SPEEX_FLOAT_BASE + 1;
128     else if (flags & PA_RESAMPLER_VARIABLE_RATE)
129         method = PA_RESAMPLER_TRIVIAL;
130     else
131         method = PA_RESAMPLER_FFMPEG;
132
133     return method;
134 }
135
136 static pa_resample_method_t fix_method(
137                 pa_resample_flags_t flags,
138                 pa_resample_method_t method,
139                 const uint32_t rate_a,
140                 const uint32_t rate_b) {
141
142     pa_assert(pa_sample_rate_valid(rate_a));
143     pa_assert(pa_sample_rate_valid(rate_b));
144     pa_assert(method >= 0);
145     pa_assert(method < PA_RESAMPLER_MAX);
146
147     if (!(flags & PA_RESAMPLER_VARIABLE_RATE) && rate_a == rate_b) {
148         pa_log_info("Forcing resampler 'copy', because of fixed, identical sample rates.");
149         method = PA_RESAMPLER_COPY;
150     }
151
152     if (!pa_resample_method_supported(method)) {
153         pa_log_warn("Support for resampler '%s' not compiled in, reverting to 'auto'.", pa_resample_method_to_string(method));
154         method = PA_RESAMPLER_AUTO;
155     }
156
157     switch (method) {
158         case PA_RESAMPLER_COPY:
159             if (rate_a != rate_b) {
160                 pa_log_info("Resampler 'copy' cannot change sampling rate, reverting to resampler 'auto'.");
161                 method = PA_RESAMPLER_AUTO;
162                 break;
163             }
164             /* Else fall through */
165         case PA_RESAMPLER_FFMPEG:
166         case PA_RESAMPLER_SOXR_MQ:
167         case PA_RESAMPLER_SOXR_HQ:
168         case PA_RESAMPLER_SOXR_VHQ:
169             if (flags & PA_RESAMPLER_VARIABLE_RATE) {
170                 pa_log_info("Resampler '%s' cannot do variable rate, reverting to resampler 'auto'.", pa_resample_method_to_string(method));
171                 method = PA_RESAMPLER_AUTO;
172             }
173             break;
174
175         /* The Peaks resampler only supports downsampling.
176          * Revert to auto if we are upsampling */
177         case PA_RESAMPLER_PEAKS:
178             if (rate_a < rate_b) {
179                 pa_log_warn("The 'peaks' resampler only supports downsampling, reverting to resampler 'auto'.");
180                 method = PA_RESAMPLER_AUTO;
181             }
182             break;
183
184         default:
185             break;
186     }
187
188     if (method == PA_RESAMPLER_AUTO)
189         method = choose_auto_resampler(flags);
190
191 #ifdef HAVE_SPEEX
192     /* At this point, method is supported in the sense that it
193      * has an init function and supports the required flags. However,
194      * speex-float implementation in PulseAudio relies on the
195      * assumption that is invalid if speex has been compiled with
196      * --enable-fixed-point. Besides, speex-fixed is more efficient
197      * in this configuration. So use it instead.
198      */
199     if (method >= PA_RESAMPLER_SPEEX_FLOAT_BASE && method <= PA_RESAMPLER_SPEEX_FLOAT_MAX) {
200         if (pa_speex_is_fixed_point()) {
201             pa_log_info("Speex appears to be compiled with --enable-fixed-point. "
202                         "Switching to a fixed-point resampler because it should be faster.");
203             method = method - PA_RESAMPLER_SPEEX_FLOAT_BASE + PA_RESAMPLER_SPEEX_FIXED_BASE;
204         }
205     }
206 #endif
207
208     return method;
209 }
210
211 /* Return true if a is a more precise sample format than b, else return false */
212 static bool sample_format_more_precise(pa_sample_format_t a, pa_sample_format_t b) {
213     pa_assert(pa_sample_format_valid(a));
214     pa_assert(pa_sample_format_valid(b));
215
216     switch (a) {
217         case PA_SAMPLE_U8:
218         case PA_SAMPLE_ALAW:
219         case PA_SAMPLE_ULAW:
220             return false;
221             break;
222
223         case PA_SAMPLE_S16LE:
224         case PA_SAMPLE_S16BE:
225             if (b == PA_SAMPLE_ULAW || b == PA_SAMPLE_ALAW || b == PA_SAMPLE_U8)
226                 return true;
227             else
228                 return false;
229             break;
230
231         case PA_SAMPLE_S24LE:
232         case PA_SAMPLE_S24BE:
233         case PA_SAMPLE_S24_32LE:
234         case PA_SAMPLE_S24_32BE:
235             if (b == PA_SAMPLE_ULAW || b == PA_SAMPLE_ALAW || b == PA_SAMPLE_U8 ||
236                 b == PA_SAMPLE_S16LE || b == PA_SAMPLE_S16BE)
237                 return true;
238             else
239                 return false;
240             break;
241
242         case PA_SAMPLE_FLOAT32LE:
243         case PA_SAMPLE_FLOAT32BE:
244         case PA_SAMPLE_S32LE:
245         case PA_SAMPLE_S32BE:
246             if (b == PA_SAMPLE_FLOAT32LE || b == PA_SAMPLE_FLOAT32BE ||
247                 b == PA_SAMPLE_S32LE || b == PA_SAMPLE_S32BE)
248                 return false;
249             else
250                 return true;
251             break;
252
253         default:
254             return false;
255     }
256 }
257
258 static pa_sample_format_t choose_work_format(
259                     pa_resample_method_t method,
260                     pa_sample_format_t a,
261                     pa_sample_format_t b,
262                     bool map_required) {
263     pa_sample_format_t work_format;
264
265     pa_assert(pa_sample_format_valid(a));
266     pa_assert(pa_sample_format_valid(b));
267     pa_assert(method >= 0);
268     pa_assert(method < PA_RESAMPLER_MAX);
269
270     if (method >= PA_RESAMPLER_SPEEX_FIXED_BASE && method <= PA_RESAMPLER_SPEEX_FIXED_MAX)
271         method = PA_RESAMPLER_SPEEX_FIXED_BASE;
272
273     switch (method) {
274         /* This block is for resampling functions that only
275          * support the S16 sample format. */
276         case PA_RESAMPLER_SPEEX_FIXED_BASE:
277         case PA_RESAMPLER_FFMPEG:
278             work_format = PA_SAMPLE_S16NE;
279             break;
280
281         /* This block is for resampling functions that support
282          * any sample format. */
283         case PA_RESAMPLER_COPY:
284         case PA_RESAMPLER_TRIVIAL:
285             if (!map_required && a == b) {
286                 work_format = a;
287                 break;
288             }
289             /* If both input and output are using S32NE and we don't
290              * need any resampling we can use S32NE directly, avoiding
291              * converting back and forth between S32NE and
292              * FLOAT32NE. */
293             if ((a == PA_SAMPLE_S32NE) && (b == PA_SAMPLE_S32NE)) {
294                 work_format = PA_SAMPLE_S32NE;
295                 break;
296             }
297             /* Else fall through */
298         case PA_RESAMPLER_PEAKS:
299             /* PEAKS, COPY and TRIVIAL do not benefit from increased
300              * working precision, so for better performance use s16ne
301              * if either input or output fits in it. */
302             if (a == PA_SAMPLE_S16NE || b == PA_SAMPLE_S16NE) {
303                 work_format = PA_SAMPLE_S16NE;
304                 break;
305             }
306             /* Else fall through */
307         case PA_RESAMPLER_SOXR_MQ:
308         case PA_RESAMPLER_SOXR_HQ:
309         case PA_RESAMPLER_SOXR_VHQ:
310             /* Do processing with max precision of input and output. */
311             if (sample_format_more_precise(a, PA_SAMPLE_S16NE) ||
312                 sample_format_more_precise(b, PA_SAMPLE_S16NE))
313                 work_format = PA_SAMPLE_FLOAT32NE;
314             else
315                 work_format = PA_SAMPLE_S16NE;
316             break;
317
318         default:
319             work_format = PA_SAMPLE_FLOAT32NE;
320     }
321
322     return work_format;
323 }
324
325 pa_resampler* pa_resampler_new(
326         pa_mempool *pool,
327         const pa_sample_spec *a,
328         const pa_channel_map *am,
329         const pa_sample_spec *b,
330         const pa_channel_map *bm,
331         unsigned crossover_freq,
332         pa_resample_method_t method,
333         pa_resample_flags_t flags) {
334
335     pa_resampler *r = NULL;
336     bool lfe_remixed = false;
337
338     pa_assert(pool);
339     pa_assert(a);
340     pa_assert(b);
341     pa_assert(pa_sample_spec_valid(a));
342     pa_assert(pa_sample_spec_valid(b));
343     pa_assert(method >= 0);
344     pa_assert(method < PA_RESAMPLER_MAX);
345
346     method = fix_method(flags, method, a->rate, b->rate);
347
348     r = pa_xnew0(pa_resampler, 1);
349     r->mempool = pool;
350     r->method = method;
351     r->flags = flags;
352
353     /* Fill sample specs */
354     r->i_ss = *a;
355     r->o_ss = *b;
356
357     if (am)
358         r->i_cm = *am;
359     else if (!pa_channel_map_init_auto(&r->i_cm, r->i_ss.channels, PA_CHANNEL_MAP_DEFAULT))
360         goto fail;
361
362     if (bm)
363         r->o_cm = *bm;
364     else if (!pa_channel_map_init_auto(&r->o_cm, r->o_ss.channels, PA_CHANNEL_MAP_DEFAULT))
365         goto fail;
366
367     r->i_fz = pa_frame_size(a);
368     r->o_fz = pa_frame_size(b);
369
370     r->map_required = (r->i_ss.channels != r->o_ss.channels || (!(r->flags & PA_RESAMPLER_NO_REMAP) &&
371         !pa_channel_map_equal(&r->i_cm, &r->o_cm)));
372
373     r->work_format = choose_work_format(method, a->format, b->format, r->map_required);
374     r->w_sz = pa_sample_size_of_format(r->work_format);
375
376     if (r->i_ss.format != r->work_format) {
377         if (r->work_format == PA_SAMPLE_FLOAT32NE) {
378             if (!(r->to_work_format_func = pa_get_convert_to_float32ne_function(r->i_ss.format)))
379                 goto fail;
380         } else {
381             pa_assert(r->work_format == PA_SAMPLE_S16NE);
382             if (!(r->to_work_format_func = pa_get_convert_to_s16ne_function(r->i_ss.format)))
383                 goto fail;
384         }
385     }
386
387     if (r->o_ss.format != r->work_format) {
388         if (r->work_format == PA_SAMPLE_FLOAT32NE) {
389             if (!(r->from_work_format_func = pa_get_convert_from_float32ne_function(r->o_ss.format)))
390                 goto fail;
391         } else {
392             pa_assert(r->work_format == PA_SAMPLE_S16NE);
393             if (!(r->from_work_format_func = pa_get_convert_from_s16ne_function(r->o_ss.format)))
394                 goto fail;
395         }
396     }
397
398     if (r->o_ss.channels <= r->i_ss.channels) {
399         /* pipeline is: format conv. -> remap -> resample -> format conv. */
400         r->work_channels = r->o_ss.channels;
401
402         /* leftover buffer is remap output buffer (before resampling) */
403         r->leftover_buf = &r->remap_buf;
404         r->leftover_buf_size = &r->remap_buf_size;
405         r->have_leftover = &r->leftover_in_remap;
406     } else {
407         /* pipeline is: format conv. -> resample -> remap -> format conv. */
408         r->work_channels = r->i_ss.channels;
409
410         /* leftover buffer is to_work output buffer (before resampling) */
411         r->leftover_buf = &r->to_work_format_buf;
412         r->leftover_buf_size = &r->to_work_format_buf_size;
413         r->have_leftover = &r->leftover_in_to_work;
414     }
415     r->w_fz = pa_sample_size_of_format(r->work_format) * r->work_channels;
416
417     pa_log_debug("Resampler:");
418     pa_log_debug("  rate %d -> %d (method %s)", a->rate, b->rate, pa_resample_method_to_string(r->method));
419     pa_log_debug("  format %s -> %s (intermediate %s)", pa_sample_format_to_string(a->format),
420                  pa_sample_format_to_string(b->format), pa_sample_format_to_string(r->work_format));
421     pa_log_debug("  channels %d -> %d (resampling %d)", a->channels, b->channels, r->work_channels);
422
423     /* set up the remap structure */
424     if (r->map_required)
425         setup_remap(r, &r->remap, &lfe_remixed);
426
427     if (lfe_remixed && crossover_freq > 0) {
428         pa_sample_spec wss = r->o_ss;
429         wss.format = r->work_format;
430         /* FIXME: For now just hardcode maxrewind to 3 seconds */
431         r->lfe_filter = pa_lfe_filter_new(&wss, &r->o_cm, (float)crossover_freq, b->rate * 3);
432         pa_log_debug("  lfe filter activated (LR4 type), the crossover_freq = %uHz", crossover_freq);
433     }
434
435     /* initialize implementation */
436     if (init_table[method](r) < 0)
437         goto fail;
438
439     return r;
440
441 fail:
442     if (r->lfe_filter)
443       pa_lfe_filter_free(r->lfe_filter);
444     pa_xfree(r);
445
446     return NULL;
447 }
448
449 void pa_resampler_free(pa_resampler *r) {
450     pa_assert(r);
451
452     if (r->impl.free)
453         r->impl.free(r);
454     else
455         pa_xfree(r->impl.data);
456
457     if (r->lfe_filter)
458         pa_lfe_filter_free(r->lfe_filter);
459
460     if (r->to_work_format_buf.memblock)
461         pa_memblock_unref(r->to_work_format_buf.memblock);
462     if (r->remap_buf.memblock)
463         pa_memblock_unref(r->remap_buf.memblock);
464     if (r->resample_buf.memblock)
465         pa_memblock_unref(r->resample_buf.memblock);
466     if (r->from_work_format_buf.memblock)
467         pa_memblock_unref(r->from_work_format_buf.memblock);
468
469     free_remap(&r->remap);
470
471     pa_xfree(r);
472 }
473
474 void pa_resampler_set_input_rate(pa_resampler *r, uint32_t rate) {
475     pa_assert(r);
476     pa_assert(rate > 0);
477     pa_assert(r->impl.update_rates);
478
479     if (r->i_ss.rate == rate)
480         return;
481
482     r->i_ss.rate = rate;
483
484     r->impl.update_rates(r);
485 }
486
487 void pa_resampler_set_output_rate(pa_resampler *r, uint32_t rate) {
488     pa_assert(r);
489     pa_assert(rate > 0);
490     pa_assert(r->impl.update_rates);
491
492     if (r->o_ss.rate == rate)
493         return;
494
495     r->o_ss.rate = rate;
496
497     r->impl.update_rates(r);
498
499     if (r->lfe_filter)
500         pa_lfe_filter_update_rate(r->lfe_filter, rate);
501 }
502
503 size_t pa_resampler_request(pa_resampler *r, size_t out_length) {
504     pa_assert(r);
505
506     /* Let's round up here to make it more likely that the caller will get at
507      * least out_length amount of data from pa_resampler_run().
508      *
509      * We don't take the leftover into account here. If we did, then it might
510      * be in theory possible that this function would return 0 and
511      * pa_resampler_run() would also return 0. That could lead to infinite
512      * loops. When the leftover is ignored here, such loops would eventually
513      * terminate, because the leftover would grow each round, finally
514      * surpassing the minimum input threshold of the resampler. */
515     return ((((uint64_t) ((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;
516 }
517
518 size_t pa_resampler_result(pa_resampler *r, size_t in_length) {
519     size_t frames;
520
521     pa_assert(r);
522
523     /* Let's round up here to ensure that the caller will always allocate big
524      * enough output buffer. */
525
526     frames = (in_length + r->i_fz - 1) / r->i_fz;
527     if (*r->have_leftover)
528         frames += r->leftover_buf->length / r->w_fz;
529
530     return (((uint64_t) frames * r->o_ss.rate + r->i_ss.rate - 1) / r->i_ss.rate) * r->o_fz;
531 }
532
533 size_t pa_resampler_max_block_size(pa_resampler *r) {
534     size_t block_size_max;
535     pa_sample_spec max_ss;
536     size_t max_fs;
537     size_t frames;
538
539     pa_assert(r);
540
541     block_size_max = pa_mempool_block_size_max(r->mempool);
542
543     /* We deduce the "largest" sample spec we're using during the
544      * conversion */
545     max_ss.channels = (uint8_t) (PA_MAX(r->i_ss.channels, r->o_ss.channels));
546
547     /* We silently assume that the format enum is ordered by size */
548     max_ss.format = PA_MAX(r->i_ss.format, r->o_ss.format);
549     max_ss.format = PA_MAX(max_ss.format, r->work_format);
550
551     max_ss.rate = PA_MAX(r->i_ss.rate, r->o_ss.rate);
552
553     max_fs = pa_frame_size(&max_ss);
554     frames = block_size_max / max_fs - EXTRA_FRAMES;
555
556     pa_assert(frames >= (r->leftover_buf->length / r->w_fz));
557     if (*r->have_leftover)
558         frames -= r->leftover_buf->length / r->w_fz;
559
560     block_size_max = ((uint64_t) frames * r->i_ss.rate / max_ss.rate) * r->i_fz;
561
562     if (block_size_max > 0)
563         return block_size_max;
564     else
565         /* A single input frame may result in so much output that it doesn't
566          * fit in one standard memblock (e.g. converting 1 Hz to 44100 Hz). In
567          * this case the max block size will be set to one frame, and some
568          * memory will be probably be allocated with malloc() instead of using
569          * the memory pool.
570          *
571          * XXX: Should we support this case at all? We could also refuse to
572          * create resamplers whose max block size would exceed the memory pool
573          * block size. In this case also updating the resampler rate should
574          * fail if the new rate would cause an excessive max block size (in
575          * which case the stream would probably have to be killed). */
576         return r->i_fz;
577 }
578
579 void pa_resampler_reset(pa_resampler *r) {
580     pa_assert(r);
581
582     if (r->impl.reset)
583         r->impl.reset(r);
584
585     if (r->lfe_filter)
586         pa_lfe_filter_reset(r->lfe_filter);
587
588     *r->have_leftover = false;
589 }
590
591 void pa_resampler_rewind(pa_resampler *r, size_t out_frames) {
592     pa_assert(r);
593
594     /* For now, we don't have any rewindable resamplers, so we just
595        reset the resampler instead (and hope that nobody hears the difference). */
596     if (r->impl.reset)
597         r->impl.reset(r);
598
599     if (r->lfe_filter)
600         pa_lfe_filter_rewind(r->lfe_filter, out_frames);
601
602     *r->have_leftover = false;
603 }
604
605 pa_resample_method_t pa_resampler_get_method(pa_resampler *r) {
606     pa_assert(r);
607
608     return r->method;
609 }
610
611 const pa_channel_map* pa_resampler_input_channel_map(pa_resampler *r) {
612     pa_assert(r);
613
614     return &r->i_cm;
615 }
616
617 const pa_sample_spec* pa_resampler_input_sample_spec(pa_resampler *r) {
618     pa_assert(r);
619
620     return &r->i_ss;
621 }
622
623 const pa_channel_map* pa_resampler_output_channel_map(pa_resampler *r) {
624     pa_assert(r);
625
626     return &r->o_cm;
627 }
628
629 const pa_sample_spec* pa_resampler_output_sample_spec(pa_resampler *r) {
630     pa_assert(r);
631
632     return &r->o_ss;
633 }
634
635 static const char * const resample_methods[] = {
636     "src-sinc-best-quality",
637     "src-sinc-medium-quality",
638     "src-sinc-fastest",
639     "src-zero-order-hold",
640     "src-linear",
641     "trivial",
642     "speex-float-0",
643     "speex-float-1",
644     "speex-float-2",
645     "speex-float-3",
646     "speex-float-4",
647     "speex-float-5",
648     "speex-float-6",
649     "speex-float-7",
650     "speex-float-8",
651     "speex-float-9",
652     "speex-float-10",
653     "speex-fixed-0",
654     "speex-fixed-1",
655     "speex-fixed-2",
656     "speex-fixed-3",
657     "speex-fixed-4",
658     "speex-fixed-5",
659     "speex-fixed-6",
660     "speex-fixed-7",
661     "speex-fixed-8",
662     "speex-fixed-9",
663     "speex-fixed-10",
664     "ffmpeg",
665     "auto",
666     "copy",
667     "peaks",
668     "soxr-mq",
669     "soxr-hq",
670     "soxr-vhq"
671 };
672
673 const char *pa_resample_method_to_string(pa_resample_method_t m) {
674
675     if (m < 0 || m >= PA_RESAMPLER_MAX)
676         return NULL;
677
678     return resample_methods[m];
679 }
680
681 int pa_resample_method_supported(pa_resample_method_t m) {
682
683     if (m < 0 || m >= PA_RESAMPLER_MAX)
684         return 0;
685
686 #ifndef HAVE_LIBSAMPLERATE
687     if (m <= PA_RESAMPLER_SRC_LINEAR)
688         return 0;
689 #endif
690
691 #ifndef HAVE_SPEEX
692     if (m >= PA_RESAMPLER_SPEEX_FLOAT_BASE && m <= PA_RESAMPLER_SPEEX_FLOAT_MAX)
693         return 0;
694     if (m >= PA_RESAMPLER_SPEEX_FIXED_BASE && m <= PA_RESAMPLER_SPEEX_FIXED_MAX)
695         return 0;
696 #endif
697
698 #ifndef HAVE_SOXR
699     if (m >= PA_RESAMPLER_SOXR_MQ && m <= PA_RESAMPLER_SOXR_VHQ)
700         return 0;
701 #endif
702
703     return 1;
704 }
705
706 pa_resample_method_t pa_parse_resample_method(const char *string) {
707     pa_resample_method_t m;
708
709     pa_assert(string);
710
711     for (m = 0; m < PA_RESAMPLER_MAX; m++)
712         if (pa_streq(string, resample_methods[m]))
713             return m;
714
715     if (pa_streq(string, "speex-fixed"))
716         return PA_RESAMPLER_SPEEX_FIXED_BASE + 1;
717
718     if (pa_streq(string, "speex-float"))
719         return PA_RESAMPLER_SPEEX_FLOAT_BASE + 1;
720
721     return PA_RESAMPLER_INVALID;
722 }
723
724 static bool on_left(pa_channel_position_t p) {
725
726     return
727         p == PA_CHANNEL_POSITION_FRONT_LEFT ||
728         p == PA_CHANNEL_POSITION_REAR_LEFT ||
729         p == PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER ||
730         p == PA_CHANNEL_POSITION_SIDE_LEFT ||
731         p == PA_CHANNEL_POSITION_TOP_FRONT_LEFT ||
732         p == PA_CHANNEL_POSITION_TOP_REAR_LEFT;
733 }
734
735 static bool on_right(pa_channel_position_t p) {
736
737     return
738         p == PA_CHANNEL_POSITION_FRONT_RIGHT ||
739         p == PA_CHANNEL_POSITION_REAR_RIGHT ||
740         p == PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER ||
741         p == PA_CHANNEL_POSITION_SIDE_RIGHT ||
742         p == PA_CHANNEL_POSITION_TOP_FRONT_RIGHT ||
743         p == PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
744 }
745
746 static bool on_center(pa_channel_position_t p) {
747
748     return
749         p == PA_CHANNEL_POSITION_FRONT_CENTER ||
750         p == PA_CHANNEL_POSITION_REAR_CENTER ||
751         p == PA_CHANNEL_POSITION_TOP_CENTER ||
752         p == PA_CHANNEL_POSITION_TOP_FRONT_CENTER ||
753         p == PA_CHANNEL_POSITION_TOP_REAR_CENTER;
754 }
755
756 static bool on_lfe(pa_channel_position_t p) {
757     return
758         p == PA_CHANNEL_POSITION_LFE;
759 }
760
761 static bool on_front(pa_channel_position_t p) {
762     return
763         p == PA_CHANNEL_POSITION_FRONT_LEFT ||
764         p == PA_CHANNEL_POSITION_FRONT_RIGHT ||
765         p == PA_CHANNEL_POSITION_FRONT_CENTER ||
766         p == PA_CHANNEL_POSITION_TOP_FRONT_LEFT ||
767         p == PA_CHANNEL_POSITION_TOP_FRONT_RIGHT ||
768         p == PA_CHANNEL_POSITION_TOP_FRONT_CENTER ||
769         p == PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER ||
770         p == PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
771 }
772
773 static bool on_rear(pa_channel_position_t p) {
774     return
775         p == PA_CHANNEL_POSITION_REAR_LEFT ||
776         p == PA_CHANNEL_POSITION_REAR_RIGHT ||
777         p == PA_CHANNEL_POSITION_REAR_CENTER ||
778         p == PA_CHANNEL_POSITION_TOP_REAR_LEFT ||
779         p == PA_CHANNEL_POSITION_TOP_REAR_RIGHT ||
780         p == PA_CHANNEL_POSITION_TOP_REAR_CENTER;
781 }
782
783 static bool on_side(pa_channel_position_t p) {
784     return
785         p == PA_CHANNEL_POSITION_SIDE_LEFT ||
786         p == PA_CHANNEL_POSITION_SIDE_RIGHT ||
787         p == PA_CHANNEL_POSITION_TOP_CENTER;
788 }
789
790 enum {
791     ON_FRONT,
792     ON_REAR,
793     ON_SIDE,
794     ON_OTHER
795 };
796
797 static int front_rear_side(pa_channel_position_t p) {
798     if (on_front(p))
799         return ON_FRONT;
800     if (on_rear(p))
801         return ON_REAR;
802     if (on_side(p))
803         return ON_SIDE;
804     return ON_OTHER;
805 }
806
807 /* Fill a map of which output channels should get mono from input, not including
808  * LFE output channels. (The LFE output channels are mapped separately.)
809  */
810 static void setup_oc_mono_map(const pa_resampler *r, float *oc_mono_map) {
811     unsigned oc;
812     unsigned n_oc;
813     bool found_oc_for_mono = false;
814
815     pa_assert(r);
816     pa_assert(oc_mono_map);
817
818     n_oc = r->o_ss.channels;
819
820     if (!(r->flags & PA_RESAMPLER_NO_FILL_SINK)) {
821         /* Mono goes to all non-LFE output channels and we're done. */
822         for (oc = 0; oc < n_oc; oc++)
823             oc_mono_map[oc] = on_lfe(r->o_cm.map[oc]) ? 0.0f : 1.0f;
824         return;
825     } else {
826         /* Initialize to all zero so we can select individual channels below. */
827         for (oc = 0; oc < n_oc; oc++)
828             oc_mono_map[oc] = 0.0f;
829     }
830
831     for (oc = 0; oc < n_oc; oc++) {
832         if (r->o_cm.map[oc] == PA_CHANNEL_POSITION_MONO) {
833             oc_mono_map[oc] = 1.0f;
834             found_oc_for_mono = true;
835         }
836     }
837     if (found_oc_for_mono)
838         return;
839
840     for (oc = 0; oc < n_oc; oc++) {
841         if (r->o_cm.map[oc] == PA_CHANNEL_POSITION_FRONT_CENTER) {
842             oc_mono_map[oc] = 1.0f;
843             found_oc_for_mono = true;
844         }
845     }
846     if (found_oc_for_mono)
847         return;
848
849     for (oc = 0; oc < n_oc; oc++) {
850         if (r->o_cm.map[oc] == PA_CHANNEL_POSITION_FRONT_LEFT || r->o_cm.map[oc] == PA_CHANNEL_POSITION_FRONT_RIGHT) {
851             oc_mono_map[oc] = 1.0f;
852             found_oc_for_mono = true;
853         }
854     }
855     if (found_oc_for_mono)
856         return;
857
858     /* Give up on finding a suitable map for mono, and just send it to all
859      * non-LFE output channels.
860      */
861     for (oc = 0; oc < n_oc; oc++)
862         oc_mono_map[oc] = on_lfe(r->o_cm.map[oc]) ? 0.0f : 1.0f;
863 }
864
865 static void setup_remap(const pa_resampler *r, pa_remap_t *m, bool *lfe_remixed) {
866     unsigned oc, ic;
867     unsigned n_oc, n_ic;
868     bool ic_connected[PA_CHANNELS_MAX];
869     pa_strbuf *s;
870     char *t;
871
872     pa_assert(r);
873     pa_assert(m);
874     pa_assert(lfe_remixed);
875
876     n_oc = r->o_ss.channels;
877     n_ic = r->i_ss.channels;
878
879     m->format = r->work_format;
880     m->i_ss = r->i_ss;
881     m->o_ss = r->o_ss;
882
883     memset(m->map_table_f, 0, sizeof(m->map_table_f));
884     memset(m->map_table_i, 0, sizeof(m->map_table_i));
885
886     memset(ic_connected, 0, sizeof(ic_connected));
887     *lfe_remixed = false;
888
889     if (r->flags & PA_RESAMPLER_NO_REMAP) {
890         for (oc = 0; oc < PA_MIN(n_ic, n_oc); oc++)
891             m->map_table_f[oc][oc] = 1.0f;
892
893     } else if (r->flags & PA_RESAMPLER_NO_REMIX) {
894         for (oc = 0; oc < n_oc; oc++) {
895             pa_channel_position_t b = r->o_cm.map[oc];
896
897             for (ic = 0; ic < n_ic; ic++) {
898                 pa_channel_position_t a = r->i_cm.map[ic];
899
900                 /* We shall not do any remixing. Hence, just check by name */
901                 if (a == b)
902                     m->map_table_f[oc][ic] = 1.0f;
903             }
904         }
905     } else {
906
907         /* OK, we shall do the full monty: upmixing and downmixing. Our
908          * algorithm is relatively simple, does not do spacialization, or delay
909          * elements. LFE filters are done after the remap step. Patches are always
910          * welcome, though. Oh, and it doesn't do any matrix decoding. (Which
911          * probably wouldn't make any sense anyway.)
912          *
913          * This code is not idempotent: downmixing an upmixed stereo stream is
914          * not identical to the original. The volume will not match, and the
915          * two channels will be a linear combination of both.
916          *
917          * This is loosely based on random suggestions found on the Internet,
918          * such as this:
919          * http://www.halfgaar.net/surround-sound-in-linux and the alsa upmix
920          * plugin.
921          *
922          * The algorithm works basically like this:
923          *
924          * 1) Connect all channels with matching names.
925          *    This also includes fixing confusion between "5.1" and
926          *    "5.1 (Side)" layouts, done by mpv.
927          *
928          * 2) Mono Handling:
929          *    S:Mono: See setup_oc_mono_map().
930          *    D:Mono: Avg all S:channels
931          *
932          * 3) Mix D:Left, D:Right (if PA_RESAMPLER_NO_FILL_SINK is clear):
933          *    D:Left: If not connected, avg all S:Left
934          *    D:Right: If not connected, avg all S:Right
935          *
936          * 4) Mix D:Center (if PA_RESAMPLER_NO_FILL_SINK is clear):
937          *    If not connected, avg all S:Center
938          *    If still not connected, avg all S:Left, S:Right
939          *
940          * 5) Mix D:LFE
941          *    If not connected, avg all S:*
942          *
943          * 6) Make sure S:Left/S:Right is used: S:Left/S:Right: If not
944          *    connected, mix into all D:left and all D:right channels. Gain is
945          *    1/9.
946          *
947          * 7) Make sure S:Center, S:LFE is used:
948          *
949          *    S:Center, S:LFE: If not connected, mix into all D:left, all
950          *    D:right, all D:center channels. Gain is 0.5 for center and 0.375
951          *    for LFE. C-front is only mixed into L-front/R-front if available,
952          *    otherwise into all L/R channels. Similarly for C-rear.
953          *
954          * 8) Normalize each row in the matrix such that the sum for each row is
955          *    not larger than 1.0 in order to avoid clipping.
956          *
957          * S: and D: shall relate to the source resp. destination channels.
958          *
959          * Rationale: 1, 2 are probably obvious. For 3: this copies front to
960          * rear if needed. For 4: we try to find some suitable C source for C,
961          * if we don't find any, we avg L and R. For 5: LFE is mixed from all
962          * channels. For 6: the rear channels should not be dropped entirely,
963          * however have only minimal impact. For 7: movies usually encode
964          * speech on the center channel. Thus we have to make sure this channel
965          * is distributed to L and R if not available in the output. Also, LFE
966          * is used to achieve a greater dynamic range, and thus we should try
967          * to do our best to pass it to L+R.
968          */
969
970         unsigned
971             ic_left = 0,
972             ic_right = 0,
973             ic_center = 0,
974             ic_unconnected_left = 0,
975             ic_unconnected_right = 0,
976             ic_unconnected_center = 0,
977             ic_unconnected_lfe = 0;
978         bool ic_unconnected_center_mixed_in = 0;
979         float oc_mono_map[PA_CHANNELS_MAX];
980
981         for (ic = 0; ic < n_ic; ic++) {
982             if (on_left(r->i_cm.map[ic]))
983                 ic_left++;
984             if (on_right(r->i_cm.map[ic]))
985                 ic_right++;
986             if (on_center(r->i_cm.map[ic]))
987                 ic_center++;
988         }
989
990         setup_oc_mono_map(r, oc_mono_map);
991
992         for (oc = 0; oc < n_oc; oc++) {
993             bool oc_connected = false;
994             pa_channel_position_t b = r->o_cm.map[oc];
995
996             for (ic = 0; ic < n_ic; ic++) {
997                 pa_channel_position_t a = r->i_cm.map[ic];
998
999                 if (a == b) {
1000                     m->map_table_f[oc][ic] = 1.0f;
1001
1002                     oc_connected = true;
1003                     ic_connected[ic] = true;
1004                 }
1005                 else if (a == PA_CHANNEL_POSITION_MONO && oc_mono_map[oc] > 0.0f) {
1006                     m->map_table_f[oc][ic] = oc_mono_map[oc];
1007
1008                     oc_connected = true;
1009                     ic_connected[ic] = true;
1010                 }
1011                 else if (b == PA_CHANNEL_POSITION_MONO) {
1012                     m->map_table_f[oc][ic] = 1.0f / (float) n_ic;
1013
1014                     oc_connected = true;
1015                     ic_connected[ic] = true;
1016                 }
1017             }
1018
1019             if (!oc_connected) {
1020                 /* Maybe it is due to 5.1 rear/side confustion? */
1021                 for (ic = 0; ic < n_ic; ic++) {
1022                     pa_channel_position_t a = r->i_cm.map[ic];
1023                     if (ic_connected[ic])
1024                         continue;
1025
1026                     if ((a == PA_CHANNEL_POSITION_REAR_LEFT && b == PA_CHANNEL_POSITION_SIDE_LEFT) ||
1027                         (a == PA_CHANNEL_POSITION_SIDE_LEFT && b == PA_CHANNEL_POSITION_REAR_LEFT) ||
1028                         (a == PA_CHANNEL_POSITION_REAR_RIGHT && b == PA_CHANNEL_POSITION_SIDE_RIGHT) ||
1029                         (a == PA_CHANNEL_POSITION_SIDE_RIGHT && b == PA_CHANNEL_POSITION_REAR_RIGHT)) {
1030
1031                         m->map_table_f[oc][ic] = 1.0f;
1032
1033                         oc_connected = true;
1034                         ic_connected[ic] = true;
1035                     }
1036                 }
1037             }
1038
1039             if (!oc_connected) {
1040                 /* Try to find matching input ports for this output port */
1041
1042                 if (on_left(b) && !(r->flags & PA_RESAMPLER_NO_FILL_SINK)) {
1043
1044                     /* We are not connected and on the left side, let's
1045                      * average all left side input channels. */
1046
1047                     if (ic_left > 0)
1048                         for (ic = 0; ic < n_ic; ic++)
1049                             if (on_left(r->i_cm.map[ic])) {
1050                                 m->map_table_f[oc][ic] = 1.0f / (float) ic_left;
1051                                 ic_connected[ic] = true;
1052                             }
1053
1054                     /* We ignore the case where there is no left input channel.
1055                      * Something is really wrong in this case anyway. */
1056
1057                 } else if (on_right(b) && !(r->flags & PA_RESAMPLER_NO_FILL_SINK)) {
1058
1059                     /* We are not connected and on the right side, let's
1060                      * average all right side input channels. */
1061
1062                     if (ic_right > 0)
1063                         for (ic = 0; ic < n_ic; ic++)
1064                             if (on_right(r->i_cm.map[ic])) {
1065                                 m->map_table_f[oc][ic] = 1.0f / (float) ic_right;
1066                                 ic_connected[ic] = true;
1067                             }
1068
1069                     /* We ignore the case where there is no right input
1070                      * channel. Something is really wrong in this case anyway.
1071                      * */
1072
1073                 } else if (on_center(b) && !(r->flags & PA_RESAMPLER_NO_FILL_SINK)) {
1074
1075                     if (ic_center > 0) {
1076
1077                         /* We are not connected and at the center. Let's average
1078                          * all center input channels. */
1079
1080                         for (ic = 0; ic < n_ic; ic++)
1081                             if (on_center(r->i_cm.map[ic])) {
1082                                 m->map_table_f[oc][ic] = 1.0f / (float) ic_center;
1083                                 ic_connected[ic] = true;
1084                             }
1085
1086                     } else if (ic_left + ic_right > 0) {
1087
1088                         /* Hmm, no center channel around, let's synthesize it
1089                          * by mixing L and R.*/
1090
1091                         for (ic = 0; ic < n_ic; ic++)
1092                             if (on_left(r->i_cm.map[ic]) || on_right(r->i_cm.map[ic])) {
1093                                 m->map_table_f[oc][ic] = 1.0f / (float) (ic_left + ic_right);
1094                                 ic_connected[ic] = true;
1095                             }
1096                     }
1097
1098                     /* We ignore the case where there is not even a left or
1099                      * right input channel. Something is really wrong in this
1100                      * case anyway. */
1101
1102                 } else if (on_lfe(b) && (r->flags & PA_RESAMPLER_PRODUCE_LFE)) {
1103
1104                     /* We are not connected and an LFE. Let's average all
1105                      * channels for LFE. */
1106
1107                     for (ic = 0; ic < n_ic; ic++)
1108                         m->map_table_f[oc][ic] = 1.0f / (float) n_ic;
1109
1110                     /* Please note that a channel connected to LFE doesn't
1111                      * really count as connected. */
1112
1113                     *lfe_remixed = true;
1114                 }
1115             }
1116         }
1117
1118         for (ic = 0; ic < n_ic; ic++) {
1119             pa_channel_position_t a = r->i_cm.map[ic];
1120
1121             if (ic_connected[ic])
1122                 continue;
1123
1124             if (on_left(a))
1125                 ic_unconnected_left++;
1126             else if (on_right(a))
1127                 ic_unconnected_right++;
1128             else if (on_center(a))
1129                 ic_unconnected_center++;
1130             else if (on_lfe(a))
1131                 ic_unconnected_lfe++;
1132         }
1133
1134         for (ic = 0; ic < n_ic; ic++) {
1135             pa_channel_position_t a = r->i_cm.map[ic];
1136
1137             if (ic_connected[ic])
1138                 continue;
1139
1140             for (oc = 0; oc < n_oc; oc++) {
1141                 pa_channel_position_t b = r->o_cm.map[oc];
1142
1143                 if (on_left(a) && on_left(b))
1144                     m->map_table_f[oc][ic] = (1.f/9.f) / (float) ic_unconnected_left;
1145
1146                 else if (on_right(a) && on_right(b))
1147                     m->map_table_f[oc][ic] = (1.f/9.f) / (float) ic_unconnected_right;
1148
1149                 else if (on_center(a) && on_center(b)) {
1150                     m->map_table_f[oc][ic] = (1.f/9.f) / (float) ic_unconnected_center;
1151                     ic_unconnected_center_mixed_in = true;
1152
1153                 } else if (on_lfe(a) && (r->flags & PA_RESAMPLER_CONSUME_LFE))
1154                     m->map_table_f[oc][ic] = .375f / (float) ic_unconnected_lfe;
1155             }
1156         }
1157
1158         if (ic_unconnected_center > 0 && !ic_unconnected_center_mixed_in) {
1159             unsigned ncenter[PA_CHANNELS_MAX];
1160             bool found_frs[PA_CHANNELS_MAX];
1161
1162             memset(ncenter, 0, sizeof(ncenter));
1163             memset(found_frs, 0, sizeof(found_frs));
1164
1165             /* Hmm, as it appears there was no center channel we
1166                could mix our center channel in. In this case, mix it into
1167                left and right. Using .5 as the factor. */
1168
1169             for (ic = 0; ic < n_ic; ic++) {
1170
1171                 if (ic_connected[ic])
1172                     continue;
1173
1174                 if (!on_center(r->i_cm.map[ic]))
1175                     continue;
1176
1177                 for (oc = 0; oc < n_oc; oc++) {
1178
1179                     if (!on_left(r->o_cm.map[oc]) && !on_right(r->o_cm.map[oc]))
1180                         continue;
1181
1182                     if (front_rear_side(r->i_cm.map[ic]) == front_rear_side(r->o_cm.map[oc])) {
1183                         found_frs[ic] = true;
1184                         break;
1185                     }
1186                 }
1187
1188                 for (oc = 0; oc < n_oc; oc++) {
1189
1190                     if (!on_left(r->o_cm.map[oc]) && !on_right(r->o_cm.map[oc]))
1191                         continue;
1192
1193                     if (!found_frs[ic] || front_rear_side(r->i_cm.map[ic]) == front_rear_side(r->o_cm.map[oc]))
1194                         ncenter[oc]++;
1195                 }
1196             }
1197
1198             for (oc = 0; oc < n_oc; oc++) {
1199
1200                 if (!on_left(r->o_cm.map[oc]) && !on_right(r->o_cm.map[oc]))
1201                     continue;
1202
1203                 if (ncenter[oc] <= 0)
1204                     continue;
1205
1206                 for (ic = 0; ic < n_ic; ic++) {
1207
1208                     if (!on_center(r->i_cm.map[ic]))
1209                         continue;
1210
1211                     if (!found_frs[ic] || front_rear_side(r->i_cm.map[ic]) == front_rear_side(r->o_cm.map[oc]))
1212                         m->map_table_f[oc][ic] = .5f / (float) ncenter[oc];
1213                 }
1214             }
1215         }
1216     }
1217
1218     for (oc = 0; oc < n_oc; oc++) {
1219         float sum = 0.0f;
1220         for (ic = 0; ic < n_ic; ic++)
1221             sum += m->map_table_f[oc][ic];
1222
1223         if (sum > 1.0f)
1224             for (ic = 0; ic < n_ic; ic++)
1225                 m->map_table_f[oc][ic] /= sum;
1226     }
1227
1228     /* make an 16:16 int version of the matrix */
1229     for (oc = 0; oc < n_oc; oc++)
1230         for (ic = 0; ic < n_ic; ic++)
1231             m->map_table_i[oc][ic] = (int32_t) (m->map_table_f[oc][ic] * 0x10000);
1232
1233     s = pa_strbuf_new();
1234
1235     pa_strbuf_printf(s, "     ");
1236     for (ic = 0; ic < n_ic; ic++)
1237         pa_strbuf_printf(s, "  I%02u ", ic);
1238     pa_strbuf_puts(s, "\n    +");
1239
1240     for (ic = 0; ic < n_ic; ic++)
1241         pa_strbuf_printf(s, "------");
1242     pa_strbuf_puts(s, "\n");
1243
1244     for (oc = 0; oc < n_oc; oc++) {
1245         pa_strbuf_printf(s, "O%02u |", oc);
1246
1247         for (ic = 0; ic < n_ic; ic++)
1248             pa_strbuf_printf(s, " %1.3f", m->map_table_f[oc][ic]);
1249
1250         pa_strbuf_puts(s, "\n");
1251     }
1252
1253     pa_log_debug("Channel matrix:\n%s", t = pa_strbuf_to_string_free(s));
1254     pa_xfree(t);
1255
1256     /* initialize the remapping function */
1257     pa_init_remap_func(m);
1258 }
1259
1260 static void free_remap(pa_remap_t *m) {
1261     pa_assert(m);
1262
1263     pa_xfree(m->state);
1264 }
1265
1266 /* check if buf's memblock is large enough to hold 'len' bytes; create a
1267  * new memblock if necessary and optionally preserve 'copy' data bytes */
1268 static void fit_buf(pa_resampler *r, pa_memchunk *buf, size_t len, size_t *size, size_t copy) {
1269     pa_assert(size);
1270
1271     if (!buf->memblock || len > *size) {
1272         pa_memblock *new_block = pa_memblock_new(r->mempool, len);
1273
1274         if (buf->memblock) {
1275             if (copy > 0) {
1276                 void *src = pa_memblock_acquire(buf->memblock);
1277                 void *dst = pa_memblock_acquire(new_block);
1278                 pa_assert(copy <= len);
1279                 memcpy(dst, src, copy);
1280                 pa_memblock_release(new_block);
1281                 pa_memblock_release(buf->memblock);
1282             }
1283
1284             pa_memblock_unref(buf->memblock);
1285         }
1286
1287         buf->memblock = new_block;
1288         *size = len;
1289     }
1290
1291     buf->length = len;
1292 }
1293
1294 static pa_memchunk* convert_to_work_format(pa_resampler *r, pa_memchunk *input) {
1295     unsigned in_n_samples, out_n_samples;
1296     void *src, *dst;
1297     bool have_leftover;
1298     size_t leftover_length = 0;
1299
1300     pa_assert(r);
1301     pa_assert(input);
1302     pa_assert(input->memblock);
1303
1304     /* Convert the incoming sample into the work sample format and place them
1305      * in to_work_format_buf. The leftover data is already converted, so it's
1306      * part of the output buffer. */
1307
1308     have_leftover = r->leftover_in_to_work;
1309     r->leftover_in_to_work = false;
1310
1311     if (!have_leftover && (!r->to_work_format_func || !input->length))
1312         return input;
1313     else if (input->length <= 0)
1314         return &r->to_work_format_buf;
1315
1316     in_n_samples = out_n_samples = (unsigned) ((input->length / r->i_fz) * r->i_ss.channels);
1317
1318     if (have_leftover) {
1319         leftover_length = r->to_work_format_buf.length;
1320         out_n_samples += (unsigned) (leftover_length / r->w_sz);
1321     }
1322
1323     fit_buf(r, &r->to_work_format_buf, r->w_sz * out_n_samples, &r->to_work_format_buf_size, leftover_length);
1324
1325     src = pa_memblock_acquire_chunk(input);
1326     dst = (uint8_t *) pa_memblock_acquire(r->to_work_format_buf.memblock) + leftover_length;
1327
1328     if (r->to_work_format_func)
1329         r->to_work_format_func(in_n_samples, src, dst);
1330     else
1331         memcpy(dst, src, input->length);
1332
1333     pa_memblock_release(input->memblock);
1334     pa_memblock_release(r->to_work_format_buf.memblock);
1335
1336     return &r->to_work_format_buf;
1337 }
1338
1339 static pa_memchunk *remap_channels(pa_resampler *r, pa_memchunk *input) {
1340     unsigned in_n_samples, out_n_samples, in_n_frames, out_n_frames;
1341     void *src, *dst;
1342     size_t leftover_length = 0;
1343     bool have_leftover;
1344
1345     pa_assert(r);
1346     pa_assert(input);
1347     pa_assert(input->memblock);
1348
1349     /* Remap channels and place the result in remap_buf. There may be leftover
1350      * data in the beginning of remap_buf. The leftover data is already
1351      * remapped, so it's not part of the input, it's part of the output. */
1352
1353     have_leftover = r->leftover_in_remap;
1354     r->leftover_in_remap = false;
1355
1356     if (!have_leftover && (!r->map_required || input->length <= 0))
1357         return input;
1358     else if (input->length <= 0)
1359         return &r->remap_buf;
1360
1361     in_n_samples = (unsigned) (input->length / r->w_sz);
1362     in_n_frames = out_n_frames = in_n_samples / r->i_ss.channels;
1363
1364     if (have_leftover) {
1365         leftover_length = r->remap_buf.length;
1366         out_n_frames += leftover_length / r->w_fz;
1367     }
1368
1369     out_n_samples = out_n_frames * r->o_ss.channels;
1370     fit_buf(r, &r->remap_buf, out_n_samples * r->w_sz, &r->remap_buf_size, leftover_length);
1371
1372     src = pa_memblock_acquire_chunk(input);
1373     dst = (uint8_t *) pa_memblock_acquire(r->remap_buf.memblock) + leftover_length;
1374
1375     if (r->map_required) {
1376         pa_remap_t *remap = &r->remap;
1377
1378         pa_assert(remap->do_remap);
1379         remap->do_remap(remap, dst, src, in_n_frames);
1380
1381     } else
1382         memcpy(dst, src, input->length);
1383
1384     pa_memblock_release(input->memblock);
1385     pa_memblock_release(r->remap_buf.memblock);
1386
1387     return &r->remap_buf;
1388 }
1389
1390 static void save_leftover(pa_resampler *r, void *buf, size_t len) {
1391     void *dst;
1392
1393     pa_assert(r);
1394     pa_assert(buf);
1395     pa_assert(len > 0);
1396
1397     /* Store the leftover data. */
1398     fit_buf(r, r->leftover_buf, len, r->leftover_buf_size, 0);
1399     *r->have_leftover = true;
1400
1401     dst = pa_memblock_acquire(r->leftover_buf->memblock);
1402     memmove(dst, buf, len);
1403     pa_memblock_release(r->leftover_buf->memblock);
1404 }
1405
1406 static pa_memchunk *resample(pa_resampler *r, pa_memchunk *input) {
1407     unsigned in_n_frames, out_n_frames, leftover_n_frames;
1408
1409     pa_assert(r);
1410     pa_assert(input);
1411
1412     /* Resample the data and place the result in resample_buf. */
1413
1414     if (!r->impl.resample || !input->length)
1415         return input;
1416
1417     in_n_frames = (unsigned) (input->length / r->w_fz);
1418
1419     out_n_frames = ((in_n_frames*r->o_ss.rate)/r->i_ss.rate)+EXTRA_FRAMES;
1420     fit_buf(r, &r->resample_buf, r->w_fz * out_n_frames, &r->resample_buf_size, 0);
1421
1422     leftover_n_frames = r->impl.resample(r, input, in_n_frames, &r->resample_buf, &out_n_frames);
1423
1424     if (leftover_n_frames > 0) {
1425         void *leftover_data = (uint8_t *) pa_memblock_acquire_chunk(input) + (in_n_frames - leftover_n_frames) * r->w_fz;
1426         save_leftover(r, leftover_data, leftover_n_frames * r->w_fz);
1427         pa_memblock_release(input->memblock);
1428     }
1429
1430     r->resample_buf.length = out_n_frames * r->w_fz;
1431
1432     return &r->resample_buf;
1433 }
1434
1435 static pa_memchunk *convert_from_work_format(pa_resampler *r, pa_memchunk *input) {
1436     unsigned n_samples, n_frames;
1437     void *src, *dst;
1438
1439     pa_assert(r);
1440     pa_assert(input);
1441
1442     /* Convert the data into the correct sample type and place the result in
1443      * from_work_format_buf. */
1444
1445     if (!r->from_work_format_func || !input->length)
1446         return input;
1447
1448     n_samples = (unsigned) (input->length / r->w_sz);
1449     n_frames = n_samples / r->o_ss.channels;
1450     fit_buf(r, &r->from_work_format_buf, r->o_fz * n_frames, &r->from_work_format_buf_size, 0);
1451
1452     src = pa_memblock_acquire_chunk(input);
1453     dst = pa_memblock_acquire(r->from_work_format_buf.memblock);
1454     r->from_work_format_func(n_samples, src, dst);
1455     pa_memblock_release(input->memblock);
1456     pa_memblock_release(r->from_work_format_buf.memblock);
1457
1458     return &r->from_work_format_buf;
1459 }
1460
1461 void pa_resampler_run(pa_resampler *r, const pa_memchunk *in, pa_memchunk *out) {
1462     pa_memchunk *buf;
1463
1464     pa_assert(r);
1465     pa_assert(in);
1466     pa_assert(out);
1467     pa_assert(in->length);
1468     pa_assert(in->memblock);
1469     pa_assert(in->length % r->i_fz == 0);
1470
1471     buf = (pa_memchunk*) in;
1472     buf = convert_to_work_format(r, buf);
1473
1474     /* Try to save resampling effort: if we have more output channels than
1475      * input channels, do resampling first, then remapping. */
1476     if (r->o_ss.channels <= r->i_ss.channels) {
1477         buf = remap_channels(r, buf);
1478         buf = resample(r, buf);
1479     } else {
1480         buf = resample(r, buf);
1481         buf = remap_channels(r, buf);
1482     }
1483
1484     if (r->lfe_filter)
1485         buf = pa_lfe_filter_process(r->lfe_filter, buf);
1486
1487     if (buf->length) {
1488         buf = convert_from_work_format(r, buf);
1489         *out = *buf;
1490
1491         if (buf == in)
1492             pa_memblock_ref(buf->memblock);
1493         else
1494             pa_memchunk_reset(buf);
1495     } else
1496         pa_memchunk_reset(out);
1497 }
1498
1499 /*** copy (noop) implementation ***/
1500
1501 static int copy_init(pa_resampler *r) {
1502     pa_assert(r);
1503
1504     pa_assert(r->o_ss.rate == r->i_ss.rate);
1505
1506     return 0;
1507 }