aboutsummaryrefslogtreecommitdiffstats
path: root/taglib/mpeg/mpegfile.cpp
blob: ddfe7f9ee829e2c95528329ad7444573c3dda6e3 (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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/***************************************************************************
    copyright            : (C) 2002 - 2008 by Scott Wheeler
    email                : wheeler@kde.org
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library 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     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tagunion.h>
#include <tagutils.h>
#include <id3v2tag.h>
#include <id3v2header.h>
#include <id3v1tag.h>
#include <apefooter.h>
#include <apetag.h>
#include <tdebug.h>

#include "mpegfile.h"
#include "mpegheader.h"
#include "mpegutils.h"
#include "tpropertymap.h"

using namespace TagLib;

namespace
{
  enum { ID3v2Index = 0, APEIndex = 1, ID3v1Index = 2 };
}

class MPEG::File::FilePrivate
{
public:
  FilePrivate(const ID3v2::FrameFactory *frameFactory = ID3v2::FrameFactory::instance()) :
    ID3v2FrameFactory(frameFactory),
    ID3v2Location(-1),
    ID3v2OriginalSize(0),
    APELocation(-1),
    APEOriginalSize(0),
    ID3v1Location(-1),
    properties(0) {}

  ~FilePrivate()
  {
    delete properties;
  }

  const ID3v2::FrameFactory *ID3v2FrameFactory;

  long ID3v2Location;
  long ID3v2OriginalSize;

  long APELocation;
  long APEOriginalSize;

  long ID3v1Location;

  TagUnion tag;

  Properties *properties;
};

////////////////////////////////////////////////////////////////////////////////
// static members
////////////////////////////////////////////////////////////////////////////////

namespace
{
  // Dummy file class to make a stream work with MPEG::Header.

  class AdapterFile : public TagLib::File
  {
  public:
    AdapterFile(IOStream *stream) : File(stream) {}

    Tag *tag() const { return 0; }
    AudioProperties *audioProperties() const { return 0; }
    bool save() { return false; }
  };
}

bool MPEG::File::isSupported(IOStream *stream)
{
  if(!stream || !stream->isOpen())
    return false;

  // An MPEG file has MPEG frame headers. An ID3v2 tag may precede.

  // MPEG frame headers are really confusing with irrelevant binary data.
  // So we check if a frame header is really valid.

  long headerOffset;
  const ByteVector buffer = Utils::readHeader(stream, bufferSize(), true, &headerOffset);

  if(buffer.isEmpty())
      return false;

  const long originalPosition = stream->tell();
  AdapterFile file(stream);

  for(unsigned int i = 0; i < buffer.size() - 1; ++i) {
    if(isFrameSync(buffer, i)) {
      const Header header(&file, headerOffset + i, true);
      if(header.isValid()) {
        stream->seek(originalPosition);
        return true;
      }
    }
  }

  stream->seek(originalPosition);
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////

MPEG::File::File(FileName file, bool readProperties, Properties::ReadStyle) :
  TagLib::File(file),
  d(new FilePrivate())
{
  if(isOpen())
    read(readProperties);
}

MPEG::File::File(FileName file, ID3v2::FrameFactory *frameFactory,
                 bool readProperties, Properties::ReadStyle) :
  TagLib::File(file),
  d(new FilePrivate(frameFactory))
{
  if(isOpen())
    read(readProperties);
}

MPEG::File::File(IOStream *stream, ID3v2::FrameFactory *frameFactory,
                 bool readProperties, Properties::ReadStyle) :
  TagLib::File(stream),
  d(new FilePrivate(frameFactory))
{
  if(isOpen())
    read(readProperties);
}

MPEG::File::~File()
{
  delete d;
}

TagLib::Tag *MPEG::File::tag() const
{
  return &d->tag;
}

PropertyMap MPEG::File::properties() const
{
  return d->tag.properties();
}

void MPEG::File::removeUnsupportedProperties(const StringList &properties)
{
  d->tag.removeUnsupportedProperties(properties);
}

PropertyMap MPEG::File::setProperties(const PropertyMap &properties)
{
  // update ID3v1 tag if it exists, but ignore the return value

  if(ID3v1Tag())
    ID3v1Tag()->setProperties(properties);

  return ID3v2Tag(true)->setProperties(properties);
}

MPEG::Properties *MPEG::File::audioProperties() const
{
  return d->properties;
}

bool MPEG::File::save()
{
  return save(AllTags);
}

bool MPEG::File::save(int tags)
{
  return save(tags, true);
}

bool MPEG::File::save(int tags, bool stripOthers)
{
  return save(tags, stripOthers, 4);
}

bool MPEG::File::save(int tags, bool stripOthers, int id3v2Version)
{
  return save(tags, stripOthers, id3v2Version, true);
}

bool MPEG::File::save(int tags, bool stripOthers, int id3v2Version, bool duplicateTags)
{
  return save(tags,
              stripOthers ? StripOthers : StripNone,
              id3v2Version == 3 ? ID3v2::v3 : ID3v2::v4,
              duplicateTags ? Duplicate : DoNotDuplicate);
}

bool MPEG::File::save(int tags, StripTags strip, ID3v2::Version version, DuplicateTags duplicate)
{
  if(readOnly()) {
    debug("MPEG::File::save() -- File is read only.");
    return false;
  }

  // Create the tags if we've been asked to.

  if(duplicate == Duplicate) {

    // Copy the values from the tag that does exist into the new tag,
    // except if the existing tag is to be stripped.

    if((tags & ID3v2) && ID3v1Tag() && !(strip == StripOthers && !(tags & ID3v1)))
      Tag::duplicate(ID3v1Tag(), ID3v2Tag(true), false);

    if((tags & ID3v1) && d->tag[ID3v2Index] && !(strip == StripOthers && !(tags & ID3v2)))
      Tag::duplicate(ID3v2Tag(), ID3v1Tag(true), false);
  }

  // Remove all the tags not going to be saved.

  if(strip == StripOthers)
    File::strip(~tags, false);

  if(ID3v2 & tags) {

    if(ID3v2Tag() && !ID3v2Tag()->isEmpty()) {

      // ID3v2 tag is not empty. Update the old one or create a new one.

      if(d->ID3v2Location < 0)
        d->ID3v2Location = 0;

      const ByteVector data = ID3v2Tag()->render(version);
      insert(data, d->ID3v2Location, d->ID3v2OriginalSize);

      if(d->APELocation >= 0)
        d->APELocation += (static_cast<long>(data.size()) - d->ID3v2OriginalSize);

      if(d->ID3v1Location >= 0)
        d->ID3v1Location += (static_cast<long>(data.size()) - d->ID3v2OriginalSize);

      d->ID3v2OriginalSize = data.size();
    }
    else {

      // ID3v2 tag is empty. Remove the old one.

      File::strip(ID3v2, false);
    }
  }

  if(ID3v1 & tags) {

    if(ID3v1Tag() && !ID3v1Tag()->isEmpty()) {

      // ID3v1 tag is not empty. Update the old one or create a new one.

      if(d->ID3v1Location >= 0) {
        seek(d->ID3v1Location);
      }
      else {
        seek(0, End);
        d->ID3v1Location = tell();
      }

      writeBlock(ID3v1Tag()->render());
    }
    else {

      // ID3v1 tag is empty. Remove the old one.

      File::strip(ID3v1, false);
    }
  }

  if(APE & tags) {

    if(APETag() && !APETag()->isEmpty()) {

      // APE tag is not empty. Update the old one or create a new one.

      if(d->APELocation < 0) {
        if(d->ID3v1Location >= 0)
          d->APELocation = d->ID3v1Location;
        else
          d->APELocation = length();
      }

      const ByteVector data = APETag()->render();
      insert(data, d->APELocation, d->APEOriginalSize);

      if(d->ID3v1Location >= 0)
        d->ID3v1Location += (static_cast<long>(data.size()) - d->APEOriginalSize);

      d->APEOriginalSize = data.size();
    }
    else {

      // APE tag is empty. Remove the old one.

      File::strip(APE, false);
    }
  }

  return true;
}

ID3v2::Tag *MPEG::File::ID3v2Tag(bool create)
{
  return d->tag.access<ID3v2::Tag>(ID3v2Index, create);
}

ID3v1::Tag *MPEG::File::ID3v1Tag(bool create)
{
  return d->tag.access<ID3v1::Tag>(ID3v1Index, create);
}

APE::Tag *MPEG::File::APETag(bool create)
{
  return d->tag.access<APE::Tag>(APEIndex, create);
}

bool MPEG::File::strip(int tags)
{
  return strip(tags, true);
}

bool MPEG::File::strip(int tags, bool freeMemory)
{
  if(readOnly()) {
    debug("MPEG::File::strip() - Cannot strip tags from a read only file.");
    return false;
  }

  if((tags & ID3v2) && d->ID3v2Location >= 0) {
    removeBlock(d->ID3v2Location, d->ID3v2OriginalSize);

    if(d->APELocation >= 0)
      d->APELocation -= d->ID3v2OriginalSize;

    if(d->ID3v1Location >= 0)
      d->ID3v1Location -= d->ID3v2OriginalSize;

    d->ID3v2Location = -1;
    d->ID3v2OriginalSize = 0;

    if(freeMemory)
      d->tag.set(ID3v2Index, 0);
  }

  if((tags & ID3v1) && d->ID3v1Location >= 0) {
    truncate(d->ID3v1Location);

    d->ID3v1Location = -1;

    if(freeMemory)
      d->tag.set(ID3v1Index, 0);
  }

  if((tags & APE) && d->APELocation >= 0) {
    removeBlock(d->APELocation, d->APEOriginalSize);

    if(d->ID3v1Location >= 0)
      d->ID3v1Location -= d->APEOriginalSize;

    d->APELocation = -1;
    d->APEOriginalSize = 0;

    if(freeMemory)
      d->tag.set(APEIndex, 0);
  }

  return true;
}

void MPEG::File::setID3v2FrameFactory(const ID3v2::FrameFactory *factory)
{
  d->ID3v2FrameFactory = factory;
}

long MPEG::File::nextFrameOffset(long position)
{
  ByteVector frameSyncBytes(2, '\0');

  while(true) {
    seek(position);
    const ByteVector buffer = readBlock(bufferSize());
    if(buffer.isEmpty())
      return -1;

    for(unsigned int i = 0; i < buffer.size(); ++i) {
      frameSyncBytes[0] = frameSyncBytes[1];
      frameSyncBytes[1] = buffer[i];
      if(isFrameSync(frameSyncBytes)) {
        const Header header(this, position + i - 1, true);
        if(header.isValid())
          return position + i - 1;
      }
    }

    position += bufferSize();
  }
}

long MPEG::File::previousFrameOffset(long position)
{
  ByteVector frameSyncBytes(2, '\0');

  while(position > 0) {
    const long bufferLength = std::min<long>(position, bufferSize());
    position -= bufferLength;

    seek(position);
    const ByteVector buffer = readBlock(bufferLength);

    for(int i = buffer.size() - 1; i >= 0; --i) {
      frameSyncBytes[1] = frameSyncBytes[0];
      frameSyncBytes[0] = buffer[i];
      if(isFrameSync(frameSyncBytes)) {
        const Header header(this, position + i, true);
        if(header.isValid())
          return position + i + header.frameLength();
      }
    }
  }

  return -1;
}

long MPEG::File::firstFrameOffset()
{
  long position = 0;

  if(hasID3v2Tag())
    position = d->ID3v2Location + ID3v2Tag()->header()->completeTagSize();

  return nextFrameOffset(position);
}

long MPEG::File::lastFrameOffset()
{
  long position;

  if(hasAPETag())
    position = d->APELocation - 1;
  else if(hasID3v1Tag())
    position = d->ID3v1Location - 1;
  else
    position = length();

  return previousFrameOffset(position);
}

bool MPEG::File::hasID3v1Tag() const
{
  return (d->ID3v1Location >= 0);
}

bool MPEG::File::hasID3v2Tag() const
{
  return (d->ID3v2Location >= 0);
}

bool MPEG::File::hasAPETag() const
{
  return (d->APELocation >= 0);
}

////////////////////////////////////////////////////////////////////////////////
// private members
////////////////////////////////////////////////////////////////////////////////

void MPEG::File::read(bool readProperties)
{
  // Look for an ID3v2 tag

  d->ID3v2Location = findID3v2();

  if(d->ID3v2Location >= 0) {
    d->tag.set(ID3v2Index, new ID3v2::Tag(this, d->ID3v2Location, d->ID3v2FrameFactory));
    d->ID3v2OriginalSize = ID3v2Tag()->header()->completeTagSize();
  }

  // Look for an ID3v1 tag

  d->ID3v1Location = Utils::findID3v1(this);

  if(d->ID3v1Location >= 0)
    d->tag.set(ID3v1Index, new ID3v1::Tag(this, d->ID3v1Location));

  // Look for an APE tag

  d->APELocation = Utils::findAPE(this, d->ID3v1Location);

  if(d->APELocation >= 0) {
    d->tag.set(APEIndex, new APE::Tag(this, d->APELocation));
    d->APEOriginalSize = APETag()->footer()->completeTagSize();
    d->APELocation = d->APELocation + APE::Footer::size() - d->APEOriginalSize;
  }

  if(readProperties)
    d->properties = new Properties(this);

  // Make sure that we have our default tag types available.

  ID3v2Tag(true);
  ID3v1Tag(true);
}

long MPEG::File::findID3v2()
{
  if(!isValid())
    return -1;

  // An ID3v2 tag or MPEG frame is most likely be at the beginning of the file.

  const ByteVector headerID = ID3v2::Header::fileIdentifier();

  seek(0);
  if(readBlock(headerID.size()) == headerID)
    return 0;

  const Header firstHeader(this, 0, true);
  if(firstHeader.isValid())
    return -1;

  // Look for an ID3v2 tag until reaching the first valid MPEG frame.

  ByteVector frameSyncBytes(2, '\0');
  ByteVector tagHeaderBytes(3, '\0');
  long position = 0;

  while(true) {
    seek(position);
    const ByteVector buffer = readBlock(bufferSize());
    if(buffer.isEmpty())
      return -1;

    for(unsigned int i = 0; i < buffer.size(); ++i) {
      frameSyncBytes[0] = frameSyncBytes[1];
      frameSyncBytes[1] = buffer[i];
      if(isFrameSync(frameSyncBytes)) {
        const Header header(this, position + i - 1, true);
        if(header.isValid())
          return -1;
      }

      tagHeaderBytes[0] = tagHeaderBytes[1];
      tagHeaderBytes[1] = tagHeaderBytes[2];
      tagHeaderBytes[2] = buffer[i];
      if(tagHeaderBytes == headerID)
        return position + i - 2;
    }

    position += bufferSize();
  }
}