1 /*
2  *  mpg123.c
3  *
4  *  Copyright (C) Thomas Oestreich - June 2001
5  *  Copyright (c) 1999 Albert L Faber
6  *
7  *  This file is part of transcode, a video stream processing tool
8  *
9  *  transcode is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2, or (at your option)
12  *  any later version.
13  *
14  *  transcode is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with GNU Make; see the file COPYING.  If not, write to
21  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22  *
23  */
24 
25 #include "transcode.h"
26 #include "tcinfo.h"
27 
28 #include "ioaux.h"
29 #include "magic.h"
30 #include "tc.h"
31 #include "libtc/libtc.h"
32 
33 #ifdef HAVE_LAME
34 #include "mpg123.h"
35 
36 #define         MAX_U_32_NUM            0xFFFFFFFF
37 
38 #define MAX_BUF 4096
39 static char sbuffer[MAX_BUF];
40 
fskip(FILE * fp,long offset,int whence)41 static int fskip(FILE * fp, long offset, int whence)
42 {
43 #ifndef PIPE_BUF
44     char    buffer[4096];
45 #else
46     char    buffer[PIPE_BUF];
47 #endif
48     int     read;
49 
50     if (0 == fseek(fp, offset, whence))
51         return 0;
52 
53     if (whence != SEEK_CUR || offset < 0) {
54         tc_log_warn(__FILE__,
55 		    "fskip problem: Mostly the return status of functions is not evaluate so it is more secure to polute <stderr>.");
56         return -1;
57     }
58 
59     while (offset > 0) {
60         read = offset > sizeof(buffer) ? sizeof(buffer) : offset;
61         if ((read = fread(buffer, 1, read, fp)) <= 0)
62             return -1;
63         offset -= read;
64     }
65 
66     return 0;
67 }
68 
check_aid(const unsigned char * header)69 static int check_aid(const unsigned char *header)
70 {
71     return 0 == strncmp(header, "AiD\1", 4);
72 }
73 
74 /*
75  * Please check this and don't kill me if there's a bug
76  * This is a (nearly?) complete header analysis for a MPEG-1/2/2.5 Layer I, II or III
77  * data stream
78  */
79 
is_syncword_mp123(const void * const headerptr)80 static int is_syncword_mp123(const void *const headerptr)
81 {
82     const unsigned char *const p = headerptr;
83     static const char abl2[16] =
84         { 0, 7, 7, 7, 0, 7, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8 };
85 
86     if ((p[0] & 0xFF) != 0xFF)
87         return 0;       // first 8 bits must be '1'
88     if ((p[1] & 0xE0) != 0xE0)
89         return 0;       // next 3 bits are also
90     if ((p[1] & 0x18) == 0x08)
91         return 0;       // no MPEG-1, -2 or -2.5
92     if ((p[1] & 0x06) == 0x00)
93         return 0;       // no Layer I, II and III
94     if ((p[2] & 0xF0) == 0xF0)
95         return 0;       // bad bitrate
96     if ((p[2] & 0x0C) == 0x0C)
97         return 0;       // no sample frequency with (32,44.1,48)/(1,2,4)
98     if ((p[1] & 0x06) == 0x04) // illegal Layer II bitrate/Channel Mode comb
99         if (abl2[p[2] >> 4] & (1 << (p[3] >> 6)))
100             return 0;
101     return 1;
102 }
103 
is_syncword_mp3(const void * const headerptr)104 static int is_syncword_mp3(const void *const headerptr)
105 {
106     const unsigned char *const p = headerptr;
107 
108     if ((p[0] & 0xFF) != 0xFF)
109         return 0;       // first 8 bits must be '1'
110     if ((p[1] & 0xE0) != 0xE0)
111         return 0;       // next 3 bits are also
112     if ((p[1] & 0x18) == 0x08)
113         return 0;       // no MPEG-1, -2 or -2.5
114     if ((p[1] & 0x06) != 0x02)
115         return 0;       // no Layer III (can be merged with 'next 3 bits are also' test, but don't do this, this decreases readability)
116     if ((p[2] & 0xF0) == 0xF0)
117         return 0;       // bad bitrate
118     if ((p[2] & 0x0C) == 0x0C)
119         return 0;       // no sample frequency with (32,44.1,48)/(1,2,4)
120     return 1;
121 }
122 
123 
lame_decode_initfile(FILE * fd,mp3data_struct * mp3data,int format)124 int lame_decode_initfile(FILE * fd, mp3data_struct * mp3data, int format)
125 {
126     //  VBRTAGDATA pTagData;
127     // int xing_header,len2,num_frames;
128 #define bufsize 100
129     unsigned char buf[bufsize];
130     int     ret;
131     int     len, aid_header;
132     short int pcm_l[1152], pcm_r[1152];
133 
134     memset(mp3data, 0, sizeof(mp3data_struct));
135     memset(buf, 0, bufsize);
136 
137     lame_decode_init();
138     if (!format) format = 0x55;
139 
140     len = 4;
141     if (fread(buf, 1, len, fd) != len)
142         return -1;      /* failed */
143     aid_header = check_aid(buf);
144     if (aid_header) {
145         if (fread(buf, 2, 1, fd) != 1)
146             return -1;  /* failed */
147         aid_header = (unsigned char) buf[0] + 256 * (unsigned char) buf[1];
148         tc_log_msg(__FILE__, "Album ID found.  length=%i", aid_header);
149         /* skip rest of AID, except for 6 bytes we have already read */
150         fskip(fd, aid_header - 6, SEEK_CUR);
151 
152         /* read 4 more bytes to set up buffer for MP3 header check */
153         len = fread(buf, 1, 4, fd);
154     }
155 
156     /* look for valid 4 byte MPEG header  */
157     if (len < 4)
158         return -1;
159 
160     if (format == 0x55) {
161 	while ( !is_syncword_mp3(buf)) {
162 	    int     i;
163 	    for (i = 0; i < len - 1; i++)
164 		buf[i] = buf[i + 1];
165 	    if (fread(buf + len - 1, 1, 1, fd) != 1)
166 		return -1;  /* failed */
167 	}
168     } else if (format == 0x50) {
169 	while ( !is_syncword_mp123(buf)) {
170 	    int     i;
171 	    for (i = 0; i < len - 1; i++)
172 		buf[i] = buf[i + 1];
173 	    if (fread(buf + len - 1, 1, 1, fd) != 1)
174 		return -1;  /* failed */
175 	}
176     }
177 
178     // now parse the current buffer looking for MP3 headers.
179     // (as of 11/00: mpglib modified so that for the first frame where
180     // headers are parsed, no data will be decoded.
181     // However, for freeformat, we need to decode an entire frame,
182     // so mp3data->bitrate will be 0 until we have decoded the first
183     // frame.  Cannot decode first frame here because we are not
184     // yet prepared to handle the output.
185 
186     ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
187     if (-1 == ret)
188         return -1;
189 
190     /* repeat until we decode a valid mp3 header.  */
191     while (!mp3data->header_parsed) {
192         len = fread(buf, 1, sizeof(buf), fd);
193         if (len != sizeof(buf))
194             return -1;
195         ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
196         if (-1 == ret)
197             return -1;
198     }
199 
200     if (mp3data->bitrate==0) {
201 	tc_log_msg(__FILE__,"Input file is freeformat.");
202     }
203 
204     if (mp3data->totalframes > 0) {
205         /* mpglib found a Xing VBR header and computed nsamp & totalframes */
206     }
207     else {
208 	/* set as unknown.  Later, we will take a guess based on file size
209 	 * ant bitrate */
210         mp3data->nsamp = MAX_U_32_NUM;
211     }
212 
213     return 0;
214 }
215 
216 /*
217 For lame_decode_fromfile:  return code
218   -1     error
219    n     number of samples output.  either 576 or 1152 depending on MP3 file.
220 
221 
222 For lame_decode1_headers():  return code
223   -1     error
224    0     ok, but need more data before outputing any samples
225    n     number of samples output.  either 576 or 1152 depending on MP3 file.
226 */
227 
lame_decode_fromfile(FILE * fd,short pcm_l[],short pcm_r[],mp3data_struct * mp3data)228 int lame_decode_fromfile(FILE * fd, short pcm_l[], short pcm_r[],
229 			 mp3data_struct * mp3data)
230 {
231     int     ret = 0, len=0;
232     unsigned char buf[1024];
233 
234     /* first see if we still have data buffered in the decoder: */
235     ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
236     if (ret!=0) return ret;
237 
238 
239     /* read until we get a valid output frame */
240     while (1) {
241         len = fread(buf, 1, 1024, fd);
242         if (len == 0) {
243 	    /* we are done reading the file, but check for buffered data */
244 	    ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
245 	    if (ret<=0) return -1;  // done with file
246 	    break;
247 	}
248 
249         ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
250         if (ret == -1) return -1;
251 	if (ret >0) break;
252     }
253     return ret;
254 }
255 
256 static int verbose_flag;
257 
buf_probe_mp3(unsigned char * _buf,int len,ProbeTrackInfo * pcm)258 int buf_probe_mp3(unsigned char *_buf, int len, ProbeTrackInfo *pcm)
259 {
260 
261   //  VBRTAGDATA pTagData;
262   // int xing_header,len2,num_frames;
263 
264   char *buf;
265   mp3data_struct *mp3data;
266   int     i, ret;
267   int format=0;
268   short int pcm_l[1152], pcm_r[1152];
269 
270   int type;
271 
272   if((mp3data = tc_zalloc(sizeof(mp3data_struct)))==NULL) {
273     tc_log_error(__FILE__, "out of memory");
274     exit(1);
275   }
276 
277   lame_decode_init();
278 
279   buf=_buf;
280 
281   for (i = 0; i < len - 1; i++) {
282     if(is_syncword_mp123(buf)) {
283 	// catch false positives
284 	switch(buf[1] & 0xff) {
285 	    case 0xFD: case 0xFC: format = CODEC_MP2; break;
286 	    case 0xFB:            format = CODEC_MP3; break;
287 	}
288 	if (format) break;
289     }
290     ++buf;
291   }
292 
293   type = buf[1] & 0xff;
294 
295   ret = lame_decode1_headers(buf, len, pcm_l, pcm_r, mp3data);
296 
297   if (-1 == ret) {
298     //tc_log_error(__FILE__, "failed to probe mp3 header (%d)", len);
299     return -1;
300   }
301 
302   //copy infos:
303 
304   pcm->samplerate = mp3data->samplerate;
305   pcm->chan = mp3data->stereo;
306   pcm->bits = 16;
307   pcm->format = CODEC_MP3;
308   pcm->bitrate = mp3data->bitrate;
309 
310   if(verbose_flag & TC_DEBUG)
311     tc_log_msg(__FILE__, "channels=%d, samplerate=%d Hz, bitrate=%d kbps, (fsize=%d)", mp3data->stereo, mp3data->samplerate, mp3data->bitrate, mp3data->framesize);
312 
313   switch(type) {
314 
315   case 0xFD:
316   case 0xFC:
317     pcm->format = CODEC_MP2;
318     break;
319   case 0xFB:
320     pcm->format = CODEC_MP3;
321     break;
322   }
323   return 0;
324 }
325 
probe_mp3(info_t * ipipe)326 void probe_mp3(info_t *ipipe)
327 {
328     ssize_t ret=0;
329 
330     // need to find syncframe:
331 
332     if((ret = tc_pread(ipipe->fd_in, sbuffer, MAX_BUF)) != MAX_BUF) {
333 	if (!ret) {
334 	    ipipe->error=1;
335 	    return;
336 	}
337     }
338 
339     verbose_flag = ipipe->verbose;
340 
341     //for single MP3 stream only
342     if(buf_probe_mp3(sbuffer, ret, &ipipe->probe_info->track[0])<0) {
343 	ipipe->error=1;
344 	return;
345     }
346 
347     switch(ipipe->probe_info->track[0].format) {
348 
349     case CODEC_MP2:
350       ipipe->probe_info->magic = TC_MAGIC_MP2;
351       break;
352     case CODEC_MP3:
353       ipipe->probe_info->magic = TC_MAGIC_MP3;
354       break;
355     }
356 
357     ++ipipe->probe_info->num_tracks;
358 
359     return;
360 }
361 
362 #else  // HAVE_LAME
363 
probe_mp3(info_t * ipipe)364 void probe_mp3(info_t *ipipe) {
365 
366     tc_log_error(__FILE__, "no lame support available");
367     return;
368 
369 }
370 
371 #endif
372