commands: playback speed: adjust video timing after change
[mplayer.git] / libmpcodecs / dec_audio.c
blob5e7fe652a5c2f34c4c12793ac8998416370dad9c
1 /*
2 * This file is part of MPlayer.
4 * MPlayer is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * MPlayer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <assert.h>
24 #include "config.h"
25 #include "mp_msg.h"
26 #include "bstr.h"
28 #include "stream/stream.h"
29 #include "libmpdemux/demuxer.h"
31 #include "codec-cfg.h"
32 #include "libmpdemux/stheader.h"
34 #include "dec_audio.h"
35 #include "ad.h"
36 #include "libaf/af_format.h"
38 #include "libaf/af.h"
40 int fakemono = 0;
42 af_cfg_t af_cfg = { 1, NULL }; // Configuration for audio filters
44 void afm_help(void)
46 int i;
47 mp_tmsg(MSGT_DECAUDIO, MSGL_INFO, "Available (compiled-in) audio codec families/drivers:\n");
48 mp_msg(MSGT_IDENTIFY, MSGL_INFO, "ID_AUDIO_DRIVERS\n");
49 mp_msg(MSGT_DECAUDIO, MSGL_INFO, " afm: info: (comment)\n");
50 for (i = 0; mpcodecs_ad_drivers[i] != NULL; i++)
51 if (mpcodecs_ad_drivers[i]->info->comment
52 && mpcodecs_ad_drivers[i]->info->comment[0])
53 mp_msg(MSGT_DECAUDIO, MSGL_INFO, "%9s %s (%s)\n",
54 mpcodecs_ad_drivers[i]->info->short_name,
55 mpcodecs_ad_drivers[i]->info->name,
56 mpcodecs_ad_drivers[i]->info->comment);
57 else
58 mp_msg(MSGT_DECAUDIO, MSGL_INFO, "%9s %s\n",
59 mpcodecs_ad_drivers[i]->info->short_name,
60 mpcodecs_ad_drivers[i]->info->name);
63 static int init_audio_codec(sh_audio_t *sh_audio)
65 assert(!sh_audio->initialized);
66 resync_audio_stream(sh_audio);
67 if ((af_cfg.force & AF_INIT_FORMAT_MASK) == AF_INIT_FLOAT) {
68 int fmt = AF_FORMAT_FLOAT_NE;
69 if (sh_audio->ad_driver->control(sh_audio, ADCTRL_QUERY_FORMAT,
70 &fmt) == CONTROL_TRUE) {
71 sh_audio->sample_format = fmt;
72 sh_audio->samplesize = 4;
75 sh_audio->audio_out_minsize = 8192; // default, preinit() may change it
76 if (!sh_audio->ad_driver->preinit(sh_audio)) {
77 mp_tmsg(MSGT_DECAUDIO, MSGL_ERR, "ADecoder preinit failed :(\n");
78 return 0;
81 /* allocate audio in buffer: */
82 if (sh_audio->audio_in_minsize > 0) {
83 sh_audio->a_in_buffer_size = sh_audio->audio_in_minsize;
84 mp_tmsg(MSGT_DECAUDIO, MSGL_V, "dec_audio: Allocating %d bytes for input buffer.\n",
85 sh_audio->a_in_buffer_size);
86 sh_audio->a_in_buffer = av_mallocz(sh_audio->a_in_buffer_size);
89 const int base_size = 65536;
90 // At least 64 KiB plus rounding up to next decodable unit size
91 sh_audio->a_buffer_size = base_size + sh_audio->audio_out_minsize;
93 mp_tmsg(MSGT_DECAUDIO, MSGL_V, "dec_audio: Allocating %d + %d = %d bytes for output buffer.\n",
94 sh_audio->audio_out_minsize, base_size, sh_audio->a_buffer_size);
96 sh_audio->a_buffer = av_mallocz(sh_audio->a_buffer_size);
97 if (!sh_audio->a_buffer)
98 abort();
99 sh_audio->a_buffer_len = 0;
101 if (!sh_audio->ad_driver->init(sh_audio)) {
102 mp_tmsg(MSGT_DECAUDIO, MSGL_V, "ADecoder init failed :(\n");
103 uninit_audio(sh_audio); // free buffers
104 return 0;
107 sh_audio->initialized = 1;
109 if (!sh_audio->channels || !sh_audio->samplerate) {
110 mp_tmsg(MSGT_DECAUDIO, MSGL_ERR, "Audio decoder did not specify "
111 "audio format!\n");
112 uninit_audio(sh_audio); // free buffers
113 return 0;
116 if (!sh_audio->o_bps)
117 sh_audio->o_bps = sh_audio->channels * sh_audio->samplerate
118 * sh_audio->samplesize;
119 return 1;
122 static int init_audio(sh_audio_t *sh_audio, char *codecname, char *afm,
123 int status, stringset_t *selected)
125 unsigned int orig_fourcc = sh_audio->wf ? sh_audio->wf->wFormatTag : 0;
126 int force = 0;
127 if (codecname && codecname[0] == '+') {
128 codecname = &codecname[1];
129 force = 1;
131 sh_audio->codec = NULL;
132 while (1) {
133 const ad_functions_t *mpadec;
134 int i;
135 sh_audio->ad_driver = 0;
136 // restore original fourcc:
137 if (sh_audio->wf)
138 sh_audio->wf->wFormatTag = i = orig_fourcc;
139 if (!(sh_audio->codec = find_audio_codec(sh_audio->format,
140 sh_audio->wf ? (&i) : NULL,
141 sh_audio->codec, force)))
142 break;
143 if (sh_audio->wf)
144 sh_audio->wf->wFormatTag = i;
145 // ok we found one codec
146 if (stringset_test(selected, sh_audio->codec->name))
147 continue; // already tried & failed
148 if (codecname && strcmp(sh_audio->codec->name, codecname))
149 continue; // -ac
150 if (afm && strcmp(sh_audio->codec->drv, afm))
151 continue; // afm doesn't match
152 if (!force && sh_audio->codec->status < status)
153 continue; // too unstable
154 stringset_add(selected, sh_audio->codec->name); // tagging it
155 // ok, it matches all rules, let's find the driver!
156 for (i = 0; mpcodecs_ad_drivers[i] != NULL; i++)
157 if (!strcmp(mpcodecs_ad_drivers[i]->info->short_name,
158 sh_audio->codec->drv))
159 break;
160 mpadec = mpcodecs_ad_drivers[i];
161 if (!mpadec) { // driver not available (==compiled in)
162 mp_tmsg(MSGT_DECAUDIO, MSGL_ERR,
163 "Requested audio codec family [%s] (afm=%s) not available.\nEnable it at compilation.\n",
164 sh_audio->codec->name, sh_audio->codec->drv);
165 continue;
167 // it's available, let's try to init!
168 // init()
169 mp_tmsg(MSGT_DECAUDIO, MSGL_V, "Opening audio decoder: [%s] %s\n",
170 mpadec->info->short_name, mpadec->info->name);
171 sh_audio->ad_driver = mpadec;
172 if (!init_audio_codec(sh_audio)) {
173 mp_tmsg(MSGT_DECAUDIO, MSGL_WARN, "Audio decoder init failed for "
174 "codecs.conf entry \"%s\".\n", sh_audio->codec->name);
175 continue; // try next...
177 // Yeah! We got it!
178 return 1;
180 return 0;
183 int init_best_audio_codec(sh_audio_t *sh_audio, char **audio_codec_list,
184 char **audio_fm_list)
186 stringset_t selected;
187 char *ac_l_default[2] = { "", (char *) NULL };
188 // hack:
189 if (!audio_codec_list)
190 audio_codec_list = ac_l_default;
191 // Go through the codec.conf and find the best codec...
192 sh_audio->initialized = 0;
193 stringset_init(&selected);
194 while (!sh_audio->initialized && *audio_codec_list) {
195 char *audio_codec = *(audio_codec_list++);
196 if (audio_codec[0]) {
197 if (audio_codec[0] == '-') {
198 // disable this codec:
199 stringset_add(&selected, audio_codec + 1);
200 } else {
201 // forced codec by name:
202 mp_tmsg(MSGT_DECAUDIO, MSGL_INFO, "Forced audio codec: %s\n",
203 audio_codec);
204 init_audio(sh_audio, audio_codec, NULL, -1, &selected);
206 } else {
207 int status;
208 // try in stability order: UNTESTED, WORKING, BUGGY.
209 // never try CRASHING.
210 if (audio_fm_list) {
211 char **fmlist = audio_fm_list;
212 // try first the preferred codec families:
213 while (!sh_audio->initialized && *fmlist) {
214 char *audio_fm = *(fmlist++);
215 mp_tmsg(MSGT_DECAUDIO, MSGL_INFO, "Trying to force audio codec driver family %s...\n",
216 audio_fm);
217 for (status = CODECS_STATUS__MAX;
218 status >= CODECS_STATUS__MIN; --status)
219 if (init_audio(sh_audio, NULL, audio_fm, status, &selected))
220 break;
223 if (!sh_audio->initialized)
224 for (status = CODECS_STATUS__MAX; status >= CODECS_STATUS__MIN;
225 --status)
226 if (init_audio(sh_audio, NULL, NULL, status, &selected))
227 break;
230 stringset_free(&selected);
232 if (!sh_audio->initialized) {
233 mp_tmsg(MSGT_DECAUDIO, MSGL_ERR, "Cannot find codec for audio format 0x%X.\n",
234 sh_audio->format);
235 return 0; // failed
238 mp_tmsg(MSGT_DECAUDIO, MSGL_INFO, "Selected audio codec: %s [%s]\n",
239 sh_audio->codecname ? sh_audio->codecname : sh_audio->codec->info,
240 sh_audio->ad_driver->info->print_name ?
241 sh_audio->ad_driver->info->print_name :
242 sh_audio->ad_driver->info->short_name);
243 mp_tmsg(MSGT_DECAUDIO, MSGL_V,
244 "Audio codecs.conf entry: %s (%s) afm: %s\n",
245 sh_audio->codec->name, sh_audio->codec->info, sh_audio->codec->drv);
246 mp_msg(MSGT_DECAUDIO, MSGL_INFO,
247 "AUDIO: %d Hz, %d ch, %s, %3.1f kbit/%3.2f%% (ratio: %d->%d)\n",
248 sh_audio->samplerate, sh_audio->channels,
249 af_fmt2str_short(sh_audio->sample_format),
250 sh_audio->i_bps * 8 * 0.001,
251 ((float) sh_audio->i_bps / sh_audio->o_bps) * 100.0,
252 sh_audio->i_bps, sh_audio->o_bps);
253 mp_msg(MSGT_IDENTIFY, MSGL_INFO,
254 "ID_AUDIO_BITRATE=%d\nID_AUDIO_RATE=%d\n" "ID_AUDIO_NCH=%d\n",
255 sh_audio->i_bps * 8, sh_audio->samplerate, sh_audio->channels);
257 return 1; // success
260 void uninit_audio(sh_audio_t *sh_audio)
262 if (sh_audio->afilter) {
263 mp_msg(MSGT_DECAUDIO, MSGL_V, "Uninit audio filters...\n");
264 af_uninit(sh_audio->afilter);
265 free(sh_audio->afilter);
266 sh_audio->afilter = NULL;
268 if (sh_audio->initialized) {
269 mp_tmsg(MSGT_DECAUDIO, MSGL_V, "Uninit audio: %s\n",
270 sh_audio->codec->drv);
271 sh_audio->ad_driver->uninit(sh_audio);
272 sh_audio->initialized = 0;
274 av_freep(&sh_audio->a_buffer);
275 av_freep(&sh_audio->a_in_buffer);
279 int init_audio_filters(sh_audio_t *sh_audio, int in_samplerate,
280 int *out_samplerate, int *out_channels, int *out_format)
282 af_stream_t *afs = sh_audio->afilter;
283 if (!afs) {
284 afs = calloc(1, sizeof(struct af_stream));
285 afs->opts = sh_audio->opts;
287 // input format: same as codec's output format:
288 afs->input.rate = in_samplerate;
289 afs->input.nch = sh_audio->channels;
290 afs->input.format = sh_audio->sample_format;
291 af_fix_parameters(&(afs->input));
293 // output format: same as ao driver's input format (if missing, fallback to input)
294 afs->output.rate = *out_samplerate;
295 afs->output.nch = *out_channels;
296 afs->output.format = *out_format;
297 af_fix_parameters(&(afs->output));
299 // filter config:
300 memcpy(&afs->cfg, &af_cfg, sizeof(af_cfg_t));
302 mp_tmsg(MSGT_DECAUDIO, MSGL_V, "Building audio filter chain for %dHz/%dch/%s -> %dHz/%dch/%s...\n",
303 afs->input.rate, afs->input.nch,
304 af_fmt2str_short(afs->input.format), afs->output.rate,
305 afs->output.nch, af_fmt2str_short(afs->output.format));
307 // let's autoprobe it!
308 if (0 != af_init(afs)) {
309 sh_audio->afilter = NULL;
310 free(afs);
311 return 0; // failed :(
314 *out_samplerate = afs->output.rate;
315 *out_channels = afs->output.nch;
316 *out_format = afs->output.format;
318 // ok!
319 sh_audio->afilter = (void *) afs;
320 return 1;
323 static void set_min_out_buffer_size(struct bstr *outbuf, int len)
325 size_t oldlen = talloc_get_size(outbuf->start);
326 if (oldlen < len) {
327 assert(outbuf->start); // talloc context should be already set
328 mp_msg(MSGT_DECAUDIO, MSGL_V, "Increasing filtered audio buffer size "
329 "from %zd to %d\n", oldlen, len);
330 outbuf->start = talloc_realloc_size(NULL, outbuf->start, len);
334 static int filter_n_bytes(sh_audio_t *sh, struct bstr *outbuf, int len)
336 assert(len-1 + sh->audio_out_minsize <= sh->a_buffer_size);
338 int error = 0;
340 // Decode more bytes if needed
341 int old_samplerate = sh->samplerate;
342 int old_channels = sh->channels;
343 int old_sample_format = sh->sample_format;
344 while (sh->a_buffer_len < len) {
345 unsigned char *buf = sh->a_buffer + sh->a_buffer_len;
346 int minlen = len - sh->a_buffer_len;
347 int maxlen = sh->a_buffer_size - sh->a_buffer_len;
348 int ret = sh->ad_driver->decode_audio(sh, buf, minlen, maxlen);
349 int format_change = sh->samplerate != old_samplerate
350 || sh->channels != old_channels
351 || sh->sample_format != old_sample_format;
352 if (ret <= 0 || format_change) {
353 error = format_change ? -2 : -1;
354 // samples from format-changing call get discarded too
355 len = sh->a_buffer_len;
356 break;
358 sh->a_buffer_len += ret;
361 // Filter
362 af_data_t filter_input = {
363 .audio = sh->a_buffer,
364 .len = len,
365 .rate = sh->samplerate,
366 .nch = sh->channels,
367 .format = sh->sample_format
369 af_fix_parameters(&filter_input);
370 af_data_t *filter_output = af_play(sh->afilter, &filter_input);
371 if (!filter_output)
372 return -1;
373 set_min_out_buffer_size(outbuf, outbuf->len + filter_output->len);
374 memcpy(outbuf->start + outbuf->len, filter_output->audio,
375 filter_output->len);
376 outbuf->len += filter_output->len;
378 // remove processed data from decoder buffer:
379 sh->a_buffer_len -= len;
380 memmove(sh->a_buffer, sh->a_buffer + len, sh->a_buffer_len);
382 return error;
385 /* Try to get at least minlen decoded+filtered bytes in outbuf
386 * (total length including possible existing data).
387 * Return 0 on success, -1 on error/EOF (not distinguished).
388 * In the former case outbuf->len is always >= minlen on return.
389 * In case of EOF/error it might or might not be.
390 * Outbuf.start must be talloc-allocated, and will be reallocated
391 * if needed to fit all filter output. */
392 int decode_audio(sh_audio_t *sh_audio, struct bstr *outbuf, int minlen)
394 // Indicates that a filter seems to be buffering large amounts of data
395 int huge_filter_buffer = 0;
396 // Decoded audio must be cut at boundaries of this many bytes
397 int unitsize = sh_audio->channels * sh_audio->samplesize * 16;
399 /* Filter output size will be about filter_multiplier times input size.
400 * If some filter buffers audio in big blocks this might only hold
401 * as average over time. */
402 double filter_multiplier = af_calc_filter_multiplier(sh_audio->afilter);
404 /* If the decoder set audio_out_minsize then it can do the equivalent of
405 * "while (output_len < target_len) output_len += audio_out_minsize;",
406 * so we must guarantee there is at least audio_out_minsize-1 bytes
407 * more space in the output buffer than the minimum length we try to
408 * decode. */
409 int max_decode_len = sh_audio->a_buffer_size - sh_audio->audio_out_minsize;
410 max_decode_len -= max_decode_len % unitsize;
412 while (outbuf->len < minlen) {
413 int declen = (minlen - outbuf->len) / filter_multiplier
414 + (unitsize << 5); // some extra for possible filter buffering
415 if (huge_filter_buffer)
416 /* Some filter must be doing significant buffering if the estimated
417 * input length didn't produce enough output from filters.
418 * Feed the filters 2k bytes at a time until we have enough output.
419 * Very small amounts could make filtering inefficient while large
420 * amounts can make MPlayer demux the file unnecessarily far ahead
421 * to get audio data and buffer video frames in memory while doing
422 * so. However the performance impact of either is probably not too
423 * significant as long as the value is not completely insane. */
424 declen = 2000;
425 declen -= declen % unitsize;
426 if (declen > max_decode_len)
427 declen = max_decode_len;
428 else
429 /* if this iteration does not fill buffer, we must have lots
430 * of buffering in filters */
431 huge_filter_buffer = 1;
432 int res = filter_n_bytes(sh_audio, outbuf, declen);
433 if (res < 0)
434 return res;
436 return 0;
439 void decode_audio_prepend_bytes(struct bstr *outbuf, int count, int byte)
441 set_min_out_buffer_size(outbuf, outbuf->len + count);
442 memmove(outbuf->start + count, outbuf->start, outbuf->len);
443 memset(outbuf->start, byte, count);
444 outbuf->len += count;
448 void resync_audio_stream(sh_audio_t *sh_audio)
450 sh_audio->a_in_buffer_len = 0; // clear audio input buffer
451 sh_audio->pts = MP_NOPTS_VALUE;
452 if (!sh_audio->initialized)
453 return;
454 sh_audio->ad_driver->control(sh_audio, ADCTRL_RESYNC_STREAM, NULL);
457 void skip_audio_frame(sh_audio_t *sh_audio)
459 if (!sh_audio->initialized)
460 return;
461 if (sh_audio->ad_driver->control(sh_audio, ADCTRL_SKIP_FRAME, NULL) ==
462 CONTROL_TRUE)
463 return;
464 // default skip code:
465 ds_fill_buffer(sh_audio->ds); // skip block