Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MpaSplitterFile.cpp « MpaSplitter « parser « filters « src - github.com/mpc-hc/mpc-hc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a05a880b35764360924a8d8dda6c60143b5df689 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/*
 * $Id$
 *
 * (C) 2003-2006 Gabest
 * (C) 2006-2012 see Authors.txt
 *
 * This file is part of MPC-HC.
 *
 * MPC-HC is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * MPC-HC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "stdafx.h"
#include <MMReg.h>
#include "MpaSplitterFile.h"

#ifdef REGISTER_FILTER
#include <InitGuid.h>
#endif
#include <moreuuids.h>

#define FRAMES_FLAG     0x0001
#define MPA_HEADER_SIZE 4   // MPEG-Audio Header Size

//

static const LPCTSTR s_genre[] = {
    _T("Blues"), _T("Classic Rock"), _T("Country"), _T("Dance"),
    _T("Disco"), _T("Funk"), _T("Grunge"), _T("Hip-Hop"),
    _T("Jazz"), _T("Metal"), _T("New Age"), _T("Oldies"),
    _T("Other"), _T("Pop"), _T("R&B"), _T("Rap"),
    _T("Reggae"), _T("Rock"), _T("Techno"), _T("Industrial"),
    _T("Alternative"), _T("Ska"), _T("Death Metal"), _T("Pranks"),
    _T("Soundtrack"), _T("Euro-Techno"), _T("Ambient"), _T("Trip-Hop"),
    _T("Vocal"), _T("Jazz+Funk"), _T("Fusion"), _T("Trance"),
    _T("Classical"), _T("Instrumental"), _T("Acid"), _T("House"),
    _T("Game"), _T("Sound Clip"), _T("Gospel"), _T("Noise"),
    _T("Alternative Rock"), _T("Bass"), _T("Soul"), _T("Punk"),
    _T("Space"), _T("Meditative"), _T("Instrumental Pop"), _T("Instrumental Rock"),
    _T("Ethnic"), _T("Gothic"), _T("Darkwave"), _T("Techno-Industrial"),
    _T("Electronic"), _T("Pop-Folk"), _T("Eurodance"), _T("Dream"),
    _T("Southern Rock"), _T("Comedy"), _T("Cult"), _T("Gangsta"),
    _T("Top 40"), _T("Christian Rap"), _T("Pop/Funk"), _T("Jungle"),
    _T("Native US"), _T("Cabaret"), _T("New Wave"), _T("Psychadelic"),
    _T("Rave"), _T("Showtunes"), _T("Trailer"), _T("Lo-Fi"),
    _T("Tribal"), _T("Acid Punk"), _T("Acid Jazz"), _T("Polka"),
    _T("Retro"), _T("Musical"), _T("Rock & Roll"), _T("Hard Rock"),
    _T("Folk"), _T("Folk-Rock"), _T("National Folk"), _T("Swing"),
    _T("Fast Fusion"), _T("Bebob"), _T("Latin"), _T("Revival"),
    _T("Celtic"), _T("Bluegrass"), _T("Avantgarde"), _T("Gothic Rock"),
    _T("Progressive Rock"), _T("Psychedelic Rock"), _T("Symphonic Rock"), _T("Slow Rock"),
    _T("Big Band"), _T("Chorus"), _T("Easy Listening"), _T("Acoustic"),
    _T("Humour"), _T("Speech"), _T("Chanson"), _T("Opera"),
    _T("Chamber Music"), _T("Sonata"), _T("Symphony"), _T("Booty Bass"),
    _T("Primus"), _T("Porn Groove"), _T("Satire"), _T("Slow Jam"),
    _T("Club"), _T("Tango"), _T("Samba"), _T("Folklore"),
    _T("Ballad"), _T("Power Ballad"), _T("Rhytmic Soul"), _T("Freestyle"),
    _T("Duet"), _T("Punk Rock"), _T("Drum Solo"), _T("Acapella"),
    _T("Euro-House"), _T("Dance Hall"), _T("Goa"), _T("Drum & Bass"),
    _T("Club-House"), _T("Hardcore"), _T("Terror"), _T("Indie"),
    _T("BritPop"), _T("Negerpunk"), _T("Polsk Punk"), _T("Beat"),
    _T("Christian Gangsta"), _T("Heavy Metal"), _T("Black Metal"),
    _T("Crossover"), _T("Contemporary C"), _T("Christian Rock"), _T("Merengue"), _T("Salsa"),
    _T("Thrash Metal"), _T("Anime"), _T("JPop"), _T("SynthPop"),
};

//

CMpaSplitterFile::CMpaSplitterFile(IAsyncReader* pAsyncReader, HRESULT& hr)
    : CBaseSplitterFileEx(pAsyncReader, hr, DEFAULT_CACHE_LENGTH, false)
    , m_mode(none)
    , m_rtDuration(0)
    , m_startpos(0)
    , m_endpos(0)
    , m_totalbps(0)
    , m_bIsVBR(false)
{
    if (SUCCEEDED(hr)) {
        hr = Init();
    }
}

HRESULT CMpaSplitterFile::Init()
{
    m_startpos = 0;
    m_endpos = GetLength();

    Seek(0);

    // some files can be determined as Mpeg Audio
    if ((BitRead(24, true) == 0x000001) || // ?
            (BitRead(32, true) == 'RIFF')   || // skip AVI and WAV files
            (BitRead(24, true) == 'AMV')) {    // skip MTV files (.amv .mtv)
        return E_FAIL;
    }

    if (m_endpos > 128 && IsRandomAccess()) {
        Seek(m_endpos - 128);

        if (BitRead(24) == 'TAG') {
            m_endpos -= 128;

            CStringA str;

            // title
            ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
            m_tags['TIT2'] = CStringW(str).Trim();

            // artist
            ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
            m_tags['TPE1'] = CStringW(str).Trim();

            // album
            ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
            m_tags['TALB'] = CStringW(str).Trim();

            // year
            ByteRead((BYTE*)str.GetBufferSetLength(4), 4);
            m_tags['TYER'] = CStringW(str).Trim();

            // comment
            ByteRead((BYTE*)str.GetBufferSetLength(30), 30);
            m_tags['COMM'] = CStringW(str).Trim();

            // track
            LPCSTR s = str;
            if (s[28] == 0 && s[29] != 0) {
                m_tags['TRCK'].Format(L"%d", s[29]);
            }

            // genre
            BYTE genre = (BYTE)BitRead(8);
            if (genre < _countof(s_genre)) {
                m_tags['TCON'] = CStringW(s_genre[genre]);
            }
        }
    }

    Seek(0);

    bool MP3_find = false;

    while (BitRead(24, true) == 'ID3') {
        MP3_find = true;

        BitRead(24);

        BYTE major = (BYTE)BitRead(8);
        BYTE revision = (BYTE)BitRead(8);
        UNREFERENCED_PARAMETER(revision);

        BYTE flags = (BYTE)BitRead(8);
        UNREFERENCED_PARAMETER(flags);
        DWORD size = 0;
        if (BitRead(1) != 0) {
            return E_FAIL;
        }
        size |= BitRead(7) << 21;
        if (BitRead(1) != 0) {
            return E_FAIL;
        }
        size |= BitRead(7) << 14;
        if (BitRead(1) != 0) {
            return E_FAIL;
        }
        size |= BitRead(7) << 7;
        if (BitRead(1) != 0) {
            return E_FAIL;
        }
        size |= BitRead(7);

        m_startpos = GetPos() + size;

        // TODO: read extended header

        if (major <= 4) {
            __int64 pos = GetPos();

            while (pos < m_startpos) {
                Seek(pos);

                DWORD tag = (DWORD)BitRead(32);
                DWORD size = 0;
                size |= BitRead(8) << 24;
                size |= BitRead(8) << 16;
                size |= BitRead(8) << 8;
                size |= BitRead(8);
                WORD flags = (WORD)BitRead(16);
                UNREFERENCED_PARAMETER(flags);

                pos += 4 + 4 + 2 + size;

                if (!size || pos >= m_startpos) {
                    break;
                }

                if (tag == 'TIT2'
                        || tag == 'TPE1'
                        || tag == 'TALB'
                        || tag == 'TYER'
                        || tag == 'COMM'
                        || tag == 'TRCK') {
                    BYTE encoding = (BYTE)BitRead(8);
                    size--;

                    WORD bom = (WORD)BitRead(16, true);

                    CStringA str;
                    CStringW wstr;

                    if (encoding > 0 && size >= 2 && bom == 0xfffe) {
                        BitRead(16);
                        size = (size - 2) / 2;
                        ByteRead((BYTE*)wstr.GetBufferSetLength(size), size * 2);
                        m_tags[tag] = wstr.Trim();
                    } else if (encoding > 0 && size >= 2 && bom == 0xfeff) {
                        BitRead(16);
                        size = (size - 2) / 2;
                        ByteRead((BYTE*)wstr.GetBufferSetLength(size), size * 2);
                        for (int i = 0, j = wstr.GetLength(); i < j; i++) {
                            wstr.SetAt(i, (wstr[i] << 8) | (wstr[i] >> 8));
                        }
                        m_tags[tag] = wstr.Trim();
                    } else {
                        ByteRead((BYTE*)str.GetBufferSetLength(size), size);
                        m_tags[tag] = (encoding > 0 ? UTF8To16(str) : CStringW(str)).Trim();
                    }
                }
            }
        }

        Seek(m_startpos);

        for (int i = 0; i < (1 << 20) && m_startpos < m_endpos && BitRead(8, true) == 0; i++) {
            BitRead(8), m_startpos++;
        }
    }

    int searchlen    = 0;
    __int64 startpos = 0;
    __int64 syncpos  = 0;

    __int64 startpos_mp3 = m_startpos;
    while (m_mode == none) {
        if (!MP3_find && GetPos() >= 2048) {
            break;
        }
        searchlen = (int)min(m_endpos - startpos_mp3, 512);
        Seek(startpos_mp3);

        // If we fail to see sync bytes, we reposition here and search again
        syncpos = startpos_mp3 + searchlen;

        // Check for a valid MPA header
        if (Read(m_mpahdr, searchlen, true, &m_mt)) {
            m_mode = mpa;

            syncpos = GetPos();
            startpos = syncpos - 4;

            // make sure the first frame is followed by another of the same kind (validates m_mpahdr basically)
            Seek(startpos + m_mpahdr.FrameSize);
            if (!Sync(4)) {
                m_mode = none;
            } else {
                break;
            }
        }

        // If we have enough room to search for a valid header, then skip ahead and try again
        if (m_endpos - syncpos >= 8) {
            startpos_mp3 = syncpos;
        } else {
            break;
        }
    }

    searchlen = (int)min(m_endpos - m_startpos, m_startpos > 0 ? 512 : 7);
    Seek(m_startpos);

    if (m_mode == none && Read(m_aachdr, searchlen, &m_mt)) {
        m_mode = mp4a;

        startpos = GetPos() - (m_aachdr.fcrc ? 7 : 9);

        // make sure the first frame is followed by another of the same kind (validates m_aachdr basically)
        Seek(startpos + m_aachdr.aac_frame_length);
        if (!Sync(9)) {
            m_mode = none;
        }
    }

    if (m_mode == none) {
        return E_FAIL;
    }

    m_startpos = startpos;

    if (m_mode == mpa) {
        DWORD m_dwFrames = 0;       // total number of frames
        Seek(m_startpos + MPA_HEADER_SIZE + 32);
        if (BitRead(32, true) == 'Xing' || BitRead(32, true) == 'Info') {
            BitRead(32); // Skip ID tag
            DWORD dwFlags = (DWORD)BitRead(32);
            // extract total number of frames in file
            if (dwFlags & FRAMES_FLAG) {
                m_dwFrames = (DWORD)BitRead(32);
            }

        } else if (BitRead(32, true) == 'VBRI') {
            BitRead(32); // Skip ID tag
            // extract all fields from header (all mandatory)
            BitRead(16); // version
            BitRead(16); // delay
            BitRead(16); // quality
            BitRead(32); // bytes
            m_dwFrames = (DWORD)BitRead(32); // extract total number of frames in file
        }

        if (m_dwFrames) {

            bool l3ext = m_mpahdr.layer == 3 && !(m_mpahdr.version & 1);
            DWORD m_dwSamplesPerFrame = m_mpahdr.layer == 1 ? 384 : l3ext ? 576 : 1152;

            m_bIsVBR = true;
            m_rtDuration = 10000000i64 * (m_dwFrames * m_dwSamplesPerFrame / m_mpahdr.nSamplesPerSec);
        }
    }

    Seek(m_startpos);

    int FrameSize;
    REFERENCE_TIME rtFrameDur, rtPrevDur = -1;
    clock_t start = clock();
    int i = 0;
    while (Sync(FrameSize, rtFrameDur) && (clock() - start) < CLOCKS_PER_SEC) {
        TRACE(_T("%I64d\n"), m_rtDuration);
        Seek(GetPos() + FrameSize);
        i = rtPrevDur == m_rtDuration ? i + 1 : 0;
        if (i == 10) {
            break;
        }
        rtPrevDur = m_rtDuration;
    }

    return S_OK;
}

bool CMpaSplitterFile::Sync(int limit)
{
    int FrameSize;
    REFERENCE_TIME rtDuration;
    return Sync(FrameSize, rtDuration, limit);
}

bool CMpaSplitterFile::Sync(int& FrameSize, REFERENCE_TIME& rtDuration, int limit)
{
    __int64 endpos = min(m_endpos, GetPos() + limit);

    if (m_mode == mpa) {
        while (GetPos() <= endpos - 4) {
            mpahdr h;

            if (Read(h, (int)(endpos - GetPos()), true)) {
                if (m_mpahdr.version == h.version
                        && m_mpahdr.layer == h.layer
                        && m_mpahdr.channels == h.channels) {
                    Seek(GetPos() - 4);
                    AdjustDuration(h.nBytesPerSec);

                    FrameSize = h.FrameSize;
                    rtDuration = h.rtDuration;

                    return true;
                }
            } else {
                break;
            }
        }
    } else if (m_mode == mp4a) {
        while (GetPos() <= endpos - 9) {
            aachdr h;

            if (Read(h, (int)(endpos - GetPos()))) {
                if (m_aachdr.version == h.version
                        && m_aachdr.layer == h.layer
                        && m_aachdr.channels == h.channels) {
                    Seek(GetPos() - (h.fcrc ? 7 : 9));
                    AdjustDuration(h.nBytesPerSec);
                    Seek(GetPos() + (h.fcrc ? 7 : 9));

                    FrameSize = h.FrameSize;
                    rtDuration = h.rtDuration;

                    return true;
                }
            } else {
                break;
            }
        }
    }

    return false;
}

void CMpaSplitterFile::AdjustDuration(int nBytesPerSec)
{
    ASSERT(nBytesPerSec);

    if (!m_bIsVBR) {
        int rValue;
        if (!m_pos2bps.Lookup(GetPos(), rValue)) {
            m_totalbps += nBytesPerSec;
            if (!m_totalbps) {
                return;
            }
            m_pos2bps.SetAt(GetPos(), nBytesPerSec);
            __int64 avgbps = m_totalbps / m_pos2bps.GetCount();
            m_rtDuration = 10000000i64 * (m_endpos - m_startpos) / avgbps;
        }
    }
}