Tag Parser  6.2.1
C++ library for reading and writing MP4 (iTunes), ID3, Vorbis, Opus, FLAC and Matroska tags
mp4container.cpp
Go to the documentation of this file.
1 #include "./mp4container.h"
2 #include "./mp4ids.h"
3 
4 #include "../exceptions.h"
5 #include "../mediafileinfo.h"
6 #include "../backuphelper.h"
7 
8 #include <c++utilities/conversion/stringbuilder.h>
9 #include <c++utilities/io/binaryreader.h>
10 #include <c++utilities/io/binarywriter.h>
11 #include <c++utilities/io/copy.h>
12 #include <c++utilities/io/catchiofailure.h>
13 
14 #include <unistd.h>
15 
16 #include <tuple>
17 #include <numeric>
18 #include <memory>
19 
20 using namespace std;
21 using namespace IoUtilities;
22 using namespace ConversionUtilities;
23 using namespace ChronoUtilities;
24 
25 namespace Media {
26 
35 Mp4Container::Mp4Container(MediaFileInfo &fileInfo, uint64 startOffset) :
36  GenericContainer<MediaFileInfo, Mp4Tag, Mp4Track, Mp4Atom>(fileInfo, startOffset),
37  m_fragmented(false)
38 {}
39 
41 {}
42 
44 {
46  m_fragmented = false;
47 }
48 
50 {
51  if(m_firstElement) {
52  const Mp4Atom *mediaDataAtom = m_firstElement->siblingById(Mp4AtomIds::MediaData);
53  const Mp4Atom *userDataAtom = m_firstElement->subelementByPath({Mp4AtomIds::Movie, Mp4AtomIds::UserData});
54  if(mediaDataAtom && userDataAtom) {
55  return userDataAtom->startOffset() < mediaDataAtom->startOffset() ? ElementPosition::BeforeData : ElementPosition::AfterData;
56  }
57  }
58  return ElementPosition::Keep;
59 }
60 
62 {
63  if(m_firstElement) {
64  const Mp4Atom *mediaDataAtom = m_firstElement->siblingById(Mp4AtomIds::MediaData);
65  const Mp4Atom *movieAtom = m_firstElement->siblingById(Mp4AtomIds::Movie);
66  if(mediaDataAtom && movieAtom) {
67  return movieAtom->startOffset() < mediaDataAtom->startOffset() ? ElementPosition::BeforeData : ElementPosition::AfterData;
68  }
69  }
70  return ElementPosition::Keep;
71 }
72 
74 {
75  //const string context("parsing header of MP4 container"); will be used when generating notifications
76  m_firstElement = make_unique<Mp4Atom>(*this, startOffset());
77  m_firstElement->parse();
78  Mp4Atom *ftypAtom = m_firstElement->siblingById(Mp4AtomIds::FileType, true);
79  if(ftypAtom) {
80  stream().seekg(ftypAtom->dataOffset());
81  m_doctype = reader().readString(4);
82  m_version = reader().readUInt32BE();
83  } else {
84  m_doctype.clear();
85  m_version = 0;
86  }
87 }
88 
90 {
91  const string context("parsing tags of MP4 container");
92  if(Mp4Atom *udtaAtom = firstElement()->subelementByPath({Mp4AtomIds::Movie, Mp4AtomIds::UserData})) {
93  Mp4Atom *metaAtom = udtaAtom->childById(Mp4AtomIds::Meta);
94  bool surplusMetaAtoms = false;
95  while(metaAtom) {
96  metaAtom->parse();
97  m_tags.emplace_back(make_unique<Mp4Tag>());
98  try {
99  m_tags.back()->parse(*metaAtom);
100  } catch(const NoDataFoundException &) {
101  m_tags.pop_back();
102  }
103  metaAtom = metaAtom->siblingById(Mp4AtomIds::Meta, false);
104  if(metaAtom) {
105  surplusMetaAtoms = true;
106  }
107  if(!m_tags.empty()) {
108  break;
109  }
110  }
111  if(surplusMetaAtoms) {
112  addNotification(NotificationType::Warning, "udta atom contains multiple meta atoms. Surplus meta atoms will be ignored.", context);
113  }
114  }
115 }
116 
118 {
120  static const string context("parsing tracks of MP4 container");
121  try {
122  // get moov atom which holds track information
123  if(Mp4Atom *moovAtom = firstElement()->siblingById(Mp4AtomIds::Movie, true)) {
124  // get mvhd atom which holds overall track information
125  if(Mp4Atom *mvhdAtom = moovAtom->childById(Mp4AtomIds::MovieHeader)) {
126  if(mvhdAtom->dataSize() > 0) {
127  stream().seekg(mvhdAtom->dataOffset());
128  byte version = reader().readByte();
129  if((version == 1 && mvhdAtom->dataSize() >= 32) || (mvhdAtom->dataSize() >= 20)) {
130  stream().seekg(3, ios_base::cur); // skip flags
131  switch(version) {
132  case 0:
133  m_creationTime = DateTime::fromDate(1904, 1, 1) + TimeSpan::fromSeconds(reader().readUInt32BE());
134  m_modificationTime = DateTime::fromDate(1904, 1, 1) + TimeSpan::fromSeconds(reader().readUInt32BE());
135  m_timeScale = reader().readUInt32BE();
136  m_duration = TimeSpan::fromSeconds(static_cast<double>(reader().readUInt32BE()) / static_cast<double>(m_timeScale));
137  break;
138  case 1:
139  m_creationTime = DateTime::fromDate(1904, 1, 1) + TimeSpan::fromSeconds(reader().readUInt64BE());
140  m_modificationTime = DateTime::fromDate(1904, 1, 1) + TimeSpan::fromSeconds(reader().readUInt64BE());
141  m_timeScale = reader().readUInt32BE();
142  m_duration = TimeSpan::fromSeconds(static_cast<double>(reader().readUInt64BE()) / static_cast<double>(m_timeScale));
143  break;
144  default:
145  ;
146  }
147  } else {
148  addNotification(NotificationType::Critical, "mvhd atom is truncated.", context);
149  }
150  } else {
151  addNotification(NotificationType::Critical, "mvhd atom is empty.", context);
152  }
153  } else {
154  addNotification(NotificationType::Critical, "mvhd atom is does not exist.", context);
155  }
156  // get mvex atom which holds default values for fragmented files
157  if(Mp4Atom *mehdAtom = moovAtom->subelementByPath({Mp4AtomIds::MovieExtends, Mp4AtomIds::MovieExtendsHeader})) {
158  m_fragmented = true;
159  if(mehdAtom->dataSize() > 0) {
160  stream().seekg(mehdAtom->dataOffset());
161  unsigned int durationSize = reader().readByte() == 1u ? 8u : 4u; // duration size depends on atom version
162  if(mehdAtom->dataSize() >= 4 + durationSize) {
163  stream().seekg(3, ios_base::cur); // skip flags
164  switch(durationSize) {
165  case 4u:
166  m_duration = TimeSpan::fromSeconds(static_cast<double>(reader().readUInt32BE()) / static_cast<double>(m_timeScale));
167  break;
168  case 8u:
169  m_duration = TimeSpan::fromSeconds(static_cast<double>(reader().readUInt64BE()) / static_cast<double>(m_timeScale));
170  break;
171  default:
172  ;
173  }
174  } else {
175  addNotification(NotificationType::Warning, "mehd atom is truncated.", context);
176  }
177  }
178  }
179  // get first trak atoms which hold information for each track
180  Mp4Atom *trakAtom = moovAtom->childById(Mp4AtomIds::Track);
181  int trackNum = 1;
182  while(trakAtom) {
183  try {
184  trakAtom->parse();
185  } catch(const Failure &) {
186  addNotification(NotificationType::Warning, "Unable to parse child atom of moov.", context);
187  }
188  // parse the trak atom using the Mp4Track class
189  m_tracks.emplace_back(make_unique<Mp4Track>(*trakAtom));
190  try { // try to parse header
191  m_tracks.back()->parseHeader();
192  } catch(const Failure &) {
193  addNotification(NotificationType::Critical, "Unable to parse track " + ConversionUtilities::numberToString(trackNum) + ".", context);
194  }
195  trakAtom = trakAtom->siblingById(Mp4AtomIds::Track, false); // get next trak atom
196  ++trackNum;
197  }
198  // get overall duration, creation time and modification time if not determined yet
199  if(m_duration.isNull() || m_modificationTime.isNull() || m_creationTime.isNull()) {
200  for(const auto &track : tracks()) {
201  if(track->duration() > m_duration) {
203  }
206  }
209  }
210  }
211  }
212  }
213  } catch(const Failure &) {
214  addNotification(NotificationType::Warning, "Unable to parse moov atom.", context);
215  }
216 }
217 
219 {
220  // set initial status
222  static const string context("making MP4 container");
223  updateStatus("Calculating atom sizes and padding ...");
224 
225  // basic validation of original file
226  if(!isHeaderParsed()) {
227  addNotification(NotificationType::Critical, "The header has not been parsed yet.", context);
228  throw InvalidDataException();
229  }
230 
231  // define variables needed to parse atoms of original file
232  if(!firstElement()) {
233  addNotification(NotificationType::Critical, "No MP4 atoms could be found.", context);
234  throw InvalidDataException();
235  }
236 
237  // define variables needed to manage file layout
238  // -> whether media data is written chunk by chunk (need to write chunk by chunk if tracks have been altered)
239  const bool writeChunkByChunk = m_tracksAltered;
240  // -> whether rewrite is required (always required when forced to rewrite or when tracks have been altered)
241  bool rewriteRequired = fileInfo().isForcingRewrite() || writeChunkByChunk;
242  // -> use the preferred tag position/index position (force one wins, if both are force tag pos wins; might be changed later if none is forced)
244  ElementPosition newTagPos = initialNewTagPos;
245  // -> current tag position (determined later)
246  ElementPosition currentTagPos;
247  // -> holds new padding (before actual data)
248  uint64 newPadding;
249  // -> holds new padding (after actual data)
250  uint64 newPaddingEnd;
251  // -> holds current offset
252  uint64 currentOffset;
253  // -> holds track information, used when writing chunk-by-chunk
254  vector<tuple<istream *, vector<uint64>, vector<uint64> > > trackInfos;
255  // -> holds offsets of media data atoms in original file, used when simply copying mdat
256  vector<int64> origMediaDataOffsets;
257  // -> holds offsets of media data atoms in new file, used when simply copying mdat
258  vector<int64> newMediaDataOffsets;
259  // -> new size of movie atom and user data atom
260  uint64 movieAtomSize, userDataAtomSize;
261  // -> track count of original file
262  const auto trackCount = this->trackCount();
263 
264  // find relevant atoms in original file
265  Mp4Atom *fileTypeAtom, *progressiveDownloadInfoAtom, *movieAtom, *firstMediaDataAtom, *firstMovieFragmentAtom, *userDataAtom, *metaAtom;
266  Mp4Atom *level0Atom, *level1Atom, *level2Atom, *lastAtomToBeWritten;
267  try {
268  // file type atom (mandatory)
269  if((fileTypeAtom = firstElement()->siblingById(Mp4AtomIds::FileType, true))) {
270  // buffer atom
271  fileTypeAtom->makeBuffer();
272  } else {
273  // throw error if missing
274  addNotification(NotificationType::Critical, "Mandatory \"ftyp\"-atom not found.", context);
275  throw InvalidDataException();
276  }
277 
278  // progressive download information atom (not mandatory)
279  if((progressiveDownloadInfoAtom = firstElement()->siblingById(Mp4AtomIds::ProgressiveDownloadInformation, true))) {
280  // buffer atom
281  progressiveDownloadInfoAtom->makeBuffer();
282  }
283 
284  // movie atom (mandatory)
285  if(!(movieAtom = firstElement()->siblingById(Mp4AtomIds::Movie, true))) {
286  // throw error if missing
287  addNotification(NotificationType::Critical, "Mandatory \"moov\"-atom not in the source file found.", context);
288  throw InvalidDataException();
289  }
290 
291  // movie fragment atom (indicates dash file)
292  if((firstMovieFragmentAtom = firstElement()->siblingById(Mp4AtomIds::MovieFragment))) {
293  // there is at least one movie fragment atom -> consider file being dash
294  // -> can not write chunk-by-chunk (currently)
295  if(writeChunkByChunk) {
296  addNotification(NotificationType::Critical, "Writing chunk-by-chunk is not implemented for DASH files.", context);
297  throw NotImplementedException();
298  }
299  // -> tags must be placed at the beginning
300  newTagPos = ElementPosition::BeforeData;
301  }
302 
303  // media data atom (mandatory?)
304  // -> consider not only mdat as media data atom; consider everything not handled otherwise as media data
305  for(firstMediaDataAtom = nullptr, level0Atom = firstElement(); level0Atom; level0Atom = level0Atom->nextSibling()) {
306  level0Atom->parse();
307  switch(level0Atom->id()) {
310  continue;
311  default:
312  firstMediaDataAtom = level0Atom;
313  }
314  break;
315  }
316 
317  // determine current tag position
318  // -> since tags are nested in the movie atom its position is relevant here
319  if(firstMediaDataAtom) {
320  currentTagPos = firstMediaDataAtom->startOffset() < movieAtom->startOffset()
322  if(newTagPos == ElementPosition::Keep) {
323  newTagPos = currentTagPos;
324  }
325  } else {
326  currentTagPos = ElementPosition::Keep;
327  }
328 
329  // ensure index and tags are always placed at the beginning when dealing with DASH files
330  if(firstMovieFragmentAtom) {
331  if(initialNewTagPos == ElementPosition::AfterData) {
332  addNotification(NotificationType::Warning, "Sorry, but putting index/tags at the end is not possible when dealing with DASH files.", context);
333  }
334  initialNewTagPos = newTagPos = ElementPosition::BeforeData;
335  }
336 
337  // user data atom, meta atom, next sibling of meta atom
338  if((userDataAtom = movieAtom->childById(Mp4AtomIds::UserData))) {
339  metaAtom = userDataAtom->childById(Mp4AtomIds::Meta);
340  }
341 
342  } catch (const NotImplementedException &) {
343  throw;
344 
345  } catch (const Failure &) {
346  // can't ignore parsing errors here
347  addNotification(NotificationType::Critical, "Unable to parse the overall atom structure of the source file.", context);
348  throw InvalidDataException();
349  }
350 
351  if(isAborted()) {
353  }
354 
355  // calculate sizes
356  // -> size of tags
357  vector<Mp4TagMaker> tagMaker;
358  uint64 tagsSize = 0;
359  tagMaker.reserve(m_tags.size());
360  for(auto &tag : m_tags) {
361  try {
362  tagMaker.emplace_back(tag->prepareMaking());
363  tagsSize += tagMaker.back().requiredSize();
364  } catch(const Failure &) {
365  // nothing to do because notifications will be added anyways
366  }
368  }
369 
370  // -> size of movie atom (contains track and tag information)
371  movieAtomSize = userDataAtomSize = 0;
372  try {
373  // add size of children
374  for(level0Atom = movieAtom; level0Atom; level0Atom = level0Atom->siblingById(Mp4AtomIds::Movie)) {
375  for(level1Atom = level0Atom->firstChild(); level1Atom; level1Atom = level1Atom->nextSibling()) {
376  level1Atom->parse();
377  switch(level1Atom->id()) {
379  try {
380  for(level2Atom = level1Atom->firstChild(); level2Atom; level2Atom = level2Atom->nextSibling()) {
381  level2Atom->parse();
382  switch(level2Atom->id()) {
383  case Mp4AtomIds::Meta:
384  // ignore meta data here; it is added separately
385  break;
386  default:
387  // add size of unknown childs of the user data atom
388  userDataAtomSize += level2Atom->totalSize();
389  level2Atom->makeBuffer();
390  }
391  }
392  } catch(const Failure &) {
393  // invalid children might be ignored as not mandatory
394  addNotification(NotificationType::Critical, "Unable to parse the children of \"udta\"-atom of the source file; ignoring them.", context);
395  }
396  break;
397  case Mp4AtomIds::Track:
398  // add size of track atoms only if not writing chunk-by-chunk (otherwise sizes are added separately)
399  if(!writeChunkByChunk) {
400  movieAtomSize += level1Atom->totalSize();
401  level1Atom->makeBuffer();
402  }
403  break;
404  default:
405  // add size of unknown childs of the movie atom
406  movieAtomSize += level1Atom->totalSize();
407  level1Atom->makeBuffer();
408  }
409  }
410  }
411 
412  // add size of meta data
413  if(userDataAtomSize += tagsSize) {
414  Mp4Atom::addHeaderSize(userDataAtomSize);
415  movieAtomSize += userDataAtomSize;
416  }
417 
418  // add size of track atoms when writing chunk-by-chunk
419  if(writeChunkByChunk) {
420  // note: Mp4Track API has to be changed when Mp4Track::makeTrack() gets a real implementation.
421  for(const auto &track : tracks()) {
422  movieAtomSize += track->requiredSize();
423  }
424  }
425 
426  // add header size
427  Mp4Atom::addHeaderSize(movieAtomSize);
428  } catch(const Failure &) {
429  // can't ignore parsing errors here
430  addNotification(NotificationType::Critical, "Unable to parse the children of \"moov\"-atom of the source file.", context);
431  throw InvalidDataException();
432  }
433 
434  if(isAborted()) {
436  }
437 
438  // check whether there are atoms to be voided after movie next sibling (only relevant when not rewriting)
439  if(!rewriteRequired) {
440  newPaddingEnd = 0;
441  uint64 currentSum = 0;
442  for(Mp4Atom *level0Atom = firstMediaDataAtom; level0Atom; level0Atom = level0Atom->nextSibling()) {
443  level0Atom->parse();
444  switch(level0Atom->id()) {
447  // must void these if they occur "between" the media data
448  currentSum += level0Atom->totalSize();
449  break;
450  default:
451  newPaddingEnd += currentSum;
452  currentSum = 0;
453  lastAtomToBeWritten = level0Atom;
454  }
455  }
456  }
457 
458  // calculate padding if no rewrite is required; otherwise use the preferred padding
459 calculatePadding:
460  if(rewriteRequired) {
461  newPadding = (fileInfo().preferredPadding() && fileInfo().preferredPadding() < 8 ? 8 : fileInfo().preferredPadding());
462  } else {
463  // file type atom
464  currentOffset = fileTypeAtom->totalSize();
465 
466  // progressive download information atom
467  if(progressiveDownloadInfoAtom) {
468  currentOffset += progressiveDownloadInfoAtom->totalSize();
469  }
470 
471  // if writing tags before data: movie atom (contains tag)
472  switch(newTagPos) {
475  currentOffset += movieAtomSize;
476  break;
477  default:
478  ;
479  }
480 
481  // check whether there is sufficiant space before the next atom
482  if(!(rewriteRequired = firstMediaDataAtom && currentOffset > firstMediaDataAtom->startOffset())) {
483  // there is sufficiant space
484  // -> check whether the padding matches specifications
485  // min padding: says "at least ... byte should be reserved to prepend further tag info", so the padding at the end
486  // shouldn't be tanken into account (it can't be used to prepend further tag info)
487  // max padding: says "do not waste more then ... byte", so here all padding should be taken into account
488  newPadding = firstMediaDataAtom->startOffset() - currentOffset;
489  rewriteRequired = (newPadding > 0 && newPadding < 8) || newPadding < fileInfo().minPadding() || (newPadding + newPaddingEnd) > fileInfo().maxPadding();
490  }
491  if(rewriteRequired) {
492  // can't put the tags before media data
493  if(!firstMovieFragmentAtom && !fileInfo().forceTagPosition() && !fileInfo().forceIndexPosition() && newTagPos != ElementPosition::AfterData) {
494  // writing tag before media data is not forced, its not a DASH file and tags aren't already at the end
495  // -> try to put the tags at the end
496  newTagPos = ElementPosition::AfterData;
497  rewriteRequired = false;
498  } else {
499  // writing tag before media data is forced -> rewrite the file
500  // when rewriting anyways, ensure the preferred tag position is used
501  newTagPos = initialNewTagPos == ElementPosition::Keep ? currentTagPos : initialNewTagPos;
502  }
503  // in any case: recalculate padding
504  goto calculatePadding;
505  } else {
506  // tags can be put before the media data
507  // -> ensure newTagPos is not ElementPosition::Keep
508  if(newTagPos == ElementPosition::Keep) {
509  newTagPos = ElementPosition::BeforeData;
510  }
511  }
512  }
513 
514  if(isAborted()) {
516  }
517 
518  // setup stream(s) for writing
519  // -> update status
520  updateStatus("Preparing streams ...");
521 
522  // -> define variables needed to handle output stream and backup stream (required when rewriting the file)
523  string backupPath;
524  NativeFileStream &outputStream = fileInfo().stream();
525  NativeFileStream backupStream; // create a stream to open the backup/original file for the case rewriting the file is required
526  BinaryWriter outputWriter(&outputStream);
527 
528  if(rewriteRequired) {
529  if(fileInfo().saveFilePath().empty()) {
530  // move current file to temp dir and reopen it as backupStream, recreate original file
531  try {
532  BackupHelper::createBackupFile(fileInfo().path(), backupPath, outputStream, backupStream);
533  // recreate original file, define buffer variables
534  outputStream.open(fileInfo().path(), ios_base::out | ios_base::binary | ios_base::trunc);
535  } catch(...) {
536  const char *what = catchIoFailure();
537  addNotification(NotificationType::Critical, "Creation of temporary file (to rewrite the original file) failed.", context);
538  throwIoFailure(what);
539  }
540  } else {
541  // open the current file as backupStream and create a new outputStream at the specified "save file path"
542  try {
543  backupStream.exceptions(ios_base::badbit | ios_base::failbit);
544  backupStream.open(fileInfo().path(), ios_base::in | ios_base::binary);
545  fileInfo().close();
546  outputStream.open(fileInfo().saveFilePath(), ios_base::out | ios_base::binary | ios_base::trunc);
547  } catch(...) {
548  const char *what = catchIoFailure();
549  addNotification(NotificationType::Critical, "Opening streams to write output file failed.", context);
550  throwIoFailure(what);
551  }
552  }
553 
554  // set backup stream as associated input stream since we need the original elements to write the new file
555  setStream(backupStream);
556 
557  // TODO: reduce code duplication
558 
559  } else { // !rewriteRequired
560  // reopen original file to ensure it is opened for writing
561  try {
562  fileInfo().close();
563  outputStream.open(fileInfo().path(), ios_base::in | ios_base::out | ios_base::binary);
564  } catch(...) {
565  const char *what = catchIoFailure();
566  addNotification(NotificationType::Critical, "Opening the file with write permissions failed.", context);
567  throwIoFailure(what);
568  }
569  }
570 
571  // start actual writing
572  try {
573  // write header
574  updateStatus("Writing header and tags ...");
575  // -> make file type atom
576  fileTypeAtom->copyBuffer(outputStream);
577  fileTypeAtom->discardBuffer();
578  // -> make progressive download info atom
579  if(progressiveDownloadInfoAtom) {
580  progressiveDownloadInfoAtom->copyBuffer(outputStream);
581  progressiveDownloadInfoAtom->discardBuffer();
582  }
583 
584  // write movie atom / padding and media data
585  for(byte pass = 0; pass != 2; ++pass) {
586  if(newTagPos == (pass ? ElementPosition::AfterData : ElementPosition::BeforeData)) {
587  // write movie atom
588  // -> write movie atom header
589  Mp4Atom::makeHeader(movieAtomSize, Mp4AtomIds::Movie, outputWriter);
590 
591  // -> write track atoms (only if writing chunk-by-chunk; otherwise track atoms are written with other children)
592  if(writeChunkByChunk) {
593  // note: Mp4Track API has to be changed when Mp4Track::makeTrack() gets a real implementation.
594  for(auto &track : tracks()) {
595  track->makeTrack();
596  }
597  }
598 
599  // -> write other movie atom children
600  for(level0Atom = movieAtom; level0Atom; level0Atom = level0Atom->siblingById(Mp4AtomIds::Movie)) {
601  for(level1Atom = level0Atom->firstChild(); level1Atom; level1Atom = level1Atom->nextSibling()) {
602  switch(level1Atom->id()) {
604  break;
605  case Mp4AtomIds::Track:
606  // write buffered data
607  if(!writeChunkByChunk) {
608  level1Atom->copyBuffer(outputStream);
609  level1Atom->discardBuffer();
610  }
611  break;
612  default:
613  // write buffered data
614  level1Atom->copyBuffer(outputStream);
615  level1Atom->discardBuffer();
616  }
617  }
618  }
619 
620  // -> write user data atom
621  if(userDataAtomSize) {
622  // writer user data atom header
623  Mp4Atom::makeHeader(userDataAtomSize, Mp4AtomIds::UserData, outputWriter);
624 
625  // write other children of user data atom
626  for(level0Atom = movieAtom; level0Atom; level0Atom = level0Atom->siblingById(Mp4AtomIds::Movie)) {
627  for(level1Atom = level0Atom->childById(Mp4AtomIds::UserData); level1Atom; level1Atom = level1Atom->siblingById(Mp4AtomIds::UserData)) {
628  for(level2Atom = level1Atom->firstChild(); level2Atom; level2Atom = level2Atom->nextSibling()) {
629  switch(level2Atom->id()) {
630  case Mp4AtomIds::Meta:
631  break;
632  default:
633  // write buffered data
634  level2Atom->copyBuffer(outputStream);
635  level2Atom->discardBuffer();
636  }
637  }
638  }
639  }
640 
641  // write meta atom
642  for(auto &maker : tagMaker) {
643  maker.make(outputStream);
644  }
645  }
646 
647  } else {
648  // write padding
649  if(newPadding) {
650  // write free atom header
651  if(newPadding < 0xFFFFFFFF) {
652  outputWriter.writeUInt32BE(newPadding);
653  outputWriter.writeUInt32BE(Mp4AtomIds::Free);
654  newPadding -= 8;
655  } else {
656  outputWriter.writeUInt32BE(1);
657  outputWriter.writeUInt32BE(Mp4AtomIds::Free);
658  outputWriter.writeUInt64BE(newPadding);
659  newPadding -= 16;
660  }
661 
662  // write zeroes
663  for(; newPadding; --newPadding) {
664  outputStream.put(0);
665  }
666  }
667 
668  // write media data
669  if(rewriteRequired) {
670  for(level0Atom = firstMediaDataAtom; level0Atom; level0Atom = level0Atom->nextSibling()) {
671  level0Atom->parse();
672  switch(level0Atom->id()) {
675  break;
677  if(writeChunkByChunk) {
678  // write actual data separately when writing chunk-by-chunk
679  break;
680  } else {
681  // store media data offsets when not writing chunk-by-chunk to be able to update chunk offset table
682  origMediaDataOffsets.push_back(level0Atom->startOffset());
683  newMediaDataOffsets.push_back(outputStream.tellp());
684  }
685  default:
686  // update status
687  updateStatus("Writing atom: " + level0Atom->idToString());
688  // copy atom entirely and forward status update calls
689  level0Atom->forwardStatusUpdateCalls(this);
690  level0Atom->copyEntirely(outputStream);
691  }
692  }
693 
694  // when writing chunk-by-chunk write media data now
695  if(writeChunkByChunk) {
696  // read chunk offset and chunk size table from the old file which are required to get chunks
697  updateStatus("Reading chunk offsets and sizes from the original file ...");
698  trackInfos.reserve(trackCount);
699  uint64 totalChunkCount = 0;
700  uint64 totalMediaDataSize = 0;
701  for(auto &track : tracks()) {
702  if(isAborted()) {
704  }
705 
706  // ensure the track reads from the original file
707  if(&track->inputStream() == &outputStream) {
708  track->setInputStream(backupStream);
709  }
710 
711  // emplace information
712  trackInfos.emplace_back(&track->inputStream(), track->readChunkOffsets(), track->readChunkSizes());
713 
714  // check whether the chunks could be parsed correctly
715  const vector<uint64> &chunkOffsetTable = get<1>(trackInfos.back());
716  const vector<uint64> &chunkSizesTable = get<2>(trackInfos.back());
717  if(track->chunkCount() != chunkOffsetTable.size() || track->chunkCount() != chunkSizesTable.size()) {
718  addNotification(NotificationType::Critical, "Chunks of track " % numberToString<uint64, string>(track->id()) + " could not be parsed correctly.", context);
719  }
720 
721  // increase total chunk count and size
722  totalChunkCount += track->chunkCount();
723  totalMediaDataSize = accumulate(chunkSizesTable.cbegin(), chunkSizesTable.cend(), totalMediaDataSize);
724  }
725 
726  // write media data chunk-by-chunk
727  // -> write header of media data atom
728  Mp4Atom::addHeaderSize(totalMediaDataSize);
729  Mp4Atom::makeHeader(totalMediaDataSize, Mp4AtomIds::MediaData, outputWriter);
730 
731  // -> copy chunks
732  CopyHelper<0x2000> copyHelper;
733  uint64 chunkIndexWithinTrack = 0, totalChunksCopied = 0;
734  bool anyChunksCopied;
735  do {
736  if(isAborted()) {
738  }
739 
740  // copy a chunk from each track
741  anyChunksCopied = false;
742  for(size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
743  // get source stream and tables for current track
744  auto &trackInfo = trackInfos[trackIndex];
745  istream &sourceStream = *get<0>(trackInfo);
746  vector<uint64> &chunkOffsetTable = get<1>(trackInfo);
747  const vector<uint64> &chunkSizesTable = get<2>(trackInfo);
748 
749  // still chunks to be copied (of this track)?
750  if(chunkIndexWithinTrack < chunkOffsetTable.size() && chunkIndexWithinTrack < chunkSizesTable.size()) {
751  // copy chunk, update entry in chunk offset table
752  sourceStream.seekg(chunkOffsetTable[chunkIndexWithinTrack]);
753  chunkOffsetTable[chunkIndexWithinTrack] = outputStream.tellp();
754  copyHelper.copy(sourceStream, outputStream, chunkSizesTable[chunkIndexWithinTrack]);
755 
756  // update counter / status
757  anyChunksCopied = true;
758  ++totalChunksCopied;
759  }
760  }
761 
762  // incrase chunk index within track, update progress percentage
763  if(++chunkIndexWithinTrack % 10) {
764  updatePercentage(static_cast<double>(totalChunksCopied) / totalChunkCount);
765  }
766 
767  } while(anyChunksCopied);
768  }
769 
770  } else {
771  // can't just skip next movie sibling
772  for(Mp4Atom *level0Atom = firstMediaDataAtom; level0Atom; level0Atom = level0Atom->nextSibling()) {
773  level0Atom->parse();
774  switch(level0Atom->id()) {
776  // must void these if they occur "between" the media data
777  outputStream.seekp(4, ios_base::cur);
778  outputWriter.writeUInt32BE(Mp4AtomIds::Free);
779  break;
780  default:
781  outputStream.seekp(level0Atom->totalSize(), ios_base::cur);
782  }
783  if(level0Atom == lastAtomToBeWritten) {
784  break;
785  }
786  }
787  }
788  }
789  }
790 
791  // reparse what is written so far
792  updateStatus("Reparsing output file ...");
793  if(rewriteRequired) {
794  // report new size
795  fileInfo().reportSizeChanged(outputStream.tellp());
796  // "save as path" is now the regular path
797  if(!fileInfo().saveFilePath().empty()) {
798  fileInfo().reportPathChanged(fileInfo().saveFilePath());
799  fileInfo().setSaveFilePath(string());
800  }
801  // the outputStream needs to be reopened to be able to read again
802  outputStream.close();
803  outputStream.open(fileInfo().path(), ios_base::in | ios_base::out | ios_base::binary);
804  setStream(outputStream);
805  } else {
806  const auto newSize = static_cast<uint64>(outputStream.tellp());
807  if(newSize < fileInfo().size()) {
808  // file is smaller after the modification -> truncate
809  // -> close stream before truncating
810  outputStream.close();
811  // -> truncate file
812  if(truncate(fileInfo().path().c_str(), newSize) == 0) {
813  fileInfo().reportSizeChanged(newSize);
814  } else {
815  addNotification(NotificationType::Critical, "Unable to truncate the file.", context);
816  }
817  // -> reopen the stream again
818  outputStream.open(fileInfo().path(), ios_base::in | ios_base::out | ios_base::binary);
819  } else {
820  // file is longer after the modification -> just report new size
821  fileInfo().reportSizeChanged(newSize);
822  }
823  }
824 
825  reset();
826  try {
827  parseTracks();
828  } catch(const Failure &) {
829  addNotification(NotificationType::Critical, "Unable to reparse the header of the new file.", context);
830  throw;
831  }
832 
833  if(rewriteRequired) {
834  // check whether track count of new file equals track count of old file
835  if(trackCount != tracks().size()) {
837  "Unable to update chunk offsets (\"stco\"-atom): Number of tracks in the output file ("
838  % numberToString(tracks().size())
839  % ") differs from the number of tracks in the original file ("
840  % numberToString(trackCount)
841  + ").", context);
842  throw Failure();
843  }
844 
845  // update chunk offset table
846  if(writeChunkByChunk) {
847  updateStatus("Updating chunk offset table for each track ...");
848  for(size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
849  const auto &track = tracks()[trackIndex];
850  const auto &chunkOffsetTable = get<1>(trackInfos[trackIndex]);
851  if(track->chunkCount() == chunkOffsetTable.size()) {
852  track->updateChunkOffsets(chunkOffsetTable);
853  } else {
854  addNotification(NotificationType::Critical, "Unable to update chunk offsets of track " % numberToString(trackIndex + 1) + ": Number of chunks in the output file differs from the number of chunks in the orignal file.", context);
855  throw Failure();
856  }
857  }
858  } else {
859  updateOffsets(origMediaDataOffsets, newMediaDataOffsets);
860  }
861  }
862 
863  updatePercentage(100.0);
864 
865  // flush output stream
866  outputStream.flush();
867 
868  // handle errors (which might have been occured after renaming/creating backup file)
869  } catch(...) {
870  BackupHelper::handleFailureAfterFileModified(fileInfo(), backupPath, outputStream, backupStream, context);
871  }
872 }
873 
886 void Mp4Container::updateOffsets(const std::vector<int64> &oldMdatOffsets, const std::vector<int64> &newMdatOffsets)
887 {
888  // do NOT invalidate the status here since this method is internally called by internalMakeFile(), just update the status
889  updateStatus("Updating chunk offset table for each track ...");
890  const string context("updating MP4 container chunk offset table");
891  if(!firstElement()) {
892  addNotification(NotificationType::Critical, "No MP4 atoms could be found.", context);
893  throw InvalidDataException();
894  }
895  // update "base-data-offset-present" of "tfhd"-atom (NOT tested properly)
896  try {
897  for(Mp4Atom *moofAtom = firstElement()->siblingById(Mp4AtomIds::MovieFragment, false);
898  moofAtom; moofAtom = moofAtom->siblingById(Mp4AtomIds::MovieFragment, false)) {
899  moofAtom->parse();
900  try {
901  for(Mp4Atom *trafAtom = moofAtom->childById(Mp4AtomIds::TrackFragment); trafAtom;
902  trafAtom = trafAtom->siblingById(Mp4AtomIds::TrackFragment, false)) {
903  trafAtom->parse();
904  int tfhdAtomCount = 0;
905  for(Mp4Atom *tfhdAtom = trafAtom->childById(Mp4AtomIds::TrackFragmentHeader); tfhdAtom;
906  tfhdAtom = tfhdAtom->siblingById(Mp4AtomIds::TrackFragmentHeader, false)) {
907  tfhdAtom->parse();
908  ++tfhdAtomCount;
909  if(tfhdAtom->dataSize() >= 8) {
910  stream().seekg(tfhdAtom->dataOffset() + 1);
911  uint32 flags = reader().readUInt24BE();
912  if(flags & 1) {
913  if(tfhdAtom->dataSize() >= 16) {
914  stream().seekg(4, ios_base::cur); // skip track ID
915  uint64 off = reader().readUInt64BE();
916  for(auto iOld = oldMdatOffsets.cbegin(), iNew = newMdatOffsets.cbegin(), end = oldMdatOffsets.cend();
917  iOld != end; ++iOld, ++iNew) {
918  if(off >= static_cast<uint64>(*iOld)) {
919  off += (*iNew - *iOld);
920  stream().seekp(tfhdAtom->dataOffset() + 8);
921  writer().writeUInt64BE(off);
922  break;
923  }
924  }
925  } else {
926  addNotification(NotificationType::Warning, "tfhd atom (denoting base-data-offset-present) is truncated.", context);
927  }
928  }
929  } else {
930  addNotification(NotificationType::Warning, "tfhd atom is truncated.", context);
931  }
932  }
933  switch(tfhdAtomCount) {
934  case 0:
935  addNotification(NotificationType::Warning, "traf atom doesn't contain mandatory tfhd atom.", context);
936  break;
937  case 1:
938  break;
939  default:
940  addNotification(NotificationType::Warning, "traf atom stores multiple tfhd atoms but it should only contain exactly one tfhd atom.", context);
941  }
942  }
943  } catch(const Failure &) {
944  addNotification(NotificationType::Critical, "Unable to parse childs of top-level atom moof.", context);
945  }
946  }
947  } catch(const Failure &) {
948  addNotification(NotificationType::Critical, "Unable to parse top-level atom moof.", context);
949  }
950  // update each track
951  for(auto &track : tracks()) {
952  if(isAborted()) {
954  }
955  if(!track->isHeaderValid()) {
956  try {
957  track->parseHeader();
958  } catch(const Failure &) {
959  addNotification(NotificationType::Warning, "The chunk offsets of track " % track->name() + " couldn't be updated because the track seems to be invalid..", context);
960  throw;
961  }
962  }
963  if(track->isHeaderValid()) {
964  try {
965  track->updateChunkOffsets(oldMdatOffsets, newMdatOffsets);
966  } catch(const Failure &) {
967  addNotification(NotificationType::Warning, "The chunk offsets of track " % track->name() + " couldn't be updated.", context);
968  throw;
969  }
970  }
971  }
972 }
973 
974 }
IoUtilities::BinaryWriter & writer()
Returns the related BinaryWriter.
implementationType * childById(const identifierType &id)
Returns the first child with the specified id.
uint64 startOffset() const
Returns the start offset in the related stream.
Mp4Atom * firstElement() const
Returns the first element of the file if available; otherwiese returns nullptr.
const std::string name() const
Returns the track name if known; otherwise returns an empty string.
void invalidateStatus()
Invalidates the current status.
uint64 dataOffset() const
Returns the data offset of the element in the related stream.
bool isAborted() const
Returns an indication whether the current operation should be aborted.
This exception is thrown when the an operation is invoked that has not been implemented yet...
Definition: exceptions.h:59
implementationType * nextSibling()
Returns the next sibling of the element.
ChronoUtilities::TimeSpan m_duration
MediaFileInfo & fileInfo() const
Returns the related file info.
std::vector< uint64 > readChunkSizes()
Reads the chunk sizes from the stsz (sample sizes) and stsc (samples per chunk) atom.
Definition: mp4track.cpp:407
uint64 version() const
Returns the version if known; otherwise returns 0.
Mp4TagMaker prepareMaking()
Prepares making.
Definition: mp4tag.cpp:345
Implementation of Media::AbstractTrack for the MP4 container.
Definition: mp4track.h:119
std::istream & inputStream()
Returns the associated input stream.
The GenericContainer class helps parsing header, track, tag and chapter information of a file...
void discardBuffer()
Discards buffered data.
ElementPosition determineIndexPosition() const
Determines the position of the index.
TAG_PARSER_EXPORT void createBackupFile(const std::string &originalPath, std::string &backupPath, IoUtilities::NativeFileStream &originalStream, IoUtilities::NativeFileStream &backupStream)
void parse()
Parses the header information of the element which is read from the related stream at the start offse...
const ChronoUtilities::DateTime & modificationTime() const
Returns the time of the last modification if known; otherwise returns a DateTime of zero ticks...
const ChronoUtilities::TimeSpan & duration() const
Returns the duration if known; otherwise returns a TimeSpan of zero ticks.
TAG_PARSER_EXPORT void handleFailureAfterFileModified(MediaFileInfo &mediaFileInfo, const std::string &backupPath, IoUtilities::NativeFileStream &outputStream, IoUtilities::NativeFileStream &backupStream, const std::string &context="making file")
uint64 totalSize() const
Returns the total size of the element.
STL namespace.
The exception that is thrown when an operation has been stopped and thus not successfully completed b...
Definition: exceptions.h:43
void addNotification(const Notification &notification)
This protected method is meant to be called by the derived class to add a notification.
void reportPathChanged(const std::string &newPath)
Call this function to report that the path changed.
ChronoUtilities::DateTime m_creationTime
bool isHeaderValid() const
Returns an indication whether the track header is valid.
uint64 size() const
Returns size of the current file in bytes.
bool forceIndexPosition() const
Returns whether indexPosition() is forced.
void internalParseTags()
Internally called to parse the tags.
void updatePercentage(double percentage)
This method is meant to be called by the derived class to report updated progress percentage only...
ChronoUtilities::DateTime m_modificationTime
size_t minPadding() const
Returns the minimum padding to be written before the data blocks when applying changes.
bool isForcingRewrite() const
Returns whether forcing rewriting (when applying changes) is enabled.
void setStream(std::iostream &stream)
Sets the related stream.
uint64 id() const
Returns the track ID if known; otherwise returns 0.
const std::string & saveFilePath() const
Returns the "save file path" which has been set using setSaveFilePath().
void close()
A possibly opened std::fstream will be closed.
IoUtilities::NativeFileStream & stream()
Returns the std::fstream for the current instance.
Definition: basicfileinfo.h:80
void setSaveFilePath(const std::string &saveFilePath)
Sets the "save file path".
void makeTrack()
Makes the track entry ("trak"-atom) for the track.
Definition: mp4track.cpp:926
Contains utility classes helping to read and write streams.
uint64 startOffset() const
Returns the start offset in the related stream.
The exception that is thrown when the data to be parsed or to be made seems invalid and therefore can...
Definition: exceptions.h:27
size_t preferredPadding() const
Returns the padding to be written before the data block when applying changes and the file needs to b...
Implementation of Media::Tag for the MP4 container.
Definition: mp4tag.h:90
implementationType * siblingById(const identifierType &id, bool includeThis=false)
Returns the first sibling with the specified id.
bool isHeaderParsed() const
Returns an indication whether the header has been parsed yet.
std::vector< uint64 > readChunkOffsets()
Reads the chunk offsets from the stco atom.
Definition: mp4track.cpp:133
ElementPosition determineTagPosition() const
Determines the position of the tags inside the file.
implementationType * subelementByPath(const std::initializer_list< identifierType > &path)
Returns the sub element for the specified path.
implementationType * firstChild()
Returns the first child of the element.
void reset()
Discards all parsing results.
const identifierType & id() const
Returns the element ID.
ElementPosition indexPosition() const
Returns the position (in the output file) where the index is written when applying changes...
The class inherits from std::exception and serves as base class for exceptions thrown by the elements...
Definition: exceptions.h:11
void reportSizeChanged(uint64 newSize)
Call this function to report that the size changed.
uint32 chunkCount() const
Returns the number of chunks denoted by the stco atom.
Definition: mp4track.h:223
size_t maxPadding() const
Returns the maximum padding to be written before the data blocks when applying changes.
The MediaFileInfo class allows to read and write tag information providing a container/tag format ind...
Definition: mediafileinfo.h:52
void makeBuffer()
Buffers the element (header and data).
void copyEntirely(std::ostream &targetStream)
Writes the entire element including all childs to the specified targetStream.
The Mp4Atom class helps to parse MP4 files.
Definition: mp4atom.h:57
void internalMakeFile()
Internally called to make the file.
void internalParseHeader()
Internally called to parse the header.
bool forceTagPosition() const
Returns whether tagPosition() is forced.
IoUtilities::BinaryReader & reader()
Returns the related BinaryReader.
const ChronoUtilities::DateTime & creationTime() const
Returns the creation time if known; otherwise returns a DateTime of zero ticks.
void copyBuffer(std::ostream &targetStream)
Copies buffered data to targetStream.
uint64 requiredSize() const
Returns the number of bytes written when calling makeTrack().
Definition: mp4track.cpp:954
void updateChunkOffsets(const std::vector< int64 > &oldMdatOffsets, const std::vector< int64 > &newMdatOffsets)
Updates the chunk offsets of the track.
Definition: mp4track.cpp:767
The exception that is thrown when the data to be parsed holds no parsable information.
Definition: exceptions.h:19
ElementPosition tagPosition() const
Returns the position (in the output file) where the tag information is written when applying changes...
std::string idToString() const
Converts the specified atom ID to a printable string.
Definition: mp4atom.h:87
void updateStatus(const std::string &status)
This method is meant to be called by the derived class to report updated status information.
Contains all classes and functions of the TagInfo library.
Definition: exceptions.h:9
static void makeHeader(uint64 size, uint32 id, IoUtilities::BinaryWriter &writer)
Writes an MP4 atom header to the specified stream.
Definition: mp4atom.cpp:157
void internalParseTracks()
Internally called to parse the tracks.
void setInputStream(std::istream &stream)
Assigns an other input stream.
const std::vector< std::unique_ptr< Mp4Track > > & tracks() const
Returns the tracks of the file.
std::iostream & stream()
Returns the related stream.
void addNotifications(const StatusProvider &from)
This protected method is meant to be called by the derived class to add all notifications from anothe...
void parseTracks()
Parses the tracks of the file if not parsed yet.
void forwardStatusUpdateCalls(StatusProvider *other=nullptr)
Forwards all status updates calls to the specified statusProvider.
void parseHeader()
Parses technical information about the track from the header.
void reset()
Discards all parsing results.
static void addHeaderSize(uint64 &dataSize)
Adds the header size to the specified data size.
Definition: mp4atom.h:95