1 /***************************************************************************
2  *  Based on mq3 and madplay projects                                      *
3  *                                                                         *
4  * Copyright (c) 2000-2001 Brad Hughes <bhughes@trolltech.com>             *
5  * Copyright (C) 2000-2004 Robert Leslie <rob@mars.org>                    *
6  * Copyright (C) 2009-2020 Ilya Kotov forkotov02@ya.ru                     *
7  *                                                                         *
8  *   This program is free software; you can redistribute it and/or modify  *
9  *   it under the terms of the GNU General Public License as published by  *
10  *   the Free Software Foundation; either version 2 of the License, or     *
11  *   (at your option) any later version.                                   *
12  *                                                                         *
13  *   This program 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         *
16  *   GNU General Public License for more details.                          *
17  *                                                                         *
18  *   You should have received a copy of the GNU General Public License     *
19  *   along with this program; if not, write to the                         *
20  *   Free Software Foundation, Inc.,                                       *
21  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
22  ***************************************************************************/
23 
24 #include <taglib/id3v2header.h>
25 #include <taglib/tbytevector.h>
26 #include <math.h>
27 #include <stdio.h>
28 #include "tagextractor.h"
29 #include "decoder_mad.h"
30 
31 #define XING_MAGIC (('X' << 24) | ('i' << 16) | ('n' << 8) | 'g')
32 #define XING_MAGIC2 (('I' << 24) | ('n' << 16) | ('f' << 8) | 'o')
33 #define LAME_MAGIC (('L' << 24) | ('A' << 16) | ('M' << 8) | 'E')
34 #define INPUT_BUFFER_SIZE (32*1024)
35 
DecoderMAD(bool crc,QIODevice * i)36 DecoderMAD::DecoderMAD(bool crc, QIODevice *i) : Decoder(i), m_crc(crc)
37 {}
38 
~DecoderMAD()39 DecoderMAD::~DecoderMAD()
40 {
41     deinit();
42     if (m_input_buf)
43     {
44         qDebug("DecoderMAD: deleting input_buf");
45         delete [] m_input_buf;
46         m_input_buf = nullptr;
47     }
48 }
49 
initialize()50 bool DecoderMAD::initialize()
51 {
52     m_inited = false;
53     m_totalTime = 0;
54     m_channels = 0;
55     m_bitrate = 0;
56     m_freq = 0;
57     m_len = 0;
58     m_input_bytes = 0;
59 
60     if (!input())
61     {
62         qWarning("DecoderMAD: cannot initialize.  No input.");
63         return false;
64     }
65 
66     if (!m_input_buf)
67         m_input_buf = new char[INPUT_BUFFER_SIZE];
68 
69     if (input()->isSequential ()) //for streams only
70     {
71         TagExtractor extractor(input());
72         if(!extractor.id3v2tag().isEmpty())
73             addMetaData(extractor.id3v2tag());
74     }
75 
76     mad_stream_init(&m_stream);
77     if(!m_crc)
78         mad_stream_options(&m_stream, MAD_OPTION_IGNORECRC);
79     mad_frame_init(&m_frame);
80     mad_synth_init(&m_synth);
81 
82     if (!findHeader())
83     {
84         qDebug("DecoderMAD: Can't find a valid MPEG header.");
85         return false;
86     }
87     mad_stream_buffer(&m_stream, (unsigned char *) m_input_buf, m_input_bytes);
88     m_stream.error = MAD_ERROR_BUFLEN;
89     mad_frame_mute (&m_frame);
90     m_stream.next_frame = nullptr;
91     m_stream.sync = 0;
92     ChannelMap map;
93     if(m_channels == 1)
94         map << Qmmp::CHAN_FRONT_LEFT;
95     else
96         map << Qmmp::CHAN_FRONT_LEFT << Qmmp::CHAN_FRONT_RIGHT;
97     configure(m_freq, map, Qmmp::PCM_FLOAT);
98     m_inited = true;
99     return true;
100 }
101 
deinit()102 void DecoderMAD::deinit()
103 {
104     if (!m_inited)
105         return;
106 
107     mad_synth_finish(&m_synth);
108     mad_frame_finish(&m_frame);
109     mad_stream_finish(&m_stream);
110 
111     m_inited = false;
112     m_totalTime = 0;
113     m_channels = 0;
114     m_bitrate = 0;
115     m_freq = 0;
116     m_len = 0;
117     m_input_bytes = 0;
118     m_skip_frames = 0;
119     m_eof = false;
120     if(m_xing.lame)
121     {
122         delete m_xing.lame;
123         m_xing.lame = nullptr;
124     }
125 }
126 
findXingHeader(struct mad_bitptr ptr,unsigned int bitlen)127 bool DecoderMAD::findXingHeader(struct mad_bitptr ptr, unsigned int bitlen)
128 {
129     if (bitlen < 64)
130         return false;
131 
132     struct mad_bitptr start = ptr;
133     quint32 xing_magic = mad_bit_read(&ptr, 32);
134     bitlen -= 32;
135 
136     if(xing_magic != XING_MAGIC && xing_magic != XING_MAGIC2)
137     {
138         /*
139          * Due to an unfortunate historical accident, a Xing VBR tag may be
140          * misplaced in a stream with CRC protection. We check for this by
141          * assuming the tag began two octets prior and the high bits of the
142          * following flags field are always zero.
143          */
144 
145         if(xing_magic != ((quint64(XING_MAGIC) << 16) & 0xffffffffL) && xing_magic != ((quint64(XING_MAGIC2) << 16) & 0xffffffffL))
146             return false;
147 
148         ptr = start;
149         mad_bit_skip(&ptr, 16);
150         bitlen += 16;
151     }
152 
153     m_xing.flags = mad_bit_read(&ptr, 32);
154     bitlen -= 32;
155 
156     if (m_xing.flags & XING_FRAMES)
157     {
158         if (bitlen < 32)
159             return false;
160 
161         m_xing.frames = mad_bit_read(&ptr, 32);
162         bitlen -= 32;
163 
164         if(!m_xing.frames)
165         {
166             qDebug("DecoderMAD: invalid xing header (zero number of frames)");
167             return false;
168         }
169     }
170 
171     if (m_xing.flags & XING_BYTES)
172     {
173         if (bitlen < 32)
174             return false;
175 
176         m_xing.bytes = mad_bit_read(&ptr, 32);
177         bitlen -= 32;
178 
179         if(!m_xing.bytes)
180         {
181             qDebug("DecoderMAD: invalid xing header (zero number of bytes)");
182             return false;
183         }
184     }
185 
186     if (m_xing.flags & XING_TOC)
187     {
188         if (bitlen < 800)
189            return false;
190 
191         for (int i = 0; i < 100; ++i)
192             m_xing.toc[i] = mad_bit_read(&ptr, 8);
193 
194         bitlen -= 800;
195     }
196 
197     if (m_xing.flags & XING_SCALE)
198     {
199         if (bitlen < 32)
200             return false;
201 
202         m_xing.scale = mad_bit_read(&ptr, 32);
203         bitlen -= 32;
204     }
205 
206     m_xing.lame = findLameHeader(ptr, bitlen);
207     return true;
208 }
209 
findLameHeader(mad_bitptr ptr,unsigned int bitlen)210 DecoderMAD::LameHeader* DecoderMAD::findLameHeader(mad_bitptr ptr, unsigned int bitlen)
211 {
212     if(bitlen < 272)
213         return nullptr;
214 
215     if(mad_bit_read (&ptr, 32) != LAME_MAGIC)
216         return nullptr;
217 
218     LameHeader header;
219     mad_bit_skip (&ptr, 40); //version
220 
221     header.revision = mad_bit_read (&ptr, 4);
222     if (header.revision == 15)
223         return nullptr;
224 
225     mad_bit_skip(&ptr, 12); //VBR,Lowpass filter value
226     header.peak = mad_bit_read(&ptr, 32) << 5; //Peak amplitude
227     mad_bit_skip(&ptr, 32); //Replay Gain
228     mad_bit_skip(&ptr, 16); //Encoding flags, ATH Type, bitrate
229     header.start_delay = mad_bit_read (&ptr, 12); //Start delay
230     header.end_padding = mad_bit_read (&ptr, 12); //End padding
231     mad_bit_skip (&ptr, 8); //Misc
232     header.gain = mad_bit_read (&ptr, 8); //MP3 Gain
233     mad_bit_skip (&ptr, 64); //Preset and surroud info, MusicLength, Music CRC
234     return new LameHeader(header);
235 }
236 
findHeader()237 bool DecoderMAD::findHeader()
238 {
239     bool result = false;
240     int count = 0;
241     bool has_xing = false;
242     bool is_vbr = false;
243     mad_timer_t duration = mad_timer_zero;
244     struct mad_header header;
245     mad_header_init (&header);
246     uint id3v2Size = 0;
247 
248     forever
249     {
250         m_input_bytes = 0;
251         if (m_stream.error == MAD_ERROR_BUFLEN || !m_stream.buffer)
252         {
253             size_t remaining = 0;
254 
255             if (m_stream.next_frame)
256             {
257                 remaining = m_stream.bufend - m_stream.next_frame;
258                 memmove (m_input_buf, m_stream.next_frame, remaining);
259             }
260 
261             m_input_bytes = input()->read(m_input_buf + remaining, INPUT_BUFFER_SIZE - remaining);
262 
263             if (m_input_bytes <= 0)
264                 break;
265 
266             mad_stream_buffer(&m_stream, (unsigned char *) m_input_buf + remaining, m_input_bytes);
267             m_stream.error = MAD_ERROR_NONE;
268         }
269 
270         if (mad_header_decode(&header, &m_stream) < 0)
271         {
272             if(m_stream.error == MAD_ERROR_LOSTSYNC)
273             {
274                 uint tagSize = findID3v2((uchar *)m_stream.this_frame,
275                                          (ulong) (m_stream.bufend - m_stream.this_frame));
276                 if (tagSize > 0)
277                 {
278                     mad_stream_skip(&m_stream, tagSize);
279                     id3v2Size = tagSize;
280                 }
281                 continue;
282             }
283             else if (m_stream.error == MAD_ERROR_BUFLEN || MAD_RECOVERABLE(m_stream.error))
284                 continue;
285             else
286             {
287                 qDebug ("DecoderMAD: Can't decode header: %s", mad_stream_errorstr(&m_stream));
288                 break;
289             }
290         }
291         result = true;
292 
293         if (input()->isSequential())
294             break;
295 
296         count ++;
297         //try to detect xing header
298         if (count == 1)
299         {
300             m_frame.header = header;
301             if (mad_frame_decode(&m_frame, &m_stream) != -1 &&
302                     findXingHeader(m_stream.anc_ptr, m_stream.anc_bitlen))
303             {
304                 is_vbr = true;
305 
306                 qDebug("DecoderMAD: Xing header found");
307 
308                 if (m_xing.flags & XING_FRAMES)
309                 {
310                     has_xing = true;
311                     count = m_xing.frames;
312 
313                     if(m_xing.lame)
314                     {
315                         qDebug("DecoderMAD: LAME header found");
316                         m_skip_bytes = m_xing.lame->start_delay * sizeof(float) * MAD_NCHANNELS(&header);
317                         m_play_bytes = (m_xing.frames * 1152 - m_xing.lame->start_delay - m_xing.lame->end_padding) *
318                                 sizeof(float) * MAD_NCHANNELS(&header);
319                         qDebug("DecoderMAD: samples to skip: %d, padding: %d",
320                                m_xing.lame->start_delay, m_xing.lame->end_padding);
321                     }
322                     break;
323                 }
324             }
325         }
326         //try to detect VBR
327         if (!is_vbr && !(count > 15))
328         {
329             if (m_bitrate && header.bitrate != m_bitrate)
330             {
331                 qDebug ("DecoderMAD: VBR detected");
332                 is_vbr = true;
333             }
334             else
335                 m_bitrate = header.bitrate;
336         }
337         else if (!is_vbr)
338         {
339             qDebug ("DecoderMAD: Fixed rate detected");
340             break;
341         }
342         mad_timer_add (&duration, header.duration);
343     }
344 
345     if (!result)
346         return false;
347 
348     if (!is_vbr && !input()->isSequential())
349     {
350         double time = ((input()->size() - id3v2Size) * 8.0) / (header.bitrate);
351         double timefrac = (double)time - ((long)(time));
352         mad_timer_set(&duration, (long)time, (long)(timefrac*100), 100);
353     }
354     else if (has_xing)
355     {
356         mad_timer_multiply (&header.duration, count);
357         duration = header.duration;
358     }
359 
360     m_totalTime = mad_timer_count(duration, MAD_UNITS_MILLISECONDS);
361     qDebug ("DecoderMAD: Total time: %ld", long(m_totalTime));
362     m_freq = header.samplerate;
363     m_channels = MAD_NCHANNELS(&header);
364     m_bitrate = header.bitrate / 1000;
365 
366     if((header.flags & MAD_FLAG_LSF_EXT) && (header.flags & MAD_FLAG_MPEG_2_5_EXT))
367         setProperty(Qmmp::FORMAT_NAME, QString("MPEG-2.5 layer %1").arg(header.layer));
368     else if(header.flags & MAD_FLAG_LSF_EXT)
369         setProperty(Qmmp::FORMAT_NAME, QString("MPEG-2 layer %1").arg(header.layer));
370     else
371         setProperty(Qmmp::FORMAT_NAME, QString("MPEG-1 layer %1").arg(header.layer));
372 
373     mad_header_finish(&header);
374     input()->seek(0);
375     m_input_bytes = 0;
376     return true;
377 }
378 
totalTime() const379 qint64 DecoderMAD::totalTime() const
380 {
381     if (!m_inited)
382         return 0;
383     return m_totalTime;
384 }
385 
bitrate() const386 int DecoderMAD::bitrate() const
387 {
388     return int(m_bitrate);
389 }
390 
read(unsigned char * data,qint64 size)391 qint64 DecoderMAD::read(unsigned char *data, qint64 size)
392 {
393     while(m_skip_bytes > 0)
394     {
395         if(!decodeFrame())
396             return 0;
397 
398         qint64 l = madOutputFloat((float*)data, size / sizeof(float)) * sizeof(float);
399 
400         if(m_skip_bytes > l)
401         {
402             m_skip_bytes -= l;
403             continue;
404         }
405         else if(m_skip_bytes < l)
406         {
407             l -= m_skip_bytes;
408             memmove(data, data + m_skip_bytes, l);
409             m_skip_bytes = 0;
410             m_play_bytes -= l;
411             return l;
412         }
413         else
414         {
415             m_skip_bytes = 0;
416             break;
417         }
418     }
419 
420     if(!decodeFrame())
421         return 0;
422 
423     qint64 l = madOutputFloat((float*)data, size / sizeof(float)) * sizeof(float);
424 
425     if(m_play_bytes > 0)
426     {
427         if(m_play_bytes > l)
428             m_play_bytes -= l;
429         else
430         {
431             l -= m_play_bytes;
432             m_play_bytes = 0;
433         }
434 
435     }
436     return l;
437 }
438 
seek(qint64 pos)439 void DecoderMAD::seek(qint64 pos)
440 {
441     if(m_totalTime > 0)
442     {
443         qint64 seek_pos = qint64(pos * input()->size() / m_totalTime);
444         input()->seek(seek_pos);
445         mad_frame_mute(&m_frame);
446         mad_synth_mute(&m_synth);
447         m_stream.error = MAD_ERROR_BUFLEN;
448         m_stream.sync = 0;
449         m_input_bytes = 0;
450         m_stream.next_frame = nullptr;
451         m_skip_frames = 2;
452         m_skip_bytes = 0;
453         m_play_bytes = -1;
454     }
455 }
456 
fillBuffer()457 bool DecoderMAD::fillBuffer()
458 {
459     if (m_stream.next_frame)
460     {
461         m_input_bytes = &m_input_buf[m_input_bytes] - (char *) m_stream.next_frame;
462         memmove(m_input_buf, m_stream.next_frame, m_input_bytes);
463     }
464     int len = input()->read((char *) m_input_buf + m_input_bytes, INPUT_BUFFER_SIZE - m_input_bytes);
465     if (!len)
466     {
467         qDebug("DecoderMAD: end of file");
468         return false;
469     }
470     else if(len < 0)
471     {
472         qWarning("DecoderMAD: error");
473         return false;
474     }
475     m_input_bytes += len;
476     mad_stream_buffer(&m_stream, (unsigned char *) m_input_buf, m_input_bytes);
477     return true;
478 }
479 
findID3v2(uchar * data,ulong size)480 uint DecoderMAD::findID3v2(uchar *data, ulong size) //retuns ID3v2 tag size
481 {
482     if (size < 10)
483         return 0;
484 
485     if (((data[0] == 'I' && data[1] == 'D' && data[2] == '3') || //ID3v2 tag
486          (data[0] == '3' && data[1] == 'D' && data[2] == 'I')) && //ID3v2 footer
487             data[3] < 0xff && data[4] < 0xff && data[6] < 0x80 &&
488             data[7] < 0x80 && data[8] < 0x80 && data[9] < 0x80)
489     {
490         TagLib::ByteVector byteVector((char *)data, size);
491         TagLib::ID3v2::Header header(byteVector);
492         return header.tagSize();
493     }
494     return 0;
495 }
496 
decodeFrame()497 bool DecoderMAD::decodeFrame()
498 {
499     forever
500     {
501         if(((m_stream.error == MAD_ERROR_BUFLEN) || !m_stream.buffer) && !m_eof)
502         {
503             m_eof = !fillBuffer();
504         }
505         if(mad_frame_decode(&m_frame, &m_stream) < 0)
506         {
507             switch((int) m_stream.error)
508             {
509             case MAD_ERROR_LOSTSYNC:
510             {
511                 //skip ID3v2 tag
512                 uint tagSize = findID3v2((uchar *)m_stream.this_frame,
513                                          (ulong) (m_stream.bufend - m_stream.this_frame));
514                 if (tagSize > 0)
515                 {
516                     mad_stream_skip(&m_stream, tagSize);
517                     qDebug("DecoderMAD: %d bytes skipped", tagSize);
518                 }
519                 continue;
520             }
521             case MAD_ERROR_BUFLEN:
522                 if(m_eof)
523                     return false;
524                 continue;
525             case MAD_ERROR_BADCRC:
526                 qDebug("DecoderMAD: CRC check error");
527                 continue;
528             default:
529                 if (!MAD_RECOVERABLE(m_stream.error))
530                     return false;
531                 else
532                     continue;
533             }
534         }
535         if(m_skip_frames)
536         {
537             m_skip_frames--;
538             continue;
539         }
540         mad_synth_frame(&m_synth, &m_frame);
541         break;
542     }
543     return true;
544 }
545 
madOutputFloat(float * data,qint64 samples)546 qint64 DecoderMAD::madOutputFloat(float *data, qint64 samples)
547 {
548     float *data_it = data;
549     unsigned int samples_per_channel, channels;
550     mad_fixed_t const *left, *right;
551 
552     samples_per_channel = m_synth.pcm.length;
553     channels = m_synth.pcm.channels;
554     left = m_synth.pcm.samples[0];
555     right = m_synth.pcm.samples[1];
556     m_bitrate = m_frame.header.bitrate / 1000;
557     qint64 output_samples = 0;
558 
559     if(samples_per_channel * channels > samples)
560     {
561         qWarning("DecoderMad: input buffer is too small");
562         samples_per_channel = samples / channels;
563     }
564 
565     while (samples_per_channel--)
566     {
567         *data_it++ = mad_f_todouble(*left++);
568         output_samples++;
569         if (channels == 2)
570         {
571             *data_it++ = mad_f_todouble(*right++);
572             output_samples++;
573         }
574     }
575     return output_samples;
576 }
577