Ticket #2149: ad_mpg123.c

File ad_mpg123.c, 18.0 KB (added by thomas-forum@…, 13 years ago)

preliminary libmpcodecs/ad_mpg123.c (tested with MPlayer-1.1.1)

Line 
1/*
2 * MPEG 1.0/2.0/2.5 audio layer I, II, III decoding with libmpg123
3 *
4 * Copyright (C) 2010-2013 Thomas Orgis <thomas@orgis.org>
5 *
6 * MPlayer is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * MPlayer 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
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with MPlayer; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21#include <stdio.h>
22#include <stdlib.h>
23#include <unistd.h>
24
25#include "config.h"
26#include "mp_msg.h"
27#include "ad_internal.h"
28#include "dec_audio.h"
29
30static const ad_info_t info = {
31 "MPEG 1.0/2.0/2.5 layers I, II, III",
32 "mpg123",
33 "Thomas Orgis",
34 "mpg123.org",
35 "High-performance decoder using libmpg123."
36};
37
38LIBAD_EXTERN(mpg123)
39
40#include "libvo/fastmemcpy.h"
41
42/* Reducing the ifdeffery to two main variants:
43 * 1. most compatible to any libmpg123 version
44 * 2. fastest variant with recent libmpg123 (>=1.14)
45 * Running variant 2 on older libmpg123 versions may work in
46 * principle, but is not supported.
47 * So, please leave the check for MPG123_API_VERSION there, m-kay?
48 */
49#include <mpg123.h>
50
51/* Enable faster mode of operation with newer libmpg123, avoiding
52 * unnecessary memcpy() calls. */
53#if (defined MPG123_API_VERSION) && (MPG123_API_VERSION >= 33)
54#define AD_MPG123_FRAMEWISE
55#endif
56
57/* Switch for updating bitrate info of VBR files. Not essential. */
58#define AD_MPG123_MEAN_BITRATE
59
60struct ad_mpg123_context {
61 mpg123_handle *handle;
62 char new_format;
63#ifdef AD_MPG123_MEAN_BITRATE
64 /* Running mean for bit rate, stream length estimation. */
65 float mean_rate;
66 unsigned int mean_count;
67 /* Time delay for updates. */
68 short delay;
69#endif
70 /* If the stream is actually VBR. */
71 char vbr;
72};
73
74/* This initializes libmpg123 and prepares the handle, including funky
75 * parameters. */
76static int preinit(sh_audio_t *sh)
77{
78 int err, flag;
79 struct ad_mpg123_context *con;
80 /* Assumption: You always call preinit + init + uninit, on every file.
81 * But you stop at preinit in case it fails.
82 * If that is not true, one must ensure not to call mpg123_init / exit
83 * twice in a row. */
84 if (mpg123_init() != MPG123_OK)
85 return 0;
86
87 sh->context = malloc(sizeof(struct ad_mpg123_context));
88 con = sh->context;
89 /* Auto-choice of optimized decoder (first argument NULL). */
90 con->handle = mpg123_new(NULL, &err);
91 if (!con->handle)
92 goto bad_end;
93
94#ifdef CONFIG_FAKE_MONO
95 /* Guessing here: Default value triggers forced upmix of mono to stereo. */
96 flag = fakemono == 0 ? MPG123_FORCE_STEREO :
97 fakemono == 1 ? MPG123_MONO_LEFT :
98 fakemono == 2 ? MPG123_MONO_RIGHT : 0;
99 if (mpg123_param(con->handle, MPG123_ADD_FLAGS, flag, 0.0) != MPG123_OK)
100 goto bad_end;
101#endif
102
103 /* Basic settings.
104 * Don't spill messages, enable better resync with non-seekable streams.
105 * Give both flags individually without error checking to keep going with
106 * old libmpg123. Generally, it is not fatal if the flags are not
107 * honored */
108 mpg123_param(con->handle, MPG123_ADD_FLAGS, MPG123_QUIET, 0.0);
109 /* Do not bail out on malformed streams at all.
110 * MPlayer does not handle a decoder throwing the towel on crappy input. */
111 mpg123_param(con->handle, MPG123_RESYNC_LIMIT, -1, 0.0);
112
113 /* Open decisions: Configure libmpg123 to force encoding (or stay open about
114 * library builds that support only float or int32 output), (de)configure
115 * gapless decoding (won't work with seeking in MPlayer, though).
116 * Don't forget to eventually enable ReplayGain/RVA support, too.
117 * Let's try to run with the default for now. */
118
119 /* That would produce floating point output.
120 * You can get 32 and 24 bit ints, even 8 bit via format matrix. */
121 /* mpg123_param(con->handle, MPG123_ADD_FLAGS, MPG123_FORCE_FLOAT, 0.); */
122
123 /* Example for RVA choice (available since libmpg123 1.0.0):
124 mpg123_param(con->handle, MPG123_RVA, MPG123_RVA_MIX, 0.0) */
125
126#ifdef AD_MPG123_FRAMEWISE
127 /* Prevent funky automatic resampling.
128 * This way, we can be sure that one frame will never produce
129 * more than 1152 stereo samples. */
130 mpg123_param(con->handle, MPG123_REMOVE_FLAGS, MPG123_AUTO_RESAMPLE, 0.);
131#else
132 /* Older mpg123 is vulnerable to concatenated streams when gapless cutting
133 * is enabled (will only play the jingle of a badly constructed radio
134 * stream). The versions using framewise decoding are fine with that. */
135 mpg123_param(con->handle, MPG123_REMOVE_FLAGS, MPG123_GAPLESS, 0.);
136#endif
137
138 return 1;
139
140 bad_end:
141 if (!con->handle)
142 mp_msg(MSGT_DECAUDIO, MSGL_ERR, "mpg123 preinit error: %s\n",
143 mpg123_plain_strerror(err));
144 else
145 mp_msg(MSGT_DECAUDIO, MSGL_ERR, "mpg123 preinit error: %s\n",
146 mpg123_strerror(con->handle));
147
148 if (con->handle)
149 mpg123_delete(con->handle);
150 mpg123_exit();
151 free(sh->context);
152 sh->context = NULL;
153 return 0;
154}
155
156/* Compute bitrate from frame size. */
157static int compute_bitrate(struct mpg123_frameinfo *i)
158{
159 static const int samples_per_frame[4][4] = {
160 {-1, 384, 1152, 1152}, /* MPEG 1 */
161 {-1, 384, 1152, 576}, /* MPEG 2 */
162 {-1, 384, 1152, 576}, /* MPEG 2.5 */
163 {-1, -1, -1, -1}, /* Unknown */
164 };
165 return (int) ((i->framesize + 4) * 8 * i->rate * 0.001 /
166 samples_per_frame[i->version][i->layer] + 0.5);
167}
168
169/* Opted against the header printout from old mp3lib, too much
170 * irrelevant info. This is modelled after the mpg123 app's
171 * standard output line.
172 * If more verbosity is demanded, one can add more detail and
173 * also throw in ID3v2 info which libmpg123 collects anyway. */
174static void print_header_compact(struct mpg123_frameinfo *i)
175{
176 static const char *smodes[5] = {
177 "stereo", "joint-stereo", "dual-channel", "mono", "invalid"
178 };
179 static const char *layers[4] = {
180 "Unknown", "I", "II", "III"
181 };
182 static const char *versions[4] = {
183 "1.0", "2.0", "2.5", "x.x"
184 };
185
186 mp_msg(MSGT_DECAUDIO, MSGL_V, "MPEG %s layer %s, ",
187 versions[i->version], layers[i->layer]);
188 switch (i->vbr) {
189 case MPG123_CBR:
190 if (i->bitrate)
191 mp_msg(MSGT_DECAUDIO, MSGL_V, "%d kbit/s", i->bitrate);
192 else
193 mp_msg(MSGT_DECAUDIO, MSGL_V, "%d kbit/s (free format)",
194 compute_bitrate(i));
195 break;
196 case MPG123_VBR:
197 mp_msg(MSGT_DECAUDIO, MSGL_V, "VBR");
198 break;
199 case MPG123_ABR:
200 mp_msg(MSGT_DECAUDIO, MSGL_V, "%d kbit/s ABR", i->abr_rate);
201 break;
202 default:
203 mp_msg(MSGT_DECAUDIO, MSGL_V, "???");
204 }
205 mp_msg(MSGT_DECAUDIO, MSGL_V, ", %ld Hz %s\n", i->rate,
206 smodes[i->mode]);
207}
208
209/* libmpg123 has a new format ready; query and store, return return value
210 of mpg123_getformat() */
211static int set_format(sh_audio_t *sh, struct ad_mpg123_context *con)
212{
213 int ret;
214 long rate;
215 int channels;
216 int encoding;
217 ret = mpg123_getformat(con->handle, &rate, &channels, &encoding);
218 if(ret == MPG123_OK) {
219 sh->channels = channels;
220 sh->samplerate = rate;
221 /* Without external force, mpg123 will always choose signed encoding,
222 * and non-16-bit only on builds that don't support it.
223 * Be reminded that it doesn't matter to the MPEG file what encoding
224 * is produced from it. */
225 switch (encoding) {
226 case MPG123_ENC_SIGNED_8:
227 sh->sample_format = AF_FORMAT_S8;
228 sh->samplesize = 1;
229 break;
230 case MPG123_ENC_SIGNED_16:
231 sh->sample_format = AF_FORMAT_S16_NE;
232 sh->samplesize = 2;
233 break;
234 /* To stay compatible with the oldest libmpg123 headers, do not rely
235 * on float and 32 bit encoding symbols being defined.
236 * Those formats came later */
237 case 0x1180: /* MPG123_ENC_SIGNED_32 */
238 sh->sample_format = AF_FORMAT_S32_NE;
239 sh->samplesize = 4;
240 break;
241 case 0x200: /* MPG123_ENC_FLOAT_32 */
242 sh->sample_format = AF_FORMAT_FLOAT_NE;
243 sh->samplesize = 4;
244 break;
245 default:
246 /* This means we got a funny custom build of libmpg123 that only supports an unknown format. */
247 mp_msg(MSGT_DECAUDIO, MSGL_ERR,
248 "Bad encoding from mpg123: %i.\n", encoding);
249 return MPG123_ERR;
250 }
251#ifdef AD_MPG123_FRAMEWISE
252 /* Going to decode directly to MPlayer's memory. It is important
253 * to have MPG123_AUTO_RESAMPLE disabled for the buffer size
254 * being an all-time limit. */
255 sh->audio_out_minsize = 1152 * 2 * sh->samplesize;
256#endif
257 con->new_format = 0;
258 }
259 return ret;
260}
261
262/* This tries to extract a requested amount of decoded data.
263 * Even when you request 0 bytes, it will feed enough input so that
264 * the decoder _could_ have delivered something.
265 * Returns byte count >= 0, -1 on error.
266 *
267 * Thoughts on exact pts keeping:
268 * We have to assume that MPEG frames are cut in pieces by packet boundaries.
269 * Also, it might be possible that the first packet does not contain enough
270 * data to ensure initial stream sync... or re-sync on erroneous streams.
271 * So we need something robust to relate the decoded byte count to the correct
272 * time stamp. This is tricky, though. From the outside, you cannot tell if,
273 * after having fed two packets until the first output arrives, one should
274 * start counting from the first packet's pts or the second packet's.
275 * So, let's just count from the last fed package's pts. If the packets are
276 * exactly cut to MPEG frames, this will cause one frame mismatch in the
277 * beginning (when mpg123 peeks ahead for the following header), but will
278 * be corrected with the third frame already. One might add special code to
279 * not increment the base pts past the first packet's after a resync before
280 * the first decoded bytes arrived. */
281static int decode_a_bit(sh_audio_t *sh, unsigned char *buf, int count)
282{
283 int ret = MPG123_OK;
284 int got = 0;
285 struct ad_mpg123_context *con = sh->context;
286
287 /* There will be one MPG123_NEW_FORMAT message on first open.
288 * This will be handled in init(). */
289 do {
290 size_t got_now = 0;
291 /* Fetch new format now, after old data has been used. */
292 if(con->new_format)
293 ret = set_format(sh, con);
294
295 /* Feed the decoder. This will only fire from the second round on. */
296 if (ret == MPG123_NEED_MORE) {
297 int incount;
298 double pts;
299 unsigned char *inbuf;
300 /* Feed more input data. */
301 incount = ds_get_packet_pts(sh->ds, &inbuf, &pts);
302 if (incount <= 0)
303 break; /* Apparently that's it. EOF. */
304
305 /* Next bytes from that presentation time. */
306 if (pts != MP_NOPTS_VALUE) {
307 sh->pts = pts;
308 sh->pts_bytes = 0;
309 }
310
311#ifdef AD_MPG123_FRAMEWISE
312 /* Have to use mpg123_feed() to avoid decoding here. */
313 ret = mpg123_feed(con->handle, inbuf, incount);
314#else
315 /* Do not use mpg123_feed(), added in later libmpg123 versions. */
316 ret = mpg123_decode(con->handle, inbuf, incount, NULL, 0, NULL);
317#endif
318 if (ret == MPG123_ERR)
319 break;
320
321 /* Indication of format change is possible here (from mpg123_decode()). */
322 if(ret == MPG123_NEW_FORMAT) {
323 con->new_format = 1;
324 if(got)
325 break; /* Do not switch format during a chunk. */
326
327 ret = set_format(sh, con);
328 }
329 }
330 /* Theoretically, mpg123 could return MPG123_DONE, so be prepared.
331 * Should not happen in our usage, but it is a valid return code. */
332 else if (ret == MPG123_ERR || ret == MPG123_DONE)
333 break;
334
335 /* Try to decode a bit. This is the return value that counts
336 * for the loop condition. */
337#ifdef AD_MPG123_FRAMEWISE
338 if (!buf) { /* fake call just for feeding to get format */
339 ret = set_format(sh, con);
340 } else { /* This is the decoding. One frame at a time. */
341 ret = mpg123_replace_buffer(con->handle, buf, count);
342 if (ret == MPG123_OK)
343 ret = mpg123_decode_frame(con->handle, NULL, NULL, &got_now);
344 }
345#else
346 ret = mpg123_decode(con->handle, NULL, 0, buf + got, count - got,
347 &got_now);
348#endif
349
350 got += got_now;
351 sh->pts_bytes += got_now;
352
353 /* Indication of format change should happen here. */
354 if(ret == MPG123_NEW_FORMAT) {
355 con->new_format = 1;
356 if(got)
357 break; /* Do not switch format during a chunk. */
358
359 ret = set_format(sh, con);
360 }
361
362#ifdef AD_MPG123_FRAMEWISE
363 } while (ret == MPG123_NEED_MORE || (got == 0 && count != 0));
364#else
365 } while (ret == MPG123_NEED_MORE || got < count);
366#endif
367
368 if (ret == MPG123_ERR) {
369 mp_msg(MSGT_DECAUDIO, MSGL_ERR, "mpg123 decoding failed: %s\n",
370 mpg123_strerror(con->handle));
371 }
372
373 return got;
374}
375
376/* Close, reopen stream. Feed data until we know the format of the stream.
377 * 1 on success, 0 on error */
378static int reopen_stream(sh_audio_t *sh)
379{
380 struct ad_mpg123_context *con = (struct ad_mpg123_context*) sh->context;
381
382 mpg123_close(con->handle);
383 /* No resetting of the context:
384 * We do not want to loose the mean bitrate data. */
385
386 /* Open and make sure we have fed enough data to get stream properties. */
387 if (MPG123_OK == mpg123_open_feed(con->handle) &&
388 /* Feed data until mpg123 is ready (has found stream beginning). */
389 !decode_a_bit(sh, NULL, 0) &&
390 set_format(sh, con) == MPG123_OK) { /* format setting again just for return value */
391 return 1;
392 } else {
393 mp_msg(MSGT_DECAUDIO, MSGL_ERR,
394 "mpg123 failed to reopen stream: %s\n",
395 mpg123_strerror(con->handle));
396 return 0;
397 }
398}
399
400/* Now we really start accessing some data and determining file format.
401 * Paranoia note: The mpg123_close() on errors is not really necessary,
402 * But it ensures that we don't accidentally continue decoding with a
403 * bad state (possibly interpreting the format badly or whatnot). */
404static int init(sh_audio_t *sh)
405{
406 mpg123_id3v2 *v2;
407 struct mpg123_frameinfo finfo;
408 struct ad_mpg123_context *con = sh->context;
409
410 con->new_format = 0;
411 if (reopen_stream(sh) &&
412 /* Get MPEG header info. */
413 MPG123_OK == mpg123_info(con->handle, &finfo) &&
414 /* Since we queried format, mpg123 should have read past ID3v2 tags.
415 * We need to decide if printing of UTF-8 encoded text info is wanted. */
416 MPG123_OK == mpg123_id3(con->handle, NULL, &v2)) {
417 /* If we are here, we passed all hurdles. Yay! Extract the info. */
418 print_header_compact(&finfo);
419 /* Do we want to print out the UTF-8 Id3v2 info?
420 if (v2)
421 print_id3v2(v2); */
422
423 /* Have kb/s, want B/s
424 * For VBR, the first frame will be a bad estimate. */
425 sh->i_bps = (finfo.bitrate ? finfo.bitrate : compute_bitrate(&finfo))
426 * 1000 / 8;
427#ifdef AD_MPG123_MEAN_BITRATE
428 con->delay = 1;
429 con->mean_rate = 0.;
430 con->mean_count = 0;
431#endif
432 con->vbr = (finfo.vbr != MPG123_CBR);
433
434 return 1;
435 } else {
436 mp_msg(MSGT_DECAUDIO, MSGL_ERR, "mpg123 init error: %s\n",
437 mpg123_strerror(con->handle));
438 return 0;
439 }
440}
441
442static void uninit(sh_audio_t *sh)
443{
444 struct ad_mpg123_context *con = (struct ad_mpg123_context*) sh->context;
445
446 mpg123_close(con->handle);
447 mpg123_delete(con->handle);
448 free(sh->context);
449 sh->context = NULL;
450 mpg123_exit();
451}
452
453#ifdef AD_MPG123_MEAN_BITRATE
454/* Update mean bitrate. This could be dropped if accurate time display
455 * on audio file playback is not desired. */
456static void update_info(sh_audio_t *sh)
457{
458 struct ad_mpg123_context *con = sh->context;
459 if (con->vbr && --con->delay < 1) {
460 struct mpg123_frameinfo finfo;
461 if (MPG123_OK == mpg123_info(con->handle, &finfo)) {
462 if (++con->mean_count > ((unsigned int) -1) / 2)
463 con->mean_count = ((unsigned int) -1) / 4;
464
465 /* Might not be numerically optimal, but works fine enough. */
466 con->mean_rate = ((con->mean_count - 1) * con->mean_rate +
467 finfo.bitrate) / con->mean_count;
468 sh->i_bps = (int) (con->mean_rate * 1000 / 8);
469
470 con->delay = 10;
471 }
472 }
473}
474#endif
475
476static int decode_audio(sh_audio_t *sh, unsigned char *buf, int minlen,
477 int maxlen)
478{
479 int bytes;
480
481 bytes = decode_a_bit(sh, buf, maxlen);
482 if (bytes == 0)
483 return -1; /* EOF */
484
485#ifdef AD_MPG123_MEAN_BITRATE
486 update_info(sh);
487#endif
488 return bytes;
489}
490
491static int control(sh_audio_t *sh, int cmd, void *arg, ...)
492{
493 switch (cmd) {
494 case ADCTRL_RESYNC_STREAM:
495 /* Close/reopen the stream for mpg123 to make sure it doesn't
496 * think that it still knows the exact stream position.
497 * Otherwise, we would have funny effects from the gapless code.
498 * Oh, and it helps to minimize artifacts from jumping in the stream. */
499 if (reopen_stream(sh)) {
500#ifdef AD_MPG123_MEAN_BITRATE
501 update_info(sh);
502#endif
503 return CONTROL_TRUE;
504 } else {
505 /* MPlayer ignores this case! It just keeps on decoding.
506 * So we have to make sure resync never fails ... */
507 mp_msg(MSGT_DECAUDIO, MSGL_ERR,
508 "mpg123 cannot reopen stream for resync.\n");
509 return CONTROL_FALSE;
510 }
511 break;
512 }
513 return CONTROL_UNKNOWN;
514}