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