xref: /third_party/lame/mpglib/interface.c (revision 159b3361)
1/*
2 * interface.c
3 *
4 * Copyright (C) 1999-2012 The L.A.M.E. project
5 *
6 * Initially written by Michael Hipp, see also AUTHORS and README.
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
17 *
18 * You should have received a copy of the GNU Library General Public
19 * License along with this library; if not, write to the
20 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 * Boston, MA 02111-1307, USA.
22 */
23/* $Id$ */
24
25#ifdef HAVE_CONFIG_H
26# include <config.h>
27#endif
28
29#include <stdlib.h>
30#include <stdio.h>
31
32#include "common.h"
33#include "interface.h"
34#include "tabinit.h"
35#include "layer3.h"
36#include "lame.h"
37#include "machine.h"
38#include "VbrTag.h"
39#include "decode_i386.h"
40
41#include "layer1.h"
42#include "layer2.h"
43
44#ifdef WITH_DMALLOC
45#include <dmalloc.h>
46#endif
47
48extern void lame_report_def(const char* format, va_list args);
49
50/* #define HIP_DEBUG */
51
52int
53InitMP3(PMPSTR mp)
54{
55    hip_init_tables_layer1();
56    hip_init_tables_layer2();
57    hip_init_tables_layer3();
58
59    if (mp) {
60        memset(mp, 0, sizeof(MPSTR));
61
62        mp->framesize = 0;
63        mp->num_frames = 0;
64        mp->enc_delay = -1;
65        mp->enc_padding = -1;
66        mp->vbr_header = 0;
67        mp->header_parsed = 0;
68        mp->side_parsed = 0;
69        mp->data_parsed = 0;
70        mp->free_format = 0;
71        mp->old_free_format = 0;
72        mp->ssize = 0;
73        mp->dsize = 0;
74        mp->fsizeold = -1;
75        mp->bsize = 0;
76        mp->head = mp->tail = NULL;
77        mp->fr.single = -1;
78        mp->bsnum = 0;
79        mp->wordpointer = mp->bsspace[mp->bsnum] + 512;
80        mp->bitindex = 0;
81        mp->synth_bo = 1;
82        mp->sync_bitstream = 1;
83
84        mp->report_dbg = &lame_report_def;
85        mp->report_err = &lame_report_def;
86        mp->report_msg = &lame_report_def;
87    }
88    make_decode_tables(32767);
89
90    return 1;
91}
92
93void
94ExitMP3(PMPSTR mp)
95{
96    if (mp) {
97        struct buf *b, *bn;
98
99        b = mp->tail;
100        while (b) {
101            free(b->pnt);
102            bn = b->next;
103            free(b);
104            b = bn;
105        }
106    }
107}
108
109static struct buf *
110addbuf(PMPSTR mp, unsigned char *buf, int size)
111{
112    struct buf *nbuf;
113
114    nbuf = (struct buf *) malloc(sizeof(struct buf));
115    if (!nbuf) {
116        lame_report_fnc(mp->report_err, "hip: addbuf() Out of memory!\n");
117        return NULL;
118    }
119    nbuf->pnt = (unsigned char *) malloc((size_t) size);
120    if (!nbuf->pnt) {
121        free(nbuf);
122        return NULL;
123    }
124    nbuf->size = size;
125    memcpy(nbuf->pnt, buf, (size_t) size);
126    nbuf->next = NULL;
127    nbuf->prev = mp->head;
128    nbuf->pos = 0;
129
130    if (!mp->tail) {
131        mp->tail = nbuf;
132    }
133    else {
134        mp->head->next = nbuf;
135    }
136
137    mp->head = nbuf;
138    mp->bsize += size;
139
140    return nbuf;
141}
142
143void
144remove_buf(PMPSTR mp)
145{
146    struct buf *buf = mp->tail;
147
148    mp->tail = buf->next;
149    if (mp->tail)
150        mp->tail->prev = NULL;
151    else {
152        mp->tail = mp->head = NULL;
153    }
154
155    free(buf->pnt);
156    free(buf);
157
158}
159
160static int
161read_buf_byte(PMPSTR mp)
162{
163    unsigned int b;
164
165    int     pos;
166
167
168    pos = mp->tail->pos;
169    while (pos >= mp->tail->size) {
170        remove_buf(mp);
171        if (!mp->tail) {
172            lame_report_fnc(mp->report_err, "hip: Fatal error! tried to read past mp buffer\n");
173            exit(1);
174        }
175        pos = mp->tail->pos;
176    }
177
178    b = mp->tail->pnt[pos];
179    mp->bsize--;
180    mp->tail->pos++;
181
182
183    return b;
184}
185
186
187
188static void
189read_head(PMPSTR mp)
190{
191    unsigned long head;
192
193    head = read_buf_byte(mp);
194    head <<= 8;
195    head |= read_buf_byte(mp);
196    head <<= 8;
197    head |= read_buf_byte(mp);
198    head <<= 8;
199    head |= read_buf_byte(mp);
200
201    mp->header = head;
202}
203
204
205
206
207static void
208copy_mp(PMPSTR mp, int size, unsigned char *ptr)
209{
210    int     len = 0;
211
212    while (len < size && mp->tail) {
213        int     nlen;
214        int     blen = mp->tail->size - mp->tail->pos;
215        if ((size - len) <= blen) {
216            nlen = size - len;
217        }
218        else {
219            nlen = blen;
220        }
221        memcpy(ptr + len, mp->tail->pnt + mp->tail->pos, (size_t) nlen);
222        len += nlen;
223        mp->tail->pos += nlen;
224        mp->bsize -= nlen;
225        if (mp->tail->pos == mp->tail->size) {
226            remove_buf(mp);
227        }
228    }
229}
230
231/* number of bytes needed by GetVbrTag to parse header */
232#define XING_HEADER_SIZE 194
233
234/*
235traverse mp data structure without changing it
236(just like sync_buffer)
237pull out Xing bytes
238call vbr header check code from LAME
239if we find a header, parse it and also compute the VBR header size
240if no header, do nothing.
241
242bytes = number of bytes before MPEG header.  skip this many bytes
243before starting to read
244return value: number of bytes in VBR header, including syncword
245*/
246static int
247check_vbr_header(PMPSTR mp, int bytes)
248{
249    int     i, pos;
250    struct buf *buf = mp->tail;
251    unsigned char xing[XING_HEADER_SIZE];
252    VBRTAGDATA pTagData;
253
254    pos = buf->pos;
255    /* skip to valid header */
256    for (i = 0; i < bytes; ++i) {
257        while (pos >= buf->size) {
258            buf = buf->next;
259            if (!buf)
260                return -1; /* fatal error */
261            pos = buf->pos;
262        }
263        ++pos;
264    }
265    /* now read header */
266    for (i = 0; i < XING_HEADER_SIZE; ++i) {
267        while (pos >= buf->size) {
268            buf = buf->next;
269            if (!buf)
270                return -1; /* fatal error */
271            pos = buf->pos;
272        }
273        xing[i] = buf->pnt[pos];
274        ++pos;
275    }
276
277    /* check first bytes for Xing header */
278    mp->vbr_header = GetVbrTag(&pTagData, xing);
279    if (mp->vbr_header) {
280        mp->num_frames = pTagData.frames;
281        mp->enc_delay = pTagData.enc_delay;
282        mp->enc_padding = pTagData.enc_padding;
283
284        /* lame_report_fnc(mp->report_msg,"hip: delays: %i %i \n",mp->enc_delay,mp->enc_padding); */
285        /* lame_report_fnc(mp->report_msg,"hip: Xing VBR header dectected.  MP3 file has %i frames\n", pTagData.frames); */
286        if (pTagData.headersize < 1)
287            return 1;
288        return pTagData.headersize;
289    }
290    return 0;
291}
292
293
294
295
296
297static int
298sync_buffer(PMPSTR mp, int free_match)
299{
300    /* traverse mp structure without modifying pointers, looking
301     * for a frame valid header.
302     * if free_format, valid header must also have the same
303     * samplerate.
304     * return number of bytes in mp, before the header
305     * return -1 if header is not found
306     */
307    unsigned int b[4] = { 0, 0, 0, 0 };
308    int     i, h, pos;
309    struct buf *buf = mp->tail;
310    if (!buf)
311        return -1;
312
313    pos = buf->pos;
314    for (i = 0; i < mp->bsize; i++) {
315        /* get 4 bytes */
316
317        b[0] = b[1];
318        b[1] = b[2];
319        b[2] = b[3];
320        while (pos >= buf->size) {
321            buf = buf->next;
322            if (!buf) {
323                return -1;
324                /* not enough data to read 4 bytes */
325            }
326            pos = buf->pos;
327        }
328        b[3] = buf->pnt[pos];
329        ++pos;
330
331        if (i >= 3) {
332            struct frame *fr = &mp->fr;
333            unsigned long head;
334
335            head = b[0];
336            head <<= 8;
337            head |= b[1];
338            head <<= 8;
339            head |= b[2];
340            head <<= 8;
341            head |= b[3];
342            h = head_check(head, fr->lay);
343
344            if (h && free_match) {
345                /* just to be even more thorough, match the sample rate */
346                int     mode, stereo, sampling_frequency, mpeg25, lsf;
347
348                if (head & (1 << 20)) {
349                    lsf = (head & (1 << 19)) ? 0x0 : 0x1;
350                    mpeg25 = 0;
351                }
352                else {
353                    lsf = 1;
354                    mpeg25 = 1;
355                }
356
357                mode = ((head >> 6) & 0x3);
358                stereo = (mode == MPG_MD_MONO) ? 1 : 2;
359
360                if (mpeg25)
361                    sampling_frequency = 6 + ((head >> 10) & 0x3);
362                else
363                    sampling_frequency = ((head >> 10) & 0x3) + (lsf * 3);
364                h = ((stereo == fr->stereo) && (lsf == fr->lsf) && (mpeg25 == fr->mpeg25) &&
365                     (sampling_frequency == fr->sampling_frequency));
366            }
367
368            if (h) {
369                return i - 3;
370            }
371        }
372    }
373    return -1;
374}
375
376
377void
378decode_reset(PMPSTR mp)
379{
380#if 0
381    remove_buf(mp);
382    /* start looking for next frame */
383    /* mp->fsizeold = mp->framesize; */
384    mp->fsizeold = -1;
385    mp->old_free_format = mp->free_format;
386    mp->framesize = 0;
387    mp->header_parsed = 0;
388    mp->side_parsed = 0;
389    mp->data_parsed = 0;
390    mp->sync_bitstream = 1; /* TODO check if this is right */
391#else
392    InitMP3(mp);        /* Less error prone to just to reinitialise. */
393#endif
394}
395
396int
397audiodata_precedesframes(PMPSTR mp)
398{
399    if (mp->fr.lay == 3)
400        return layer3_audiodata_precedesframes(mp);
401    else
402        return 0;       /* For Layer 1 & 2 the audio data starts at the frame that describes it, so no audio data precedes. */
403}
404
405static int
406decodeMP3_clipchoice(PMPSTR mp, unsigned char *in, int isize, char *out, int *done,
407                     int (*synth_1to1_mono_ptr) (PMPSTR, real *, unsigned char *, int *),
408                     int (*synth_1to1_ptr) (PMPSTR, real *, int, unsigned char *, int *))
409{
410    int     i, iret, bits, bytes;
411
412    if (in && isize && addbuf(mp, in, isize) == NULL)
413        return MP3_ERR;
414
415    /* First decode header */
416    if (!mp->header_parsed) {
417
418        if (mp->fsizeold == -1 || mp->sync_bitstream) {
419            int     vbrbytes;
420            mp->sync_bitstream = 0;
421
422            /* This is the very first call.   sync with anything */
423            /* bytes= number of bytes before header */
424            bytes = sync_buffer(mp, 0);
425
426            /* now look for Xing VBR header */
427            if (mp->bsize >= bytes + XING_HEADER_SIZE) {
428                /* vbrbytes = number of bytes in entire vbr header */
429                vbrbytes = check_vbr_header(mp, bytes);
430            }
431            else {
432                /* not enough data to look for Xing header */
433#ifdef HIP_DEBUG
434                lame_report_fnc(mp->report_dbg, "hip: not enough data to look for Xing header\n");
435#endif
436                return MP3_NEED_MORE;
437            }
438
439            if (mp->vbr_header) {
440                /* do we have enough data to parse entire Xing header? */
441                if (bytes + vbrbytes > mp->bsize) {
442                    /* lame_report_fnc(mp->report_err,"hip: not enough data to parse entire Xing header\n"); */
443                    return MP3_NEED_MORE;
444                }
445
446                /* read in Xing header.  Buffer data in case it
447                 * is used by a non zero main_data_begin for the next
448                 * frame, but otherwise dont decode Xing header */
449#ifdef HIP_DEBUG
450                lame_report_fnc(mp->report_dbg, "hip: found xing header, skipping %i bytes\n", vbrbytes + bytes);
451#endif
452                for (i = 0; i < vbrbytes + bytes; ++i)
453                    read_buf_byte(mp);
454                /* now we need to find another syncword */
455                /* just return and make user send in more data */
456
457                return MP3_NEED_MORE;
458            }
459        }
460        else {
461            /* match channels, samplerate, etc, when syncing */
462            bytes = sync_buffer(mp, 1);
463        }
464
465        /* buffer now synchronized */
466        if (bytes < 0) {
467            /* lame_report_fnc(mp->report_err,"hip: need more bytes %d\n", bytes); */
468            return MP3_NEED_MORE;
469        }
470        if (bytes > 0) {
471            /* there were some extra bytes in front of header.
472             * bitstream problem, but we are now resynced
473             * should try to buffer previous data in case new
474             * frame has nonzero main_data_begin, but we need
475             * to make sure we do not overflow buffer
476             */
477            int     size;
478            if (mp->fsizeold != -1) {
479                lame_report_fnc(mp->report_err, "hip: bitstream problem, resyncing skipping %d bytes...\n", bytes);
480            }
481            mp->old_free_format = 0;
482#if 1
483            /* FIXME: correct ??? */
484            mp->sync_bitstream = 1;
485#endif
486            /* skip some bytes, buffer the rest */
487            size = (int) (mp->wordpointer - (mp->bsspace[mp->bsnum] + 512));
488
489            if (size > MAXFRAMESIZE) {
490                /* wordpointer buffer is trashed.  probably cant recover, but try anyway */
491                lame_report_fnc(mp->report_err, "hip: wordpointer trashed.  size=%i (%i)  bytes=%i \n",
492                        size, MAXFRAMESIZE, bytes);
493                size = 0;
494                mp->wordpointer = mp->bsspace[mp->bsnum] + 512;
495            }
496
497            /* buffer contains 'size' data right now
498               we want to add 'bytes' worth of data, but do not
499               exceed MAXFRAMESIZE, so we through away 'i' bytes */
500            i = (size + bytes) - MAXFRAMESIZE;
501            for (; i > 0; --i) {
502                --bytes;
503                read_buf_byte(mp);
504            }
505
506            copy_mp(mp, bytes, mp->wordpointer);
507            mp->fsizeold += bytes;
508        }
509
510        read_head(mp);
511        if (!decode_header(mp, &mp->fr, mp->header))
512            return MP3_ERR;
513        mp->header_parsed = 1;
514        mp->framesize = mp->fr.framesize;
515        mp->free_format = (mp->framesize == 0);
516
517        if (mp->fr.lsf)
518            mp->ssize = (mp->fr.stereo == 1) ? 9 : 17;
519        else
520            mp->ssize = (mp->fr.stereo == 1) ? 17 : 32;
521        if (mp->fr.error_protection)
522            mp->ssize += 2;
523
524        mp->bsnum = 1 - mp->bsnum; /* toggle buffer */
525        mp->wordpointer = mp->bsspace[mp->bsnum] + 512;
526        mp->bitindex = 0;
527
528        /* for very first header, never parse rest of data */
529        if (mp->fsizeold == -1) {
530#ifdef HIP_DEBUG
531            lame_report_fnc(mp->report_dbg, "hip: not parsing the rest of the data of the first header\n");
532#endif
533            return MP3_NEED_MORE;
534        }
535    }                   /* end of header parsing block */
536
537    /* now decode side information */
538    if (!mp->side_parsed) {
539
540        /* Layer 3 only */
541        if (mp->fr.lay == 3) {
542            if (mp->bsize < mp->ssize)
543                return MP3_NEED_MORE;
544
545            copy_mp(mp, mp->ssize, mp->wordpointer);
546
547            if (mp->fr.error_protection)
548                getbits(mp, 16);
549            bits = decode_layer3_sideinfo(mp);
550            /* bits = actual number of bits needed to parse this frame */
551            /* can be negative, if all bits needed are in the reservoir */
552            if (bits < 0)
553                bits = 0;
554
555            /* read just as many bytes as necessary before decoding */
556            mp->dsize = (bits + 7) / 8;
557
558            if (!mp->free_format) {
559                /* do not read more than framsize data */
560                int framesize = mp->fr.framesize - mp->ssize;
561                if (mp->dsize > framesize) {
562                    lame_report_fnc(mp->report_err,
563                            "hip: error audio data exceeds framesize by %d bytes\n",
564                            mp->dsize - framesize);
565                    mp->dsize = framesize;
566                }
567            }
568#ifdef HIP_DEBUG
569            lame_report_fnc(mp->report_dbg,
570                    "hip: %d bits needed to parse layer III frame, number of bytes to read before decoding dsize = %d\n",
571                    bits, mp->dsize);
572#endif
573
574            /* this will force mpglib to read entire frame before decoding */
575            /* mp->dsize= mp->framesize - mp->ssize; */
576
577        }
578        else {
579            /* Layers 1 and 2 */
580
581            /* check if there is enough input data */
582            if (mp->fr.framesize > mp->bsize)
583                return MP3_NEED_MORE;
584
585            /* takes care that the right amount of data is copied into wordpointer */
586            mp->dsize = mp->fr.framesize;
587            mp->ssize = 0;
588        }
589
590        mp->side_parsed = 1;
591    }
592
593    /* now decode main data */
594    iret = MP3_NEED_MORE;
595    if (!mp->data_parsed) {
596        if (mp->dsize > mp->bsize) {
597            return MP3_NEED_MORE;
598        }
599
600        copy_mp(mp, mp->dsize, mp->wordpointer);
601
602        *done = 0;
603
604        /*do_layer3(&mp->fr,(unsigned char *) out,done); */
605        switch (mp->fr.lay) {
606        case 1:
607            if (mp->fr.error_protection)
608                getbits(mp, 16);
609
610            if (decode_layer1_frame(mp, (unsigned char *) out, done) < 0)
611                return MP3_ERR;
612            break;
613
614        case 2:
615            if (mp->fr.error_protection)
616                getbits(mp, 16);
617
618            decode_layer2_frame(mp, (unsigned char *) out, done);
619            break;
620
621        case 3:
622            decode_layer3_frame(mp, (unsigned char *) out, done, synth_1to1_mono_ptr, synth_1to1_ptr);
623            break;
624        default:
625            lame_report_fnc(mp->report_err, "hip: invalid layer %d\n", mp->fr.lay);
626        }
627
628        mp->wordpointer = mp->bsspace[mp->bsnum] + 512 + mp->ssize + mp->dsize;
629
630        mp->data_parsed = 1;
631        iret = MP3_OK;
632    }
633
634
635    /* remaining bits are ancillary data, or reservoir for next frame
636     * If free format, scan stream looking for next frame to determine
637     * mp->framesize */
638    if (mp->free_format) {
639        if (mp->old_free_format) {
640            /* free format.  bitrate must not vary */
641            mp->framesize = mp->fsizeold_nopadding + (mp->fr.padding);
642        }
643        else {
644            bytes = sync_buffer(mp, 1);
645            if (bytes < 0)
646                return iret;
647            mp->framesize = bytes + mp->ssize + mp->dsize;
648            mp->fsizeold_nopadding = mp->framesize - mp->fr.padding;
649#if 0
650               lame_report_fnc(mp->report_dbg,"hip: freeformat bitstream:  estimated bitrate=%ikbs  \n",
651               8*(4+mp->framesize)*freqs[mp->fr.sampling_frequency]/
652               (1000*576*(2-mp->fr.lsf)));
653#endif
654        }
655    }
656
657    /* buffer the ancillary data and reservoir for next frame */
658    bytes = mp->framesize - (mp->ssize + mp->dsize);
659    if (bytes > mp->bsize) {
660        return iret;
661    }
662
663    if (bytes > 0) {
664        int     size;
665#if 1
666        /* FIXME: while loop OK ??? */
667        while (bytes > 512) {
668            read_buf_byte(mp);
669            bytes--;
670            mp->framesize--;
671        }
672#endif
673        copy_mp(mp, bytes, mp->wordpointer);
674        mp->wordpointer += bytes;
675
676        size = (int) (mp->wordpointer - (mp->bsspace[mp->bsnum] + 512));
677        if (size > MAXFRAMESIZE) {
678            lame_report_fnc(mp->report_err, "hip: fatal error.  MAXFRAMESIZE not large enough.\n");
679        }
680
681    }
682
683    /* the above frame is completely parsed.  start looking for next frame */
684    mp->fsizeold = mp->framesize;
685    mp->old_free_format = mp->free_format;
686    mp->framesize = 0;
687    mp->header_parsed = 0;
688    mp->side_parsed = 0;
689    mp->data_parsed = 0;
690
691    return iret;
692}
693
694int
695decodeMP3(PMPSTR mp, unsigned char *in, int isize, char *out, int osize, int *done)
696{
697    if (osize < 4608) {
698        lame_report_fnc(mp->report_err, "hip: Insufficient memory for decoding buffer %d\n", osize);
699        return MP3_ERR;
700    }
701
702    /* passing pointers to the functions which clip the samples */
703    return decodeMP3_clipchoice(mp, in, isize, out, done, synth_1to1_mono, synth_1to1);
704}
705
706int
707decodeMP3_unclipped(PMPSTR mp, unsigned char *in, int isize, char *out, int osize, int *done)
708{
709    /* we forbid input with more than 1152 samples per channel for output in unclipped mode */
710    if (osize < (int) (1152 * 2 * sizeof(real))) {
711        lame_report_fnc(mp->report_err, "hip: out space too small for unclipped mode\n");
712        return MP3_ERR;
713    }
714
715    /* passing pointers to the functions which don't clip the samples */
716    return decodeMP3_clipchoice(mp, in, isize, out, done, synth_1to1_mono_unclipped,
717                                synth_1to1_unclipped);
718}
719