File: k3bcuefileparser.cpp

package info (click to toggle)
k3b 25.12.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,820 kB
  • sloc: cpp: 99,202; xml: 375; sh: 84; makefile: 10
file content (437 lines) | stat: -rw-r--r-- 13,715 bytes parent folder | download | duplicates (2)
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
434
435
436
437
/*
    SPDX-FileCopyrightText: 1998-2008 Sebastian Trueg <trueg@k3b.org>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include "k3bcuefileparser.h"

#include "k3bmsf.h"
#include "k3bglobals.h"
#include "k3btrack.h"
#include "k3bcdtext.h"

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QRegularExpression>


// TODO: add method: usableByCdrecordDirectly()
// TODO: add Toc with sector sizes

class K3b::CueFileParser::Private
{
public:
    bool inFile;
    bool inTrack;
    Device::Track::TrackType trackType;
    Device::Track::DataMode trackMode;
    bool rawData;
    bool haveIndex1;
    K3b::Msf currentDataPos;
    K3b::Msf index0;

    K3b::Device::Toc toc;
    int currentParsedTrack;

    K3b::Device::CdText cdText;

    QString imageFileType;
};



K3b::CueFileParser::CueFileParser( const QString& filename )
    : K3b::ImageFileReader()
{
    d = new Private;
    openFile( filename );
}


K3b::CueFileParser::~CueFileParser()
{
    delete d;
}


void K3b::CueFileParser::readFile()
{
    setValid(true);

    d->inFile = d->inTrack = d->haveIndex1 = false;
    d->trackMode = K3b::Device::Track::UNKNOWN;
    d->toc.clear();
    d->cdText.clear();
    d->currentParsedTrack = 0;

    QFile f( filename() );
    if( f.open( QIODevice::ReadOnly ) ) {
        while( !f.atEnd() ) {
            if( !parseLine( QString::fromUtf8(f.readLine() ) ) ) {
                setValid(false);
                break;
            }
        }

        if( isValid() ) {
            // save last parsed track for which we do not have the proper length :(
            if( d->currentParsedTrack > 0 ) {
                d->toc.append( K3b::Device::Track( d->currentDataPos,
                                                 d->currentDataPos,
                                                 d->trackType,
                                                 d->trackMode ) );
            }

            // debug the toc
            qDebug() << "(K3b::CueFileParser) successfully parsed cue file." << Qt::endl
                     << "------------------------------------------------" << Qt::endl;
            for( int i = 0; i < d->toc.count(); ++i ) {
                K3b::Device::Track& track = d->toc[i];
                qDebug() << "Track " << (i+1)
                         << " (" << ( track.type() == K3b::Device::Track::TYPE_AUDIO ? "audio" : "data" ) << ") "
                         << track.firstSector().toString() << " - " << track.lastSector().toString() << Qt::endl;
            }

            qDebug() << "------------------------------------------------";
        }
    }
    else {
        qDebug() << "(K3b::CueFileParser) could not open file " << filename();
        setValid(false);
    }
}


bool K3b::CueFileParser::parseLine( QString line )
{
    // use cap(1) for the filename
    static const QRegularExpression fileRx( QRegularExpression::anchoredPattern( "FILE\\s\"?([^\"].*[^\"\\s])\"?\\s\"?(.*)\"?" ) );

    // use cap(1) for the flags
    static const QRegularExpression flagsRx( QRegularExpression::anchoredPattern( "FLAGS(\\s(DCP|4CH|PRE|SCMS)){1,4}" ) );

    // use cap(1) for the tracknumber and cap(2) for the datatype
    static const QRegularExpression trackRx( QRegularExpression::anchoredPattern( "TRACK\\s(\\d{1,2})\\s(AUDIO|CDG|MODE1/2048|MODE1/2352|MODE2/2336|MODE2/2352|CDI/2336|CDI/2352)" ) );

    // use cap(1) for the index number, cap(3) for the minutes, cap(4) for the seconds, cap(5) for the frames,
    // and cap(2) for the MSF value string
    static const QRegularExpression indexRx( QRegularExpression::anchoredPattern( "INDEX\\s(\\d{1,2})\\s((\\d+):([0-5]\\d):((?:[0-6]\\d)|(?:7[0-4])))" ) );

    // use cap(1) for the MCN
    static const QRegularExpression catalogRx( QRegularExpression::anchoredPattern( "CATALOG\\s(\\w{13,13})" ) );

    // use cap(1) for the ISRC
    static const QRegularExpression isrcRx( QRegularExpression::anchoredPattern( "ISRC\\s(\\w{5,5}\\d{7,7})" ) );

    static QString cdTextRxStr = "\"?([^\"]{0,80})\"?";

    // use cap(1) for the string
    static const QRegularExpression titleRx( QRegularExpression::anchoredPattern( "TITLE\\s" + cdTextRxStr ) );
    static const QRegularExpression performerRx( QRegularExpression::anchoredPattern( "PERFORMER\\s" + cdTextRxStr ) );
    static const QRegularExpression songwriterRx( QRegularExpression::anchoredPattern( "SONGWRITER\\s" + cdTextRxStr ) );


    // simplify all white spaces except those in filenames and CD-TEXT
    simplified( line );

    // skip comments and empty lines
    if( line.startsWith("REM") || line.startsWith('#') || line.isEmpty() )
        return true;


    //
    // FILE
    //
    if( const auto fileMatch = fileRx.match( line ); fileMatch.hasMatch() ) {

        setValid( findImageFileName( fileMatch.captured(1) ) );

        if( d->inFile ) {
            qDebug() << "(K3b::CueFileParser) only one FILE statement allowed.";
            return false;
        }
        d->inFile = true;
        d->inTrack = false;
        d->haveIndex1 = false;
        d->imageFileType = fileMatch.captured( 2 ).toLower();
        return true;
    }


    //
    // TRACK
    //
    else if( const auto trackMatch = trackRx.match( line ); trackMatch.hasMatch() ) {
        if( !d->inFile ) {
            qDebug() << "(K3b::CueFileParser) TRACK statement before FILE.";
            return false;
        }

        // check if we had index1 for the last track
        if( d->inTrack && !d->haveIndex1 ) {
            qDebug() << "(K3b::CueFileParser) TRACK without INDEX 1.";
            return false;
        }

        // save last track
        // TODO: use d->rawData in some way
        if( d->currentParsedTrack > 0 ) {
            d->toc.append( K3b::Device::Track( d->currentDataPos,
                                             d->currentDataPos,
                                             d->trackType,
                                             d->trackMode ) );
        }

        d->currentParsedTrack++;

        // parse the tracktype
        if( trackMatch.captured(2) == "AUDIO" ) {
            d->trackType = K3b::Device::Track::TYPE_AUDIO;
            d->trackMode = K3b::Device::Track::UNKNOWN;
        }
        else {
            d->trackType = K3b::Device::Track::TYPE_DATA;
            if( trackMatch.captured(2).startsWith("MODE1") ) {
                d->trackMode = K3b::Device::Track::MODE1;
                d->rawData = (trackMatch.captured(2) == "MODE1/2352");
            }
            else if( trackMatch.captured(2).startsWith("MODE2") ) {
                d->trackMode = K3b::Device::Track::MODE2;
                d->rawData = (trackMatch.captured(2) == "MODE2/2352");
            }
            else {
                qDebug() << "(K3b::CueFileParser) unsupported track type: " << trackMatch.capturedView(2);
                return false;
            }
        }

        d->haveIndex1 = false;
        d->inTrack = true;
        d->index0 = 0;

        return true;
    }


    //
    // FLAGS
    //
    else if( const auto flagsMatch = flagsRx.match( line ); flagsMatch.hasMatch() ) {
        if( !d->inTrack ) {
            qDebug() << "(K3b::CueFileParser) FLAGS statement without TRACK.";
            return false;
        }

        // TODO: save the flags
        return true;
    }


    //
    // INDEX
    //
    else if( const auto indexMatch = indexRx.match( line ); indexMatch.hasMatch() ) {
        if( !d->inTrack ) {
            qDebug() << "(K3b::CueFileParser) INDEX statement without TRACK.";
            return false;
        }

        unsigned int indexNumber = indexMatch.capturedView(1).toInt();

        K3b::Msf indexStart = K3b::Msf::fromString( indexMatch.captured(2) );

        if( indexNumber == 0 ) {
            d->index0 = indexStart;

            if( d->currentParsedTrack < 2 && indexStart > 0 ) {
                qDebug() << "(K3b::CueFileParser) first track is not allowed to have a pregap > 0.";
                return false;
            }
        }
        else if( indexNumber == 1 ) {
            d->haveIndex1 = true;
            d->currentDataPos = indexStart;
            if( d->currentParsedTrack > 1 ) {
                d->toc[d->currentParsedTrack-2].setLastSector( indexStart-1 );
                if( d->index0 > 0 && d->index0 < indexStart ) {
                    d->toc[d->currentParsedTrack-2].setIndex0( d->index0 - d->toc[d->currentParsedTrack-2].firstSector() );
                }
            }
        }
        else {
            // TODO: add index > 0
        }

        return true;
    }


    //
    // CATALOG
    //
    if( const auto catalogMatch = catalogRx.match( line ); catalogMatch.hasMatch() ) {
        // TODO: set the toc's mcn
        return true;
    }


    //
    // ISRC
    //
    if( const auto isrcMatch = isrcRx.match( line ); isrcMatch.hasMatch() ) {
        if( d->inTrack ) {
            // TODO: set the track's ISRC
            return true;
        }
        else {
            qDebug() << "(K3b::CueFileParser) ISRC without TRACK.";
            return false;
        }
    }


    //
    // CD-TEXT
    // TODO: create K3b::Device::TrackCdText entries
    //
    else if( const auto titleMatch = titleRx.match( line ); titleMatch.hasMatch() ) {
        if( d->inTrack )
            d->cdText[d->currentParsedTrack-1].setTitle( titleMatch.captured(1) );
        else
            d->cdText.setTitle( titleMatch.captured(1) );
        return true;
    }

    else if( const auto performerMatch = performerRx.match( line ); performerMatch.hasMatch() ) {
        if( d->inTrack )
            d->cdText[d->currentParsedTrack-1].setPerformer( performerMatch.captured(1) );
        else
            d->cdText.setPerformer( performerMatch.captured(1) );
        return true;
    }

    else if( const auto songwriterMatch = songwriterRx.match( line ); songwriterMatch.hasMatch() ) {
        if( d->inTrack )
            d->cdText[d->currentParsedTrack-1].setSongwriter( songwriterMatch.captured(1) );
        else
            d->cdText.setSongwriter( songwriterMatch.captured(1) );
        return true;
    }

    else {
        qDebug() << "(K3b::CueFileParser) unknown Cue line: '" << line << "'";
        return false;
    }
}


void K3b::CueFileParser::simplified( QString& s )
{
    s = s.trimmed();

    int i = 0;
    bool insideQuote = false;
    while( i < s.length() ) {
        if( !insideQuote ) {
            if( s[i].isSpace() && s[i+1].isSpace() )
                s.remove( i, 1 );
        }

        if( s[i] == '"' )
            insideQuote = !insideQuote;

        ++i;
    }
}


K3b::Device::Toc K3b::CueFileParser::toc() const
{
    return d->toc;
}


K3b::Device::CdText K3b::CueFileParser::cdText() const
{
    return d->cdText;
}


QString K3b::CueFileParser::imageFileType() const
{
    return d->imageFileType;
}


bool K3b::CueFileParser::findImageFileName( const QString& dataFile )
{
    //
    // CDRDAO does not use this image filename but replaces the extension from the cue file
    // with "bin" to get the image filename, we should take this into account
    //

    qDebug() << "(K3b::CueFileParser) trying to find file: " << dataFile;

    m_imageFilenameInCue = true;

    // first try filename as a whole (absolute)
    if( QFile::exists( dataFile ) ) {
        setImageFilename( QFileInfo(dataFile).absoluteFilePath() );
        return true;
    }

    // try the filename in the cue's directory
    if( QFileInfo( K3b::parentDir(filename()) + dataFile.section( '/', -1 ) ).isFile() ) {
        setImageFilename( K3b::parentDir(filename()) + dataFile.section( '/', -1 ) );
        qDebug() << "(K3b::CueFileParser) found image file: " << imageFilename();
        return true;
    }

    // try the filename ignoring case
    if( QFileInfo( K3b::parentDir(filename()) + dataFile.section( '/', -1 ).toLower() ).isFile() ) {
        setImageFilename( K3b::parentDir(filename()) + dataFile.section( '/', -1 ).toLower() );
        qDebug() << "(K3b::CueFileParser) found image file: " << imageFilename();
        return true;
    }

    m_imageFilenameInCue = false;

    // try removing the ending from the cue file (image.bin.cue and image.bin)
    if( QFileInfo( filename().left( filename().length()-4 ) ).isFile() ) {
        setImageFilename( filename().left( filename().length()-4 ) );
        qDebug() << "(K3b::CueFileParser) found image file: " << imageFilename();
        return true;
    }

    //
    // we did not find the image specified in the cue.
    // Search for another one having the same filename as the cue but a different extension
    //

    QDir parentDir( K3b::parentDir(filename()) );
    QString filenamePrefix = filename().section( '/', -1 );
    filenamePrefix.truncate( filenamePrefix.length() - 3 ); // remove cue extension
    qDebug() << "(K3b::CueFileParser) checking folder " << parentDir.path() << " for files: " << filenamePrefix << "*";

    //
    // we cannot use the nameFilter in QDir because of the spaces that may occur in filenames
    //
    QStringList possibleImageFiles = parentDir.entryList( QDir::Files );
    int cnt = 0;
    for( QStringList::const_iterator it = possibleImageFiles.constBegin(); it != possibleImageFiles.constEnd(); ++it ) {
        if( (*it).toLower() == dataFile.section( '/', -1 ).toLower() ||
            ((*it).startsWith( filenamePrefix ) && !(*it).endsWith( "cue" )) ) {
            ++cnt;
            setImageFilename( K3b::parentDir(filename()) + *it );
        }
    }

    //
    // we only do this if there is one unique file which fits the requirements.
    // Otherwise we cannot be certain to have the right file.
    //
    return ( cnt == 1 && QFileInfo( imageFilename() ).isFile() );
}