swr: add double precision support to the rematrix code
[ffmpeg.git] / libswresample / swresample.c
1 /*
2  * Copyright (C) 2011 Michael Niedermayer (michaelni@gmx.at)
3  *
4  * This file is part of libswresample
5  *
6  * libswresample is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * libswresample is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with libswresample; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "libavutil/opt.h"
22 #include "swresample_internal.h"
23 #include "audioconvert.h"
24 #include "libavutil/avassert.h"
25 #include "libavutil/audioconvert.h"
26
27 #define  C30DB  M_SQRT2
28 #define  C15DB  1.189207115
29 #define C__0DB  1.0
30 #define C_15DB  0.840896415
31 #define C_30DB  M_SQRT1_2
32 #define C_45DB  0.594603558
33 #define C_60DB  0.5
34
35
36 //TODO split options array out?
37 #define OFFSET(x) offsetof(SwrContext,x)
38 #define PARAM AV_OPT_FLAG_AUDIO_PARAM
39
40 static const AVOption options[]={
41 {"ich"                  ,  "Input Channel Count"        , OFFSET( in.ch_count   ), AV_OPT_TYPE_INT  , {.dbl=2                     }, 0      , SWR_CH_MAX, PARAM},
42 {"in_channel_count"     ,  "Input Channel Count"        , OFFSET( in.ch_count   ), AV_OPT_TYPE_INT  , {.dbl=2                     }, 0      , SWR_CH_MAX, PARAM},
43 {"och"                  , "Output Channel Count"        , OFFSET(out.ch_count   ), AV_OPT_TYPE_INT  , {.dbl=2                     }, 0      , SWR_CH_MAX, PARAM},
44 {"out_channel_count"    , "Output Channel Count"        , OFFSET(out.ch_count   ), AV_OPT_TYPE_INT  , {.dbl=2                     }, 0      , SWR_CH_MAX, PARAM},
45 {"uch"                  ,   "Used Channel Count"        , OFFSET(used_ch_count  ), AV_OPT_TYPE_INT  , {.dbl=0                     }, 0      , SWR_CH_MAX, PARAM},
46 {"used_channel_count"   ,   "Used Channel Count"        , OFFSET(used_ch_count  ), AV_OPT_TYPE_INT  , {.dbl=0                     }, 0      , SWR_CH_MAX, PARAM},
47 {"isr"                  ,  "Input Sample Rate"          , OFFSET( in_sample_rate), AV_OPT_TYPE_INT  , {.dbl=48000                 }, 1      , INT_MAX   , PARAM},
48 {"in_sample_rate"       ,  "Input Sample Rate"          , OFFSET( in_sample_rate), AV_OPT_TYPE_INT  , {.dbl=48000                 }, 1      , INT_MAX   , PARAM},
49 {"osr"                  , "Output Sample Rate"          , OFFSET(out_sample_rate), AV_OPT_TYPE_INT  , {.dbl=48000                 }, 1      , INT_MAX   , PARAM},
50 {"out_sample_rate"      , "Output Sample Rate"          , OFFSET(out_sample_rate), AV_OPT_TYPE_INT  , {.dbl=48000                 }, 1      , INT_MAX   , PARAM},
51 {"isf"                  ,    "Input Sample Format"      , OFFSET( in_sample_fmt ), AV_OPT_TYPE_INT  , {.dbl=AV_SAMPLE_FMT_S16     }, 0      , AV_SAMPLE_FMT_NB-1+256, PARAM},
52 {"in_sample_fmt"        ,    "Input Sample Format"      , OFFSET( in_sample_fmt ), AV_OPT_TYPE_INT  , {.dbl=AV_SAMPLE_FMT_S16     }, 0      , AV_SAMPLE_FMT_NB-1+256, PARAM},
53 {"osf"                  ,   "Output Sample Format"      , OFFSET(out_sample_fmt ), AV_OPT_TYPE_INT  , {.dbl=AV_SAMPLE_FMT_S16     }, 0      , AV_SAMPLE_FMT_NB-1+256, PARAM},
54 {"out_sample_fmt"       ,   "Output Sample Format"      , OFFSET(out_sample_fmt ), AV_OPT_TYPE_INT  , {.dbl=AV_SAMPLE_FMT_S16     }, 0      , AV_SAMPLE_FMT_NB-1+256, PARAM},
55 {"tsf"                  , "Internal Sample Format"      , OFFSET(int_sample_fmt ), AV_OPT_TYPE_INT  , {.dbl=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_FLTP, PARAM},
56 {"internal_sample_fmt"  , "Internal Sample Format"      , OFFSET(int_sample_fmt ), AV_OPT_TYPE_INT  , {.dbl=AV_SAMPLE_FMT_NONE    }, -1     , AV_SAMPLE_FMT_FLTP, PARAM},
57 {"icl"                  ,   "Input Channel Layout"      , OFFSET( in_ch_layout  ), AV_OPT_TYPE_INT64, {.dbl=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
58 {"in_channel_layout"    ,   "Input Channel Layout"      , OFFSET( in_ch_layout  ), AV_OPT_TYPE_INT64, {.dbl=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
59 {"ocl"                  ,  "Output Channel Layout"      , OFFSET(out_ch_layout  ), AV_OPT_TYPE_INT64, {.dbl=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
60 {"out_channel_layout"   ,  "Output Channel Layout"      , OFFSET(out_ch_layout  ), AV_OPT_TYPE_INT64, {.dbl=0                     }, 0      , INT64_MAX , PARAM, "channel_layout"},
61 {"clev"                 ,    "Center Mix Level"         , OFFSET(clev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
62 {"center_mix_level"     ,    "Center Mix Level"         , OFFSET(clev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
63 {"slev"                 , "Sourround Mix Level"         , OFFSET(slev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
64 {"surround_mix_level"   , "Sourround Mix Level"         , OFFSET(slev           ), AV_OPT_TYPE_FLOAT, {.dbl=C_30DB                }, -32    , 32        , PARAM},
65 {"lfe_mix_level"        , "LFE Mix Level"               , OFFSET(lfe_mix_level  ), AV_OPT_TYPE_FLOAT, {.dbl=0                     }, -32    , 32        , PARAM},
66 {"rmvol"                , "Rematrix Volume"             , OFFSET(rematrix_volume), AV_OPT_TYPE_FLOAT, {.dbl=1.0                   }, -1000  , 1000      , PARAM},
67 {"rematrix_volume"      , "Rematrix Volume"             , OFFSET(rematrix_volume), AV_OPT_TYPE_FLOAT, {.dbl=1.0                   }, -1000  , 1000      , PARAM},
68 {"flags"                , NULL                          , OFFSET(flags          ), AV_OPT_TYPE_FLAGS, {.dbl=0                     }, 0      , UINT_MAX  , PARAM, "flags"},
69 {"swr_flags"            , NULL                          , OFFSET(flags          ), AV_OPT_TYPE_FLAGS, {.dbl=0                     }, 0      , UINT_MAX  , PARAM, "flags"},
70 {"res"                  , "Force Resampling"            , 0                      , AV_OPT_TYPE_CONST, {.dbl=SWR_FLAG_RESAMPLE     }, INT_MIN, INT_MAX   , PARAM, "flags"},
71 {"dither_scale"         , "Dither Scale"                , OFFSET(dither_scale   ), AV_OPT_TYPE_FLOAT, {.dbl=1                     }, 0      , INT_MAX   , PARAM},
72 {"dither_method"        , "Dither Method"               , OFFSET(dither_method  ), AV_OPT_TYPE_INT  , {.dbl=0                     }, 0      , SWR_DITHER_NB-1, PARAM, "dither_method"},
73 {"rectangular"          , "Rectangular Dither"          , 0                      , AV_OPT_TYPE_CONST, {.dbl=SWR_DITHER_RECTANGULAR}, INT_MIN, INT_MAX   , PARAM, "dither_method"},
74 {"triangular"           ,  "Triangular Dither"          , 0                      , AV_OPT_TYPE_CONST, {.dbl=SWR_DITHER_TRIANGULAR }, INT_MIN, INT_MAX   , PARAM, "dither_method"},
75 {"triangular_hp"        , "Triangular Dither With High Pass" , 0                 , AV_OPT_TYPE_CONST, {.dbl=SWR_DITHER_TRIANGULAR_HIGHPASS }, INT_MIN, INT_MAX, PARAM, "dither_method"},
76 {"filter_size"          , "Resampling Filter Size"      , OFFSET(filter_size)    , AV_OPT_TYPE_INT  , {.dbl=16                    }, 0      , INT_MAX   , PARAM },
77 {"phase_shift"          , "Resampling Phase Shift"      , OFFSET(phase_shift)    , AV_OPT_TYPE_INT  , {.dbl=10                    }, 0      , 30        , PARAM },
78 {"linear_interp"        , "Use Linear Interpolation"    , OFFSET(linear_interp)  , AV_OPT_TYPE_INT  , {.dbl=0                     }, 0      , 1         , PARAM },
79 {"cutoff"               , "Cutoff Frequency Ratio"      , OFFSET(cutoff)         , AV_OPT_TYPE_DOUBLE,{.dbl=0.8                   }, 0      , 1         , PARAM },
80 {0}
81 };
82
83 static const char* context_to_name(void* ptr) {
84     return "SWR";
85 }
86
87 static const AVClass av_class = {
88     .class_name                = "SwrContext",
89     .item_name                 = context_to_name,
90     .option                    = options,
91     .version                   = LIBAVUTIL_VERSION_INT,
92     .log_level_offset_offset   = OFFSET(log_level_offset),
93     .parent_log_context_offset = OFFSET(log_ctx),
94 };
95
96 unsigned swresample_version(void)
97 {
98     av_assert0(LIBSWRESAMPLE_VERSION_MICRO >= 100);
99     return LIBSWRESAMPLE_VERSION_INT;
100 }
101
102 const char *swresample_configuration(void)
103 {
104     return FFMPEG_CONFIGURATION;
105 }
106
107 const char *swresample_license(void)
108 {
109 #define LICENSE_PREFIX "libswresample license: "
110     return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
111 }
112
113 int swr_set_channel_mapping(struct SwrContext *s, const int *channel_map){
114     if(!s || s->in_convert) // s needs to be allocated but not initialized
115         return AVERROR(EINVAL);
116     s->channel_map = channel_map;
117     return 0;
118 }
119
120 const AVClass *swr_get_class(void)
121 {
122     return &av_class;
123 }
124
125 struct SwrContext *swr_alloc(void){
126     SwrContext *s= av_mallocz(sizeof(SwrContext));
127     if(s){
128         s->av_class= &av_class;
129         av_opt_set_defaults(s);
130     }
131     return s;
132 }
133
134 struct SwrContext *swr_alloc_set_opts(struct SwrContext *s,
135                                       int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate,
136                                       int64_t  in_ch_layout, enum AVSampleFormat  in_sample_fmt, int  in_sample_rate,
137                                       int log_offset, void *log_ctx){
138     if(!s) s= swr_alloc();
139     if(!s) return NULL;
140
141     s->log_level_offset= log_offset;
142     s->log_ctx= log_ctx;
143
144     av_opt_set_int(s, "ocl", out_ch_layout,   0);
145     av_opt_set_int(s, "osf", out_sample_fmt,  0);
146     av_opt_set_int(s, "osr", out_sample_rate, 0);
147     av_opt_set_int(s, "icl", in_ch_layout,    0);
148     av_opt_set_int(s, "isf", in_sample_fmt,   0);
149     av_opt_set_int(s, "isr", in_sample_rate,  0);
150     av_opt_set_int(s, "tsf", AV_SAMPLE_FMT_NONE,   0);
151     av_opt_set_int(s, "ich", av_get_channel_layout_nb_channels(s-> in_ch_layout), 0);
152     av_opt_set_int(s, "och", av_get_channel_layout_nb_channels(s->out_ch_layout), 0);
153     av_opt_set_int(s, "uch", 0, 0);
154     return s;
155 }
156
157 static void set_audiodata_fmt(AudioData *a, enum AVSampleFormat fmt){
158     a->fmt   = fmt;
159     a->bps   = av_get_bytes_per_sample(fmt);
160     a->planar= av_sample_fmt_is_planar(fmt);
161 }
162
163 static void free_temp(AudioData *a){
164     av_free(a->data);
165     memset(a, 0, sizeof(*a));
166 }
167
168 void swr_free(SwrContext **ss){
169     SwrContext *s= *ss;
170     if(s){
171         free_temp(&s->postin);
172         free_temp(&s->midbuf);
173         free_temp(&s->preout);
174         free_temp(&s->in_buffer);
175         free_temp(&s->dither);
176         swri_audio_convert_free(&s-> in_convert);
177         swri_audio_convert_free(&s->out_convert);
178         swri_audio_convert_free(&s->full_convert);
179         swri_resample_free(&s->resample);
180         swri_rematrix_free(s);
181     }
182
183     av_freep(ss);
184 }
185
186 int swr_init(struct SwrContext *s){
187     s->in_buffer_index= 0;
188     s->in_buffer_count= 0;
189     s->resample_in_constraint= 0;
190     free_temp(&s->postin);
191     free_temp(&s->midbuf);
192     free_temp(&s->preout);
193     free_temp(&s->in_buffer);
194     free_temp(&s->dither);
195     swri_audio_convert_free(&s-> in_convert);
196     swri_audio_convert_free(&s->out_convert);
197     swri_audio_convert_free(&s->full_convert);
198     swri_rematrix_free(s);
199
200     s->flushed = 0;
201
202     if(s-> in_sample_fmt >= AV_SAMPLE_FMT_NB){
203         av_log(s, AV_LOG_ERROR, "Requested input sample format %d is invalid\n", s->in_sample_fmt);
204         return AVERROR(EINVAL);
205     }
206     if(s->out_sample_fmt >= AV_SAMPLE_FMT_NB){
207         av_log(s, AV_LOG_ERROR, "Requested output sample format %d is invalid\n", s->out_sample_fmt);
208         return AVERROR(EINVAL);
209     }
210
211     //FIXME should we allow/support using FLT on material that doesnt need it ?
212     if(av_get_planar_sample_fmt(s->in_sample_fmt) <= AV_SAMPLE_FMT_S16P || s->int_sample_fmt==AV_SAMPLE_FMT_S16P){
213         s->int_sample_fmt= AV_SAMPLE_FMT_S16P;
214     }else
215         s->int_sample_fmt= AV_SAMPLE_FMT_FLTP;
216
217     if(   s->int_sample_fmt != AV_SAMPLE_FMT_S16P
218         &&s->int_sample_fmt != AV_SAMPLE_FMT_S32P
219         &&s->int_sample_fmt != AV_SAMPLE_FMT_FLTP
220         &&s->int_sample_fmt != AV_SAMPLE_FMT_DBLP){
221         av_log(s, AV_LOG_ERROR, "Requested sample format %s is not supported internally, S16/S32/FLT/DBL is supported\n", av_get_sample_fmt_name(s->int_sample_fmt));
222         return AVERROR(EINVAL);
223     }
224
225     set_audiodata_fmt(&s-> in, s-> in_sample_fmt);
226     set_audiodata_fmt(&s->out, s->out_sample_fmt);
227
228     if (s->out_sample_rate!=s->in_sample_rate || (s->flags & SWR_FLAG_RESAMPLE)){
229         s->resample = swri_resample_init(s->resample, s->out_sample_rate, s->in_sample_rate, s->filter_size, s->phase_shift, s->linear_interp, s->cutoff, s->int_sample_fmt);
230     }else
231         swri_resample_free(&s->resample);
232     if(    s->int_sample_fmt != AV_SAMPLE_FMT_S16P
233         && s->int_sample_fmt != AV_SAMPLE_FMT_S32P
234         && s->int_sample_fmt != AV_SAMPLE_FMT_FLTP
235         && s->int_sample_fmt != AV_SAMPLE_FMT_DBLP
236         && s->resample){
237         av_log(s, AV_LOG_ERROR, "Resampling only supported with internal s16/s32/flt/dbl\n");
238         return -1;
239     }
240
241     if(!s->used_ch_count)
242         s->used_ch_count= s->in.ch_count;
243
244     if(s->used_ch_count && s-> in_ch_layout && s->used_ch_count != av_get_channel_layout_nb_channels(s-> in_ch_layout)){
245         av_log(s, AV_LOG_WARNING, "Input channel layout has a different number of channels than the number of used channels, ignoring layout\n");
246         s-> in_ch_layout= 0;
247     }
248
249     if(!s-> in_ch_layout)
250         s-> in_ch_layout= av_get_default_channel_layout(s->used_ch_count);
251     if(!s->out_ch_layout)
252         s->out_ch_layout= av_get_default_channel_layout(s->out.ch_count);
253
254     s->rematrix= s->out_ch_layout  !=s->in_ch_layout || s->rematrix_volume!=1.0 ||
255                  s->rematrix_custom;
256
257 #define RSC 1 //FIXME finetune
258     if(!s-> in.ch_count)
259         s-> in.ch_count= av_get_channel_layout_nb_channels(s-> in_ch_layout);
260     if(!s->used_ch_count)
261         s->used_ch_count= s->in.ch_count;
262     if(!s->out.ch_count)
263         s->out.ch_count= av_get_channel_layout_nb_channels(s->out_ch_layout);
264
265     if(!s-> in.ch_count){
266         av_assert0(!s->in_ch_layout);
267         av_log(s, AV_LOG_ERROR, "Input channel count and layout are unset\n");
268         return -1;
269     }
270
271     if ((!s->out_ch_layout || !s->in_ch_layout) && s->used_ch_count != s->out.ch_count && !s->rematrix_custom) {
272         av_log(s, AV_LOG_ERROR, "Rematrix is needed but there is not enough information to do it\n");
273         return -1;
274     }
275
276 av_assert0(s->used_ch_count);
277 av_assert0(s->out.ch_count);
278     s->resample_first= RSC*s->out.ch_count/s->in.ch_count - RSC < s->out_sample_rate/(float)s-> in_sample_rate - 1.0;
279
280     s->in_buffer= s->in;
281
282     if(!s->resample && !s->rematrix && !s->channel_map && !s->dither_method){
283         s->full_convert = swri_audio_convert_alloc(s->out_sample_fmt,
284                                                    s-> in_sample_fmt, s-> in.ch_count, NULL, 0);
285         return 0;
286     }
287
288     s->in_convert = swri_audio_convert_alloc(s->int_sample_fmt,
289                                              s-> in_sample_fmt, s->used_ch_count, s->channel_map, 0);
290     s->out_convert= swri_audio_convert_alloc(s->out_sample_fmt,
291                                              s->int_sample_fmt, s->out.ch_count, NULL, 0);
292
293
294     s->postin= s->in;
295     s->preout= s->out;
296     s->midbuf= s->in;
297
298     if(s->channel_map){
299         s->postin.ch_count=
300         s->midbuf.ch_count= s->used_ch_count;
301         if(s->resample)
302             s->in_buffer.ch_count= s->used_ch_count;
303     }
304     if(!s->resample_first){
305         s->midbuf.ch_count= s->out.ch_count;
306         if(s->resample)
307             s->in_buffer.ch_count = s->out.ch_count;
308     }
309
310     set_audiodata_fmt(&s->postin, s->int_sample_fmt);
311     set_audiodata_fmt(&s->midbuf, s->int_sample_fmt);
312     set_audiodata_fmt(&s->preout, s->int_sample_fmt);
313
314     if(s->resample){
315         set_audiodata_fmt(&s->in_buffer, s->int_sample_fmt);
316     }
317
318     s->dither = s->preout;
319
320     if(s->rematrix || s->dither_method)
321         return swri_rematrix_init(s);
322
323     return 0;
324 }
325
326 static int realloc_audio(AudioData *a, int count){
327     int i, countb;
328     AudioData old;
329
330     if(a->count >= count)
331         return 0;
332
333     count*=2;
334
335     countb= FFALIGN(count*a->bps, 32);
336     old= *a;
337
338     av_assert0(a->bps);
339     av_assert0(a->ch_count);
340
341     a->data= av_malloc(countb*a->ch_count);
342     if(!a->data)
343         return AVERROR(ENOMEM);
344     for(i=0; i<a->ch_count; i++){
345         a->ch[i]= a->data + i*(a->planar ? countb : a->bps);
346         if(a->planar) memcpy(a->ch[i], old.ch[i], a->count*a->bps);
347     }
348     if(!a->planar) memcpy(a->ch[0], old.ch[0], a->count*a->ch_count*a->bps);
349     av_free(old.data);
350     a->count= count;
351
352     return 1;
353 }
354
355 static void copy(AudioData *out, AudioData *in,
356                  int count){
357     av_assert0(out->planar == in->planar);
358     av_assert0(out->bps == in->bps);
359     av_assert0(out->ch_count == in->ch_count);
360     if(out->planar){
361         int ch;
362         for(ch=0; ch<out->ch_count; ch++)
363             memcpy(out->ch[ch], in->ch[ch], count*out->bps);
364     }else
365         memcpy(out->ch[0], in->ch[0], count*out->ch_count*out->bps);
366 }
367
368 static void fill_audiodata(AudioData *out, uint8_t *in_arg [SWR_CH_MAX]){
369     int i;
370     if(out->planar){
371         for(i=0; i<out->ch_count; i++)
372             out->ch[i]= in_arg[i];
373     }else{
374         for(i=0; i<out->ch_count; i++)
375             out->ch[i]= in_arg[0] + i*out->bps;
376     }
377 }
378
379 /**
380  *
381  * out may be equal in.
382  */
383 static void buf_set(AudioData *out, AudioData *in, int count){
384     int ch;
385     if(in->planar){
386         for(ch=0; ch<out->ch_count; ch++)
387             out->ch[ch]= in->ch[ch] + count*out->bps;
388     }else{
389         for(ch=0; ch<out->ch_count; ch++)
390             out->ch[ch]= in->ch[0] + (ch + count*out->ch_count) * out->bps;
391     }
392 }
393
394 /**
395  *
396  * @return number of samples output per channel
397  */
398 static int resample(SwrContext *s, AudioData *out_param, int out_count,
399                              const AudioData * in_param, int in_count){
400     AudioData in, out, tmp;
401     int ret_sum=0;
402     int border=0;
403
404     tmp=out=*out_param;
405     in =  *in_param;
406
407     do{
408         int ret, size, consumed;
409         if(!s->resample_in_constraint && s->in_buffer_count){
410             buf_set(&tmp, &s->in_buffer, s->in_buffer_index);
411             ret= swri_multiple_resample(s->resample, &out, out_count, &tmp, s->in_buffer_count, &consumed);
412             out_count -= ret;
413             ret_sum += ret;
414             buf_set(&out, &out, ret);
415             s->in_buffer_count -= consumed;
416             s->in_buffer_index += consumed;
417
418             if(!in_count)
419                 break;
420             if(s->in_buffer_count <= border){
421                 buf_set(&in, &in, -s->in_buffer_count);
422                 in_count += s->in_buffer_count;
423                 s->in_buffer_count=0;
424                 s->in_buffer_index=0;
425                 border = 0;
426             }
427         }
428
429         if(in_count && !s->in_buffer_count){
430             s->in_buffer_index=0;
431             ret= swri_multiple_resample(s->resample, &out, out_count, &in, in_count, &consumed);
432             out_count -= ret;
433             ret_sum += ret;
434             buf_set(&out, &out, ret);
435             in_count -= consumed;
436             buf_set(&in, &in, consumed);
437         }
438
439         //TODO is this check sane considering the advanced copy avoidance below
440         size= s->in_buffer_index + s->in_buffer_count + in_count;
441         if(   size > s->in_buffer.count
442            && s->in_buffer_count + in_count <= s->in_buffer_index){
443             buf_set(&tmp, &s->in_buffer, s->in_buffer_index);
444             copy(&s->in_buffer, &tmp, s->in_buffer_count);
445             s->in_buffer_index=0;
446         }else
447             if((ret=realloc_audio(&s->in_buffer, size)) < 0)
448                 return ret;
449
450         if(in_count){
451             int count= in_count;
452             if(s->in_buffer_count && s->in_buffer_count+2 < count && out_count) count= s->in_buffer_count+2;
453
454             buf_set(&tmp, &s->in_buffer, s->in_buffer_index + s->in_buffer_count);
455             copy(&tmp, &in, /*in_*/count);
456             s->in_buffer_count += count;
457             in_count -= count;
458             border += count;
459             buf_set(&in, &in, count);
460             s->resample_in_constraint= 0;
461             if(s->in_buffer_count != count || in_count)
462                 continue;
463         }
464         break;
465     }while(1);
466
467     s->resample_in_constraint= !!out_count;
468
469     return ret_sum;
470 }
471
472 static int swr_convert_internal(struct SwrContext *s, AudioData *out, int out_count,
473                                                       AudioData *in , int  in_count){
474     AudioData *postin, *midbuf, *preout;
475     int ret/*, in_max*/;
476     AudioData preout_tmp, midbuf_tmp;
477
478     if(s->full_convert){
479         av_assert0(!s->resample);
480         swri_audio_convert(s->full_convert, out, in, in_count);
481         return out_count;
482     }
483
484 //     in_max= out_count*(int64_t)s->in_sample_rate / s->out_sample_rate + resample_filter_taps;
485 //     in_count= FFMIN(in_count, in_in + 2 - s->hist_buffer_count);
486
487     if((ret=realloc_audio(&s->postin, in_count))<0)
488         return ret;
489     if(s->resample_first){
490         av_assert0(s->midbuf.ch_count == s->used_ch_count);
491         if((ret=realloc_audio(&s->midbuf, out_count))<0)
492             return ret;
493     }else{
494         av_assert0(s->midbuf.ch_count ==  s->out.ch_count);
495         if((ret=realloc_audio(&s->midbuf,  in_count))<0)
496             return ret;
497     }
498     if((ret=realloc_audio(&s->preout, out_count))<0)
499         return ret;
500
501     postin= &s->postin;
502
503     midbuf_tmp= s->midbuf;
504     midbuf= &midbuf_tmp;
505     preout_tmp= s->preout;
506     preout= &preout_tmp;
507
508     if(s->int_sample_fmt == s-> in_sample_fmt && s->in.planar)
509         postin= in;
510
511     if(s->resample_first ? !s->resample : !s->rematrix)
512         midbuf= postin;
513
514     if(s->resample_first ? !s->rematrix : !s->resample)
515         preout= midbuf;
516
517     if(s->int_sample_fmt == s->out_sample_fmt && s->out.planar){
518         if(preout==in){
519             out_count= FFMIN(out_count, in_count); //TODO check at the end if this is needed or redundant
520             av_assert0(s->in.planar); //we only support planar internally so it has to be, we support copying non planar though
521             copy(out, in, out_count);
522             return out_count;
523         }
524         else if(preout==postin) preout= midbuf= postin= out;
525         else if(preout==midbuf) preout= midbuf= out;
526         else                    preout= out;
527     }
528
529     if(in != postin){
530         swri_audio_convert(s->in_convert, postin, in, in_count);
531     }
532
533     if(s->resample_first){
534         if(postin != midbuf)
535             out_count= resample(s, midbuf, out_count, postin, in_count);
536         if(midbuf != preout)
537             swri_rematrix(s, preout, midbuf, out_count, preout==out);
538     }else{
539         if(postin != midbuf)
540             swri_rematrix(s, midbuf, postin, in_count, midbuf==out);
541         if(midbuf != preout)
542             out_count= resample(s, preout, out_count, midbuf, in_count);
543     }
544
545     if(preout != out && out_count){
546         if(s->dither_method){
547             int ch;
548             int dither_count= FFMAX(out_count, 1<<16);
549             av_assert0(preout != in);
550
551             if((ret=realloc_audio(&s->dither, dither_count))<0)
552                 return ret;
553             if(ret)
554                 for(ch=0; ch<s->dither.ch_count; ch++)
555                     swri_get_dither(s, s->dither.ch[ch], s->dither.count, 12345678913579<<ch, s->out_sample_fmt, s->int_sample_fmt);
556             av_assert0(s->dither.ch_count == preout->ch_count);
557
558             if(s->dither_pos + out_count > s->dither.count)
559                 s->dither_pos = 0;
560
561             for(ch=0; ch<preout->ch_count; ch++)
562                 s->mix_2_1_f(preout->ch[ch], preout->ch[ch], s->dither.ch[ch] + s->dither.bps * s->dither_pos, s->native_one, 0, 0, out_count);
563
564             s->dither_pos += out_count;
565         }
566 //FIXME packed doesnt need more than 1 chan here!
567         swri_audio_convert(s->out_convert, out, preout, out_count);
568     }
569     return out_count;
570 }
571
572 int swr_convert(struct SwrContext *s, uint8_t *out_arg[SWR_CH_MAX], int out_count,
573                                 const uint8_t *in_arg [SWR_CH_MAX], int  in_count){
574     AudioData * in= &s->in;
575     AudioData *out= &s->out;
576
577     if(!in_arg){
578         if(s->in_buffer_count){
579             if (s->resample && !s->flushed) {
580                 AudioData *a= &s->in_buffer;
581                 int i, j, ret;
582                 if((ret=realloc_audio(a, s->in_buffer_index + 2*s->in_buffer_count)) < 0)
583                     return ret;
584                 av_assert0(a->planar);
585                 for(i=0; i<a->ch_count; i++){
586                     for(j=0; j<s->in_buffer_count; j++){
587                         memcpy(a->ch[i] + (s->in_buffer_index+s->in_buffer_count+j  )*a->bps,
588                             a->ch[i] + (s->in_buffer_index+s->in_buffer_count-j-1)*a->bps, a->bps);
589                     }
590                 }
591                 s->in_buffer_count += (s->in_buffer_count+1)/2;
592                 s->resample_in_constraint = 0;
593                 s->flushed = 1;
594             }
595         }else{
596             return 0;
597         }
598     }else
599         fill_audiodata(in ,  (void*)in_arg);
600
601     fill_audiodata(out, out_arg);
602
603     if(s->resample){
604         return swr_convert_internal(s, out, out_count, in, in_count);
605     }else{
606         AudioData tmp= *in;
607         int ret2=0;
608         int ret, size;
609         size = FFMIN(out_count, s->in_buffer_count);
610         if(size){
611             buf_set(&tmp, &s->in_buffer, s->in_buffer_index);
612             ret= swr_convert_internal(s, out, size, &tmp, size);
613             if(ret<0)
614                 return ret;
615             ret2= ret;
616             s->in_buffer_count -= ret;
617             s->in_buffer_index += ret;
618             buf_set(out, out, ret);
619             out_count -= ret;
620             if(!s->in_buffer_count)
621                 s->in_buffer_index = 0;
622         }
623
624         if(in_count){
625             size= s->in_buffer_index + s->in_buffer_count + in_count - out_count;
626
627             if(in_count > out_count) { //FIXME move after swr_convert_internal
628                 if(   size > s->in_buffer.count
629                 && s->in_buffer_count + in_count - out_count <= s->in_buffer_index){
630                     buf_set(&tmp, &s->in_buffer, s->in_buffer_index);
631                     copy(&s->in_buffer, &tmp, s->in_buffer_count);
632                     s->in_buffer_index=0;
633                 }else
634                     if((ret=realloc_audio(&s->in_buffer, size)) < 0)
635                         return ret;
636             }
637
638             if(out_count){
639                 size = FFMIN(in_count, out_count);
640                 ret= swr_convert_internal(s, out, size, in, size);
641                 if(ret<0)
642                     return ret;
643                 buf_set(in, in, ret);
644                 in_count -= ret;
645                 ret2 += ret;
646             }
647             if(in_count){
648                 buf_set(&tmp, &s->in_buffer, s->in_buffer_index);
649                 copy(&tmp, in, in_count);
650                 s->in_buffer_count += in_count;
651             }
652         }
653         return ret2;
654     }
655 }
656