Tag Parser  6.4.0
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*/;
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 (currently not used)
338  //userDataAtom = movieAtom->childById(Mp4AtomIds::UserData);
339 
340  } catch (const NotImplementedException &) {
341  throw;
342 
343  } catch (const Failure &) {
344  // can't ignore parsing errors here
345  addNotification(NotificationType::Critical, "Unable to parse the overall atom structure of the source file.", context);
346  throw InvalidDataException();
347  }
348 
349  if(isAborted()) {
351  }
352 
353  // calculate sizes
354  // -> size of tags
355  vector<Mp4TagMaker> tagMaker;
356  uint64 tagsSize = 0;
357  tagMaker.reserve(m_tags.size());
358  for(auto &tag : m_tags) {
359  try {
360  tagMaker.emplace_back(tag->prepareMaking());
361  tagsSize += tagMaker.back().requiredSize();
362  } catch(const Failure &) {
363  // nothing to do because notifications will be added anyways
364  }
366  }
367 
368  // -> size of movie atom (contains track and tag information)
369  movieAtomSize = userDataAtomSize = 0;
370  try {
371  // add size of children
372  for(level0Atom = movieAtom; level0Atom; level0Atom = level0Atom->siblingById(Mp4AtomIds::Movie)) {
373  for(level1Atom = level0Atom->firstChild(); level1Atom; level1Atom = level1Atom->nextSibling()) {
374  level1Atom->parse();
375  switch(level1Atom->id()) {
377  try {
378  for(level2Atom = level1Atom->firstChild(); level2Atom; level2Atom = level2Atom->nextSibling()) {
379  level2Atom->parse();
380  switch(level2Atom->id()) {
381  case Mp4AtomIds::Meta:
382  // ignore meta data here; it is added separately
383  break;
384  default:
385  // add size of unknown childs of the user data atom
386  userDataAtomSize += level2Atom->totalSize();
387  level2Atom->makeBuffer();
388  }
389  }
390  } catch(const Failure &) {
391  // invalid children might be ignored as not mandatory
392  addNotification(NotificationType::Critical, "Unable to parse the children of \"udta\"-atom of the source file; ignoring them.", context);
393  }
394  break;
395  case Mp4AtomIds::Track:
396  // ignore track atoms here; they are added separately
397  break;
398  default:
399  // add size of unknown childs of the movie atom
400  movieAtomSize += level1Atom->totalSize();
401  level1Atom->makeBuffer();
402  }
403  }
404  }
405 
406  // add size of meta data
407  if(userDataAtomSize += tagsSize) {
408  Mp4Atom::addHeaderSize(userDataAtomSize);
409  movieAtomSize += userDataAtomSize;
410  }
411 
412  // add size of track atoms
413  for(const auto &track : tracks()) {
414  movieAtomSize += track->requiredSize();
415  }
416 
417  // add header size
418  Mp4Atom::addHeaderSize(movieAtomSize);
419  } catch(const Failure &) {
420  // can't ignore parsing errors here
421  addNotification(NotificationType::Critical, "Unable to parse the children of \"moov\"-atom of the source file.", context);
422  throw InvalidDataException();
423  }
424 
425  if(isAborted()) {
427  }
428 
429  // check whether there are atoms to be voided after movie next sibling (only relevant when not rewriting)
430  if(!rewriteRequired) {
431  newPaddingEnd = 0;
432  uint64 currentSum = 0;
433  for(Mp4Atom *level0Atom = firstMediaDataAtom; level0Atom; level0Atom = level0Atom->nextSibling()) {
434  level0Atom->parse();
435  switch(level0Atom->id()) {
438  // must void these if they occur "between" the media data
439  currentSum += level0Atom->totalSize();
440  break;
441  default:
442  newPaddingEnd += currentSum;
443  currentSum = 0;
444  lastAtomToBeWritten = level0Atom;
445  }
446  }
447  }
448 
449  // calculate padding if no rewrite is required; otherwise use the preferred padding
450 calculatePadding:
451  if(rewriteRequired) {
452  newPadding = (fileInfo().preferredPadding() && fileInfo().preferredPadding() < 8 ? 8 : fileInfo().preferredPadding());
453  } else {
454  // file type atom
455  currentOffset = fileTypeAtom->totalSize();
456 
457  // progressive download information atom
458  if(progressiveDownloadInfoAtom) {
459  currentOffset += progressiveDownloadInfoAtom->totalSize();
460  }
461 
462  // if writing tags before data: movie atom (contains tag)
463  switch(newTagPos) {
466  currentOffset += movieAtomSize;
467  break;
468  default:
469  ;
470  }
471 
472  // check whether there is sufficiant space before the next atom
473  if(!(rewriteRequired = firstMediaDataAtom && currentOffset > firstMediaDataAtom->startOffset())) {
474  // there is sufficiant space
475  // -> check whether the padding matches specifications
476  // min padding: says "at least ... byte should be reserved to prepend further tag info", so the padding at the end
477  // shouldn't be tanken into account (it can't be used to prepend further tag info)
478  // max padding: says "do not waste more than ... byte", so here all padding should be taken into account
479  newPadding = firstMediaDataAtom->startOffset() - currentOffset;
480  rewriteRequired = (newPadding > 0 && newPadding < 8) || newPadding < fileInfo().minPadding() || (newPadding + newPaddingEnd) > fileInfo().maxPadding();
481  }
482  if(rewriteRequired) {
483  // can't put the tags before media data
484  if(!firstMovieFragmentAtom && !fileInfo().forceTagPosition() && !fileInfo().forceIndexPosition() && newTagPos != ElementPosition::AfterData) {
485  // writing tag before media data is not forced, its not a DASH file and tags aren't already at the end
486  // -> try to put the tags at the end
487  newTagPos = ElementPosition::AfterData;
488  rewriteRequired = false;
489  } else {
490  // writing tag before media data is forced -> rewrite the file
491  // when rewriting anyways, ensure the preferred tag position is used
492  newTagPos = initialNewTagPos == ElementPosition::Keep ? currentTagPos : initialNewTagPos;
493  }
494  // in any case: recalculate padding
495  goto calculatePadding;
496  } else {
497  // tags can be put before the media data
498  // -> ensure newTagPos is not ElementPosition::Keep
499  if(newTagPos == ElementPosition::Keep) {
500  newTagPos = ElementPosition::BeforeData;
501  }
502  }
503  }
504 
505  if(isAborted()) {
507  }
508 
509  // setup stream(s) for writing
510  // -> update status
511  updateStatus("Preparing streams ...");
512 
513  // -> define variables needed to handle output stream and backup stream (required when rewriting the file)
514  string backupPath;
515  NativeFileStream &outputStream = fileInfo().stream();
516  NativeFileStream backupStream; // create a stream to open the backup/original file for the case rewriting the file is required
517  BinaryWriter outputWriter(&outputStream);
518 
519  if(rewriteRequired) {
520  if(fileInfo().saveFilePath().empty()) {
521  // move current file to temp dir and reopen it as backupStream, recreate original file
522  try {
523  BackupHelper::createBackupFile(fileInfo().path(), backupPath, outputStream, backupStream);
524  // recreate original file, define buffer variables
525  outputStream.open(fileInfo().path(), ios_base::out | ios_base::binary | ios_base::trunc);
526  } catch(...) {
527  const char *what = catchIoFailure();
528  addNotification(NotificationType::Critical, "Creation of temporary file (to rewrite the original file) failed.", context);
529  throwIoFailure(what);
530  }
531  } else {
532  // open the current file as backupStream and create a new outputStream at the specified "save file path"
533  try {
534  backupStream.exceptions(ios_base::badbit | ios_base::failbit);
535  backupStream.open(fileInfo().path(), ios_base::in | ios_base::binary);
536  fileInfo().close();
537  outputStream.open(fileInfo().saveFilePath(), ios_base::out | ios_base::binary | ios_base::trunc);
538  } catch(...) {
539  const char *what = catchIoFailure();
540  addNotification(NotificationType::Critical, "Opening streams to write output file failed.", context);
541  throwIoFailure(what);
542  }
543  }
544 
545  // set backup stream as associated input stream since we need the original elements to write the new file
546  setStream(backupStream);
547 
548  // TODO: reduce code duplication
549 
550  } else { // !rewriteRequired
551  // ensure everything to make track atoms is buffered before altering the source file
552  for(const auto &track : tracks()) {
554  }
555 
556  // reopen original file to ensure it is opened for writing
557  try {
558  fileInfo().close();
559  outputStream.open(fileInfo().path(), ios_base::in | ios_base::out | ios_base::binary);
560  } catch(...) {
561  const char *what = catchIoFailure();
562  addNotification(NotificationType::Critical, "Opening the file with write permissions failed.", context);
563  throwIoFailure(what);
564  }
565  }
566 
567  // start actual writing
568  try {
569  // write header
570  updateStatus("Writing header and tags ...");
571  // -> make file type atom
572  fileTypeAtom->copyBuffer(outputStream);
573  fileTypeAtom->discardBuffer();
574  // -> make progressive download info atom
575  if(progressiveDownloadInfoAtom) {
576  progressiveDownloadInfoAtom->copyBuffer(outputStream);
577  progressiveDownloadInfoAtom->discardBuffer();
578  }
579 
580  // set input/output streams of each track
581  for(auto &track : tracks()) {
582  // ensure the track reads from the original file
583  if(&track->inputStream() == &outputStream) {
584  track->setInputStream(backupStream);
585  }
586  // ensure the track writes to the output file
587  track->setOutputStream(outputStream);
588  }
589 
590  // write movie atom / padding and media data
591  for(byte pass = 0; pass != 2; ++pass) {
592  if(newTagPos == (pass ? ElementPosition::AfterData : ElementPosition::BeforeData)) {
593  // write movie atom
594  // -> write movie atom header
595  Mp4Atom::makeHeader(movieAtomSize, Mp4AtomIds::Movie, outputWriter);
596 
597  // -> write track atoms
598  for(auto &track : tracks()) {
599  track->makeTrack();
600  }
601 
602  // -> write other movie atom children
603  for(level0Atom = movieAtom; level0Atom; level0Atom = level0Atom->siblingById(Mp4AtomIds::Movie)) {
604  for(level1Atom = level0Atom->firstChild(); level1Atom; level1Atom = level1Atom->nextSibling()) {
605  switch(level1Atom->id()) {
607  case Mp4AtomIds::Track:
608  // track and user data atoms are written separately
609  break;
610  default:
611  // write buffered data
612  level1Atom->copyBuffer(outputStream);
613  level1Atom->discardBuffer();
614  }
615  }
616  }
617 
618  // -> write user data atom
619  if(userDataAtomSize) {
620  // writer user data atom header
621  Mp4Atom::makeHeader(userDataAtomSize, Mp4AtomIds::UserData, outputWriter);
622 
623  // write other children of user data atom
624  for(level0Atom = movieAtom; level0Atom; level0Atom = level0Atom->siblingById(Mp4AtomIds::Movie)) {
625  for(level1Atom = level0Atom->childById(Mp4AtomIds::UserData); level1Atom; level1Atom = level1Atom->siblingById(Mp4AtomIds::UserData)) {
626  for(level2Atom = level1Atom->firstChild(); level2Atom; level2Atom = level2Atom->nextSibling()) {
627  switch(level2Atom->id()) {
628  case Mp4AtomIds::Meta:
629  break;
630  default:
631  // write buffered data
632  level2Atom->copyBuffer(outputStream);
633  level2Atom->discardBuffer();
634  }
635  }
636  }
637  }
638 
639  // write meta atom
640  for(auto &maker : tagMaker) {
641  maker.make(outputStream);
642  }
643  }
644 
645  } else {
646  // write padding
647  if(newPadding) {
648  // write free atom header
649  if(newPadding < 0xFFFFFFFF) {
650  outputWriter.writeUInt32BE(newPadding);
651  outputWriter.writeUInt32BE(Mp4AtomIds::Free);
652  newPadding -= 8;
653  } else {
654  outputWriter.writeUInt32BE(1);
655  outputWriter.writeUInt32BE(Mp4AtomIds::Free);
656  outputWriter.writeUInt64BE(newPadding);
657  newPadding -= 16;
658  }
659 
660  // write zeroes
661  for(; newPadding; --newPadding) {
662  outputStream.put(0);
663  }
664  }
665 
666  // write media data
667  if(rewriteRequired) {
668  for(level0Atom = firstMediaDataAtom; level0Atom; level0Atom = level0Atom->nextSibling()) {
669  level0Atom->parse();
670  switch(level0Atom->id()) {
673  break;
675  if(writeChunkByChunk) {
676  // write actual data separately when writing chunk-by-chunk
677  break;
678  } else {
679  // store media data offsets when not writing chunk-by-chunk to be able to update chunk offset table
680  origMediaDataOffsets.push_back(level0Atom->startOffset());
681  newMediaDataOffsets.push_back(outputStream.tellp());
682  }
683  default:
684  // update status
685  updateStatus("Writing atom: " + level0Atom->idToString());
686  // copy atom entirely and forward status update calls
687  level0Atom->forwardStatusUpdateCalls(this);
688  level0Atom->copyEntirely(outputStream);
689  }
690  }
691 
692  // when writing chunk-by-chunk write media data now
693  if(writeChunkByChunk) {
694  // read chunk offset and chunk size table from the old file which are required to get chunks
695  updateStatus("Reading chunk offsets and sizes from the original file ...");
696  trackInfos.reserve(trackCount);
697  uint64 totalChunkCount = 0;
698  uint64 totalMediaDataSize = 0;
699  for(auto &track : tracks()) {
700  if(isAborted()) {
702  }
703 
704  // emplace information
705  trackInfos.emplace_back(&track->inputStream(), track->readChunkOffsetsSupportingFragments(fileInfo().isForcingFullParse()), track->readChunkSizes());
706 
707  // check whether the chunks could be parsed correctly
708  const vector<uint64> &chunkOffsetTable = get<1>(trackInfos.back());
709  const vector<uint64> &chunkSizesTable = get<2>(trackInfos.back());
710  if(track->chunkCount() != chunkOffsetTable.size() || track->chunkCount() != chunkSizesTable.size()) {
711  addNotification(NotificationType::Critical, "Chunks of track " % numberToString<uint64, string>(track->id()) + " could not be parsed correctly.", context);
712  }
713 
714  // increase total chunk count and size
715  totalChunkCount += track->chunkCount();
716  totalMediaDataSize += accumulate(chunkSizesTable.cbegin(), chunkSizesTable.cend(), totalMediaDataSize);
717  }
718 
719  // write media data chunk-by-chunk
720  // -> write header of media data atom
721  Mp4Atom::addHeaderSize(totalMediaDataSize);
722  Mp4Atom::makeHeader(totalMediaDataSize, Mp4AtomIds::MediaData, outputWriter);
723 
724  // -> copy chunks
725  CopyHelper<0x2000> copyHelper;
726  uint64 chunkIndexWithinTrack = 0, totalChunksCopied = 0;
727  bool anyChunksCopied;
728  do {
729  if(isAborted()) {
731  }
732 
733  // copy a chunk from each track
734  anyChunksCopied = false;
735  for(size_t trackIndex = 0; trackIndex < trackCount; ++trackIndex) {
736  // get source stream and tables for current track
737  auto &trackInfo = trackInfos[trackIndex];
738  istream &sourceStream = *get<0>(trackInfo);
739  vector<uint64> &chunkOffsetTable = get<1>(trackInfo);
740  const vector<uint64> &chunkSizesTable = get<2>(trackInfo);
741 
742  // still chunks to be copied (of this track)?
743  if(chunkIndexWithinTrack < chunkOffsetTable.size() && chunkIndexWithinTrack < chunkSizesTable.size()) {
744  // copy chunk, update entry in chunk offset table
745  sourceStream.seekg(chunkOffsetTable[chunkIndexWithinTrack]);
746  chunkOffsetTable[chunkIndexWithinTrack] = outputStream.tellp();
747  copyHelper.copy(sourceStream, outputStream, chunkSizesTable[chunkIndexWithinTrack]);
748 
749  // update counter / status
750  anyChunksCopied = true;
751  ++totalChunksCopied;
752  }
753  }
754 
755  // incrase chunk index within track, update progress percentage
756  if(!(++chunkIndexWithinTrack % 10)) {
757  updatePercentage(static_cast<double>(totalChunksCopied) / totalChunkCount);
758  }
759 
760  } while(anyChunksCopied);
761  }
762 
763  } else {
764  // can't just skip next movie sibling
765  for(Mp4Atom *level0Atom = firstMediaDataAtom; level0Atom; level0Atom = level0Atom->nextSibling()) {
766  level0Atom->parse();
767  switch(level0Atom->id()) {
769  // must void these if they occur "between" the media data
770  outputStream.seekp(4, ios_base::cur);
771  outputWriter.writeUInt32BE(Mp4AtomIds::Free);
772  break;
773  default:
774  outputStream.seekp(level0Atom->totalSize(), ios_base::cur);
775  }
776  if(level0Atom == lastAtomToBeWritten) {
777  break;
778  }
779  }
780  }
781  }
782  }
783 
784  // reparse what is written so far
785  updateStatus("Reparsing output file ...");
786  if(rewriteRequired) {
787  // report new size
788  fileInfo().reportSizeChanged(outputStream.tellp());
789  // "save as path" is now the regular path
790  if(!fileInfo().saveFilePath().empty()) {
791  fileInfo().reportPathChanged(fileInfo().saveFilePath());
792  fileInfo().setSaveFilePath(string());
793  }
794  // the outputStream needs to be reopened to be able to read again
795  outputStream.close();
796  outputStream.open(fileInfo().path(), ios_base::in | ios_base::out | ios_base::binary);
797  setStream(outputStream);
798  } else {
799  const auto newSize = static_cast<uint64>(outputStream.tellp());
800  if(newSize < fileInfo().size()) {
801  // file is smaller after the modification -> truncate
802  // -> close stream before truncating
803  outputStream.close();
804  // -> truncate file
805  if(truncate(fileInfo().path().c_str(), newSize) == 0) {
806  fileInfo().reportSizeChanged(newSize);
807  } else {
808  addNotification(NotificationType::Critical, "Unable to truncate the file.", context);
809  }
810  // -> reopen the stream again
811  outputStream.open(fileInfo().path(), ios_base::in | ios_base::out | ios_base::binary);
812  } else {
813  // file is longer after the modification -> just report new size
814  fileInfo().reportSizeChanged(newSize);
815  }
816  }
817 
818  reset();
819  try {
820  parseTracks();
821  } catch(const Failure &) {
822  addNotification(NotificationType::Critical, "Unable to reparse the header of the new file.", context);
823  throw;
824  }
825 
826  if(rewriteRequired) {
827  // check whether track count of new file equals track count of old file
828  if(trackCount != tracks().size()) {
830  argsToString("Unable to update chunk offsets (\"stco\"-atom): Number of tracks in the output file (",
831  tracks().size(),
832  ") differs from the number of tracks in the original file (",
833  trackCount,
834  ")."), context);
835  throw Failure();
836  }
837 
838  // update chunk offset table
839  if(writeChunkByChunk) {
840  updateStatus("Updating chunk offset table for each track ...");
841  for(size_t trackIndex = 0; trackIndex != trackCount; ++trackIndex) {
842  const auto &track = tracks()[trackIndex];
843  const auto &chunkOffsetTable = get<1>(trackInfos[trackIndex]);
844  if(track->chunkCount() == chunkOffsetTable.size()) {
845  track->updateChunkOffsets(chunkOffsetTable);
846  } else {
847  addNotification(NotificationType::Critical, argsToString("Unable to update chunk offsets of track ", (trackIndex + 1), ": Number of chunks in the output file differs from the number of chunks in the orignal file."), context);
848  throw Failure();
849  }
850  }
851  } else {
852  updateOffsets(origMediaDataOffsets, newMediaDataOffsets);
853  }
854  }
855 
856  updatePercentage(100.0);
857 
858  // flush output stream
859  outputStream.flush();
860 
861  // handle errors (which might have been occured after renaming/creating backup file)
862  } catch(...) {
863  BackupHelper::handleFailureAfterFileModified(fileInfo(), backupPath, outputStream, backupStream, context);
864  }
865 }
866 
879 void Mp4Container::updateOffsets(const std::vector<int64> &oldMdatOffsets, const std::vector<int64> &newMdatOffsets)
880 {
881  // do NOT invalidate the status here since this method is internally called by internalMakeFile(), just update the status
882  updateStatus("Updating chunk offset table for each track ...");
883  const string context("updating MP4 container chunk offset table");
884  if(!firstElement()) {
885  addNotification(NotificationType::Critical, "No MP4 atoms could be found.", context);
886  throw InvalidDataException();
887  }
888  // update "base-data-offset-present" of "tfhd"-atom (NOT tested properly)
889  try {
890  for(Mp4Atom *moofAtom = firstElement()->siblingById(Mp4AtomIds::MovieFragment, false);
891  moofAtom; moofAtom = moofAtom->siblingById(Mp4AtomIds::MovieFragment, false)) {
892  moofAtom->parse();
893  try {
894  for(Mp4Atom *trafAtom = moofAtom->childById(Mp4AtomIds::TrackFragment); trafAtom;
895  trafAtom = trafAtom->siblingById(Mp4AtomIds::TrackFragment, false)) {
896  trafAtom->parse();
897  int tfhdAtomCount = 0;
898  for(Mp4Atom *tfhdAtom = trafAtom->childById(Mp4AtomIds::TrackFragmentHeader); tfhdAtom;
899  tfhdAtom = tfhdAtom->siblingById(Mp4AtomIds::TrackFragmentHeader, false)) {
900  tfhdAtom->parse();
901  ++tfhdAtomCount;
902  if(tfhdAtom->dataSize() >= 8) {
903  stream().seekg(tfhdAtom->dataOffset() + 1);
904  uint32 flags = reader().readUInt24BE();
905  if(flags & 1) {
906  if(tfhdAtom->dataSize() >= 16) {
907  stream().seekg(4, ios_base::cur); // skip track ID
908  uint64 off = reader().readUInt64BE();
909  for(auto iOld = oldMdatOffsets.cbegin(), iNew = newMdatOffsets.cbegin(), end = oldMdatOffsets.cend();
910  iOld != end; ++iOld, ++iNew) {
911  if(off >= static_cast<uint64>(*iOld)) {
912  off += (*iNew - *iOld);
913  stream().seekp(tfhdAtom->dataOffset() + 8);
914  writer().writeUInt64BE(off);
915  break;
916  }
917  }
918  } else {
919  addNotification(NotificationType::Warning, "tfhd atom (denoting base-data-offset-present) is truncated.", context);
920  }
921  }
922  } else {
923  addNotification(NotificationType::Warning, "tfhd atom is truncated.", context);
924  }
925  }
926  switch(tfhdAtomCount) {
927  case 0:
928  addNotification(NotificationType::Warning, "traf atom doesn't contain mandatory tfhd atom.", context);
929  break;
930  case 1:
931  break;
932  default:
933  addNotification(NotificationType::Warning, "traf atom stores multiple tfhd atoms but it should only contain exactly one tfhd atom.", context);
934  }
935  }
936  } catch(const Failure &) {
937  addNotification(NotificationType::Critical, "Unable to parse childs of top-level atom moof.", context);
938  }
939  }
940  } catch(const Failure &) {
941  addNotification(NotificationType::Critical, "Unable to parse top-level atom moof.", context);
942  }
943  // update each track
944  for(auto &track : tracks()) {
945  if(isAborted()) {
947  }
948  if(!track->isHeaderValid()) {
949  try {
950  track->parseHeader();
951  } catch(const Failure &) {
952  addNotification(NotificationType::Warning, "The chunk offsets of track " % track->name() + " couldn't be updated because the track seems to be invalid..", context);
953  throw;
954  }
955  }
956  if(track->isHeaderValid()) {
957  try {
958  track->updateChunkOffsets(oldMdatOffsets, newMdatOffsets);
959  } catch(const Failure &) {
960  addNotification(NotificationType::Warning, "The chunk offsets of track " % track->name() + " couldn't be updated.", context);
961  throw;
962  }
963  }
964  }
965 }
966 
967 }
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:417
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...
void setOutputStream(std::ostream &stream)
Assigns another output stream.
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 bufferTrackAtoms()
Buffers all atoms required by the makeTrack() method.
Definition: mp4track.cpp:937
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:1025
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.
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:53
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:973
void updateChunkOffsets(const std::vector< int64 > &oldMdatOffsets, const std::vector< int64 > &newMdatOffsets)
Updates the chunk offsets of the track.
Definition: mp4track.cpp:777
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:158
void internalParseTracks()
Internally called to parse the tracks.
void setInputStream(std::istream &stream)
Assigns another 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:101
std::vector< uint64 > readChunkOffsetsSupportingFragments(bool parseFragments=false)
Reads the chunk offsets from the stco atom and fragments if parseFragments is true.
Definition: mp4track.cpp:148