update for new memory API
[platform/upstream/gst-plugins-good.git] / gst / isomp4 / atomsrecovery.c
1 /* Quicktime muxer plugin for GStreamer
2  * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 /*
20  * Unless otherwise indicated, Source Code is licensed under MIT license.
21  * See further explanation attached in License Statement (distributed in the file
22  * LICENSE).
23  *
24  * Permission is hereby granted, free of charge, to any person obtaining a copy of
25  * this software and associated documentation files (the "Software"), to deal in
26  * the Software without restriction, including without limitation the rights to
27  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
28  * of the Software, and to permit persons to whom the Software is furnished to do
29  * so, subject to the following conditions:
30  *
31  * The above copyright notice and this permission notice shall be included in all
32  * copies or substantial portions of the Software.
33  *
34  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
36  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
37  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
38  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
39  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
40  * SOFTWARE.
41  */
42
43 /**
44  * This module contains functions for serializing partial information from
45  * a mux in progress (by qtmux elements). This enables reconstruction of the
46  * moov box if a crash happens and thus recovering the movie file.
47  *
48  * Usage:
49  * 1) pipeline: ...yourelements ! qtmux moov-recovery-file=path.mrf ! \
50  * filesink location=moovie.mov
51  *
52  * 2) CRASH!
53  *
54  * 3) gst-launch qtmoovrecover recovery-input=path.mrf broken-input=moovie.mov \
55         fixed-output=recovered.mov
56  *
57  * 4) (Hopefully) enjoy recovered.mov.
58  *
59  * --- Recovery file layout ---
60  * 1) Version (a guint16)
61  * 2) Prefix atom (if present)
62  * 3) ftyp atom
63  * 4) MVHD atom (without timescale/duration set)
64  * 5) moovie timescale
65  * 6) number of traks
66  * 7) list of trak atoms (stbl data is ignored, except for the stsd atom)
67  * 8) Buffers metadata (metadata that is relevant to the container)
68  *    Buffers metadata are stored in the order they are added to the mdat,
69  *    each entre has a fixed size and is stored in BE. booleans are stored
70  *    as a single byte where 0 means false, otherwise is true.
71  *   Metadata:
72  *   - guint32   track_id;
73  *   - guint32   nsamples;
74  *   - guint32   delta;
75  *   - guint32   size;
76  *   - guint64   chunk_offset;
77  *   - gboolean  sync;
78  *   - gboolean  do_pts;
79  *   - guint64   pts_offset; (always present, ignored if do_pts is false)
80  *
81  * The mdat file might contain ftyp and then mdat, in case this is the faststart
82  * temporary file there is no ftyp and no mdat header, only the buffers data.
83  *
84  * Notes about recovery file layout: We still don't store tags nor EDTS data.
85  *
86  * IMPORTANT: this is still at a experimental state.
87  */
88
89 #include "atomsrecovery.h"
90
91 #define ATOMS_RECOV_OUTPUT_WRITE_ERROR(err) \
92     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE, \
93         "Failed to write to output file: %s", g_strerror (errno))
94
95 static gboolean
96 atoms_recov_write_version (FILE * f)
97 {
98   guint8 data[2];
99   GST_WRITE_UINT16_BE (data, ATOMS_RECOV_FILE_VERSION);
100   return fwrite (data, 2, 1, f) == 1;
101 }
102
103 static gboolean
104 atoms_recov_write_ftyp_info (FILE * f, AtomFTYP * ftyp, GstBuffer * prefix)
105 {
106   guint8 *data = NULL;
107   guint64 offset = 0;
108   guint64 size = 0;
109
110   if (prefix) {
111     GstMapInfo map;
112
113     gst_buffer_map (prefix, &map, GST_MAP_READ);
114     if (fwrite (map.data, 1, map.size, f) != map.size) {
115       gst_buffer_unmap (prefix, &map);
116       return FALSE;
117     }
118     gst_buffer_unmap (prefix, &map);
119   }
120   if (!atom_ftyp_copy_data (ftyp, &data, &size, &offset)) {
121     return FALSE;
122   }
123   if (fwrite (data, 1, offset, f) != offset) {
124     g_free (data);
125     return FALSE;
126   }
127   g_free (data);
128   return TRUE;
129 }
130
131 /**
132  * Writes important info on the 'moov' atom (non-trak related)
133  * to be able to recover the moov structure after a crash.
134  *
135  * Currently, it writes the MVHD atom.
136  */
137 static gboolean
138 atoms_recov_write_moov_info (FILE * f, AtomMOOV * moov)
139 {
140   guint8 *data;
141   guint64 size;
142   guint64 offset = 0;
143   guint64 atom_size = 0;
144   gint writen = 0;
145
146   /* likely enough */
147   size = 256;
148   data = g_malloc (size);
149   atom_size = atom_mvhd_copy_data (&moov->mvhd, &data, &size, &offset);
150   if (atom_size > 0)
151     writen = fwrite (data, 1, atom_size, f);
152   g_free (data);
153   return atom_size > 0 && writen == atom_size;
154 }
155
156 /**
157  * Writes the number of traks to the file.
158  * This simply writes a guint32 in BE.
159  */
160 static gboolean
161 atoms_recov_write_traks_number (FILE * f, guint32 traks)
162 {
163   guint8 data[4];
164   GST_WRITE_UINT32_BE (data, traks);
165   return fwrite (data, 4, 1, f) == 1;
166 }
167
168 /**
169  * Writes the moov's timescale to the file
170  * This simply writes a guint32 in BE.
171  */
172 static gboolean
173 atoms_recov_write_moov_timescale (FILE * f, guint32 timescale)
174 {
175   guint8 data[4];
176   GST_WRITE_UINT32_BE (data, timescale);
177   return fwrite (data, 4, 1, f) == 1;
178 }
179
180 /**
181  * Writes the trak atom to the file.
182  */
183 gboolean
184 atoms_recov_write_trak_info (FILE * f, AtomTRAK * trak)
185 {
186   guint8 *data;
187   guint64 size;
188   guint64 offset = 0;
189   guint64 atom_size = 0;
190   gint writen = 0;
191
192   /* buffer is realloced to a larger size if needed */
193   size = 4 * 1024;
194   data = g_malloc (size);
195   atom_size = atom_trak_copy_data (trak, &data, &size, &offset);
196   if (atom_size > 0)
197     writen = fwrite (data, atom_size, 1, f);
198   g_free (data);
199   return atom_size > 0 && writen == atom_size;
200 }
201
202 gboolean
203 atoms_recov_write_trak_samples (FILE * f, AtomTRAK * trak, guint32 nsamples,
204     guint32 delta, guint32 size, guint64 chunk_offset, gboolean sync,
205     gboolean do_pts, gint64 pts_offset)
206 {
207   guint8 data[TRAK_BUFFER_ENTRY_INFO_SIZE];
208   /*
209    * We have to write a TrakBufferEntryInfo
210    */
211   GST_WRITE_UINT32_BE (data + 0, trak->tkhd.track_ID);
212   GST_WRITE_UINT32_BE (data + 4, nsamples);
213   GST_WRITE_UINT32_BE (data + 8, delta);
214   GST_WRITE_UINT32_BE (data + 12, size);
215   GST_WRITE_UINT64_BE (data + 16, chunk_offset);
216   if (sync)
217     GST_WRITE_UINT8 (data + 24, 1);
218   else
219     GST_WRITE_UINT8 (data + 24, 0);
220   if (do_pts) {
221     GST_WRITE_UINT8 (data + 25, 1);
222     GST_WRITE_UINT64_BE (data + 26, pts_offset);
223   } else {
224     GST_WRITE_UINT8 (data + 25, 0);
225     GST_WRITE_UINT64_BE (data + 26, 0);
226   }
227
228   return fwrite (data, 1, TRAK_BUFFER_ENTRY_INFO_SIZE, f) ==
229       TRAK_BUFFER_ENTRY_INFO_SIZE;
230 }
231
232 gboolean
233 atoms_recov_write_headers (FILE * f, AtomFTYP * ftyp, GstBuffer * prefix,
234     AtomMOOV * moov, guint32 timescale, guint32 traks_number)
235 {
236   if (!atoms_recov_write_version (f)) {
237     return FALSE;
238   }
239
240   if (!atoms_recov_write_ftyp_info (f, ftyp, prefix)) {
241     return FALSE;
242   }
243
244   if (!atoms_recov_write_moov_info (f, moov)) {
245     return FALSE;
246   }
247
248   if (!atoms_recov_write_moov_timescale (f, timescale)) {
249     return FALSE;
250   }
251
252   if (!atoms_recov_write_traks_number (f, traks_number)) {
253     return FALSE;
254   }
255
256   return TRUE;
257 }
258
259 static gboolean
260 read_atom_header (FILE * f, guint32 * fourcc, guint32 * size)
261 {
262   guint8 aux[8];
263
264   if (fread (aux, 1, 8, f) != 8)
265     return FALSE;
266   *size = GST_READ_UINT32_BE (aux);
267   *fourcc = GST_READ_UINT32_LE (aux + 4);
268   return TRUE;
269 }
270
271 static gboolean
272 moov_recov_file_parse_prefix (MoovRecovFile * moovrf)
273 {
274   guint32 fourcc;
275   guint32 size;
276   guint32 total_size = 0;
277   if (fseek (moovrf->file, 2, SEEK_SET) != 0)
278     return FALSE;
279   if (!read_atom_header (moovrf->file, &fourcc, &size)) {
280     return FALSE;
281   }
282
283   if (fourcc != FOURCC_ftyp) {
284     /* we might have a prefix here */
285     if (fseek (moovrf->file, size - 8, SEEK_CUR) != 0)
286       return FALSE;
287
288     total_size += size;
289
290     /* now read the ftyp */
291     if (!read_atom_header (moovrf->file, &fourcc, &size))
292       return FALSE;
293   }
294
295   /* this has to be the ftyp */
296   if (fourcc != FOURCC_ftyp)
297     return FALSE;
298   total_size += size;
299   moovrf->prefix_size = total_size;
300   return fseek (moovrf->file, size - 8, SEEK_CUR) == 0;
301 }
302
303 static gboolean
304 moov_recov_file_parse_mvhd (MoovRecovFile * moovrf)
305 {
306   guint32 fourcc;
307   guint32 size;
308   if (!read_atom_header (moovrf->file, &fourcc, &size)) {
309     return FALSE;
310   }
311   /* check for sanity */
312   if (fourcc != FOURCC_mvhd)
313     return FALSE;
314
315   moovrf->mvhd_size = size;
316   moovrf->mvhd_pos = ftell (moovrf->file) - 8;
317
318   /* skip the remaining of the mvhd in the file */
319   return fseek (moovrf->file, size - 8, SEEK_CUR) == 0;
320 }
321
322 static gboolean
323 mdat_recov_file_parse_mdat_start (MdatRecovFile * mdatrf)
324 {
325   guint32 fourcc, size;
326
327   if (!read_atom_header (mdatrf->file, &fourcc, &size)) {
328     return FALSE;
329   }
330   if (size == 1) {
331     mdatrf->mdat_header_size = 16;
332     mdatrf->mdat_size = 16;
333   } else {
334     mdatrf->mdat_header_size = 8;
335     mdatrf->mdat_size = 8;
336   }
337   mdatrf->mdat_start = ftell (mdatrf->file) - 8;
338
339   return fourcc == FOURCC_mdat;
340 }
341
342 MdatRecovFile *
343 mdat_recov_file_create (FILE * file, gboolean datafile, GError ** err)
344 {
345   MdatRecovFile *mrf = g_new0 (MdatRecovFile, 1);
346   guint32 fourcc, size;
347
348   g_return_val_if_fail (file != NULL, NULL);
349
350   mrf->file = file;
351   mrf->rawfile = datafile;
352
353   /* get the file/data length */
354   if (fseek (file, 0, SEEK_END) != 0)
355     goto file_length_error;
356   /* still needs to deduce the mdat header and ftyp size */
357   mrf->data_size = ftell (file);
358   if (mrf->data_size == -1L)
359     goto file_length_error;
360
361   if (fseek (file, 0, SEEK_SET) != 0)
362     goto file_seek_error;
363
364   if (datafile) {
365     /* this file contains no atoms, only raw data to be placed on the mdat
366      * this happens when faststart mode is used */
367     mrf->mdat_start = 0;
368     mrf->mdat_header_size = 16;
369     mrf->mdat_size = 16;
370     return mrf;
371   }
372
373   if (!read_atom_header (file, &fourcc, &size)) {
374     goto parse_error;
375   }
376   if (fourcc != FOURCC_ftyp) {
377     /* this could be a prefix atom, let's skip it and try again */
378     if (fseek (file, size - 8, SEEK_CUR) != 0) {
379       goto file_seek_error;
380     }
381     if (!read_atom_header (file, &fourcc, &size)) {
382       goto parse_error;
383     }
384   }
385
386   if (fourcc != FOURCC_ftyp) {
387     goto parse_error;
388   }
389   if (fseek (file, size - 8, SEEK_CUR) != 0)
390     goto file_seek_error;
391
392   /* we don't parse this if we have a tmpdatafile */
393   if (!mdat_recov_file_parse_mdat_start (mrf)) {
394     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
395         "Error while parsing mdat atom");
396     goto fail;
397   }
398
399   return mrf;
400
401 parse_error:
402   g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
403       "Failed to parse atom");
404   goto fail;
405
406 file_seek_error:
407   g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
408       "Failed to seek to start of the file");
409   goto fail;
410
411 file_length_error:
412   g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
413       "Failed to determine file size");
414   goto fail;
415
416 fail:
417   mdat_recov_file_free (mrf);
418   return NULL;
419 }
420
421 void
422 mdat_recov_file_free (MdatRecovFile * mrf)
423 {
424   fclose (mrf->file);
425   g_free (mrf);
426 }
427
428 static gboolean
429 moov_recov_parse_num_traks (MoovRecovFile * moovrf)
430 {
431   guint8 traks[4];
432   if (fread (traks, 1, 4, moovrf->file) != 4)
433     return FALSE;
434   moovrf->num_traks = GST_READ_UINT32_BE (traks);
435   return TRUE;
436 }
437
438 static gboolean
439 moov_recov_parse_moov_timescale (MoovRecovFile * moovrf)
440 {
441   guint8 ts[4];
442   if (fread (ts, 1, 4, moovrf->file) != 4)
443     return FALSE;
444   moovrf->timescale = GST_READ_UINT32_BE (ts);
445   return TRUE;
446 }
447
448 static gboolean
449 skip_atom (MoovRecovFile * moovrf, guint32 expected_fourcc)
450 {
451   guint32 size;
452   guint32 fourcc;
453
454   if (!read_atom_header (moovrf->file, &fourcc, &size))
455     return FALSE;
456   if (fourcc != expected_fourcc)
457     return FALSE;
458
459   return (fseek (moovrf->file, size - 8, SEEK_CUR) == 0);
460 }
461
462 static gboolean
463 moov_recov_parse_tkhd (MoovRecovFile * moovrf, TrakRecovData * trakrd)
464 {
465   guint32 size;
466   guint32 fourcc;
467   guint8 data[4];
468
469   /* make sure we are on a tkhd atom */
470   if (!read_atom_header (moovrf->file, &fourcc, &size))
471     return FALSE;
472   if (fourcc != FOURCC_tkhd)
473     return FALSE;
474
475   trakrd->tkhd_file_offset = ftell (moovrf->file) - 8;
476
477   /* move 8 bytes forward to the trak_id pos */
478   if (fseek (moovrf->file, 12, SEEK_CUR) != 0)
479     return FALSE;
480   if (fread (data, 1, 4, moovrf->file) != 4)
481     return FALSE;
482
483   /* advance the rest of tkhd */
484   fseek (moovrf->file, 68, SEEK_CUR);
485
486   trakrd->trak_id = GST_READ_UINT32_BE (data);
487   return TRUE;
488 }
489
490 static gboolean
491 moov_recov_parse_stbl (MoovRecovFile * moovrf, TrakRecovData * trakrd)
492 {
493   guint32 size;
494   guint32 fourcc;
495   guint32 auxsize;
496
497   if (!read_atom_header (moovrf->file, &fourcc, &size))
498     return FALSE;
499   if (fourcc != FOURCC_stbl)
500     return FALSE;
501
502   trakrd->stbl_file_offset = ftell (moovrf->file) - 8;
503   trakrd->stbl_size = size;
504
505   /* skip the stsd */
506   if (!read_atom_header (moovrf->file, &fourcc, &auxsize))
507     return FALSE;
508   if (fourcc != FOURCC_stsd)
509     return FALSE;
510   if (fseek (moovrf->file, auxsize - 8, SEEK_CUR) != 0)
511     return FALSE;
512
513   trakrd->stsd_size = auxsize;
514   trakrd->post_stsd_offset = ftell (moovrf->file);
515
516   /* as this is the last atom we parse, we don't skip forward */
517
518   return TRUE;
519 }
520
521 static gboolean
522 moov_recov_parse_minf (MoovRecovFile * moovrf, TrakRecovData * trakrd)
523 {
524   guint32 size;
525   guint32 fourcc;
526   guint32 auxsize;
527
528   if (!read_atom_header (moovrf->file, &fourcc, &size))
529     return FALSE;
530   if (fourcc != FOURCC_minf)
531     return FALSE;
532
533   trakrd->minf_file_offset = ftell (moovrf->file) - 8;
534   trakrd->minf_size = size;
535
536   /* skip either of vmhd, smhd, hmhd that might follow */
537   if (!read_atom_header (moovrf->file, &fourcc, &auxsize))
538     return FALSE;
539   if (fourcc != FOURCC_vmhd && fourcc != FOURCC_smhd && fourcc != FOURCC_hmhd &&
540       fourcc != FOURCC_gmhd)
541     return FALSE;
542   if (fseek (moovrf->file, auxsize - 8, SEEK_CUR))
543     return FALSE;
544
545   /* skip a possible hdlr and the following dinf */
546   if (!read_atom_header (moovrf->file, &fourcc, &auxsize))
547     return FALSE;
548   if (fourcc == FOURCC_hdlr) {
549     if (fseek (moovrf->file, auxsize - 8, SEEK_CUR))
550       return FALSE;
551     if (!read_atom_header (moovrf->file, &fourcc, &auxsize))
552       return FALSE;
553   }
554   if (fourcc != FOURCC_dinf)
555     return FALSE;
556   if (fseek (moovrf->file, auxsize - 8, SEEK_CUR))
557     return FALSE;
558
559   /* now we are ready to read the stbl */
560   if (!moov_recov_parse_stbl (moovrf, trakrd))
561     return FALSE;
562
563   return TRUE;
564 }
565
566 static gboolean
567 moov_recov_parse_mdhd (MoovRecovFile * moovrf, TrakRecovData * trakrd)
568 {
569   guint32 size;
570   guint32 fourcc;
571   guint8 data[4];
572
573   /* make sure we are on a tkhd atom */
574   if (!read_atom_header (moovrf->file, &fourcc, &size))
575     return FALSE;
576   if (fourcc != FOURCC_mdhd)
577     return FALSE;
578
579   trakrd->mdhd_file_offset = ftell (moovrf->file) - 8;
580
581   /* get the timescale */
582   if (fseek (moovrf->file, 12, SEEK_CUR) != 0)
583     return FALSE;
584   if (fread (data, 1, 4, moovrf->file) != 4)
585     return FALSE;
586   trakrd->timescale = GST_READ_UINT32_BE (data);
587   if (fseek (moovrf->file, 8, SEEK_CUR) != 0)
588     return FALSE;
589   return TRUE;
590 }
591
592 static gboolean
593 moov_recov_parse_mdia (MoovRecovFile * moovrf, TrakRecovData * trakrd)
594 {
595   guint32 size;
596   guint32 fourcc;
597
598   /* make sure we are on a tkhd atom */
599   if (!read_atom_header (moovrf->file, &fourcc, &size))
600     return FALSE;
601   if (fourcc != FOURCC_mdia)
602     return FALSE;
603
604   trakrd->mdia_file_offset = ftell (moovrf->file) - 8;
605   trakrd->mdia_size = size;
606
607   if (!moov_recov_parse_mdhd (moovrf, trakrd))
608     return FALSE;
609
610   if (!skip_atom (moovrf, FOURCC_hdlr))
611     return FALSE;
612   if (!moov_recov_parse_minf (moovrf, trakrd))
613     return FALSE;
614   return TRUE;
615 }
616
617 static gboolean
618 moov_recov_parse_trak (MoovRecovFile * moovrf, TrakRecovData * trakrd)
619 {
620   guint64 offset;
621   guint32 size;
622   guint32 fourcc;
623
624   offset = ftell (moovrf->file);
625   if (offset == -1) {
626     return FALSE;
627   }
628
629   /* make sure we are on a trak atom */
630   if (!read_atom_header (moovrf->file, &fourcc, &size)) {
631     return FALSE;
632   }
633   if (fourcc != FOURCC_trak) {
634     return FALSE;
635   }
636   trakrd->trak_size = size;
637
638   /* now we should have a trak header 'tkhd' */
639   if (!moov_recov_parse_tkhd (moovrf, trakrd))
640     return FALSE;
641
642   /* FIXME add edts handling here and in qtmux, as this is only detected
643    * after buffers start flowing */
644
645   if (!moov_recov_parse_mdia (moovrf, trakrd))
646     return FALSE;
647
648   trakrd->file_offset = offset;
649   /* position after the trak */
650   return fseek (moovrf->file, (long int) offset + size, SEEK_SET) == 0;
651 }
652
653 MoovRecovFile *
654 moov_recov_file_create (FILE * file, GError ** err)
655 {
656   gint i;
657   MoovRecovFile *moovrf = g_new0 (MoovRecovFile, 1);
658
659   g_return_val_if_fail (file != NULL, NULL);
660
661   moovrf->file = file;
662
663   /* look for ftyp and prefix at the start */
664   if (!moov_recov_file_parse_prefix (moovrf)) {
665     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
666         "Error while parsing prefix atoms");
667     goto fail;
668   }
669
670   /* parse the mvhd */
671   if (!moov_recov_file_parse_mvhd (moovrf)) {
672     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
673         "Error while parsing mvhd atom");
674     goto fail;
675   }
676
677   if (!moov_recov_parse_moov_timescale (moovrf)) {
678     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
679         "Error while parsing timescale");
680     goto fail;
681   }
682   if (!moov_recov_parse_num_traks (moovrf)) {
683     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
684         "Error while parsing parsing number of traks");
685     goto fail;
686   }
687
688   /* init the traks */
689   moovrf->traks_rd = g_new0 (TrakRecovData, moovrf->num_traks);
690   for (i = 0; i < moovrf->num_traks; i++) {
691     atom_stbl_init (&(moovrf->traks_rd[i].stbl));
692   }
693   for (i = 0; i < moovrf->num_traks; i++) {
694     if (!moov_recov_parse_trak (moovrf, &(moovrf->traks_rd[i]))) {
695       g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
696           "Error while parsing trak atom");
697       goto fail;
698     }
699   }
700
701   return moovrf;
702
703 fail:
704   moov_recov_file_free (moovrf);
705   return NULL;
706 }
707
708 void
709 moov_recov_file_free (MoovRecovFile * moovrf)
710 {
711   gint i;
712   fclose (moovrf->file);
713   if (moovrf->traks_rd) {
714     for (i = 0; i < moovrf->num_traks; i++) {
715       atom_stbl_clear (&(moovrf->traks_rd[i].stbl));
716     }
717     g_free (moovrf->traks_rd);
718   }
719   g_free (moovrf);
720 }
721
722 static gboolean
723 moov_recov_parse_buffer_entry (MoovRecovFile * moovrf, TrakBufferEntryInfo * b)
724 {
725   guint8 data[TRAK_BUFFER_ENTRY_INFO_SIZE];
726   gint read;
727
728   read = fread (data, 1, TRAK_BUFFER_ENTRY_INFO_SIZE, moovrf->file);
729   if (read != TRAK_BUFFER_ENTRY_INFO_SIZE)
730     return FALSE;
731
732   b->track_id = GST_READ_UINT32_BE (data);
733   b->nsamples = GST_READ_UINT32_BE (data + 4);
734   b->delta = GST_READ_UINT32_BE (data + 8);
735   b->size = GST_READ_UINT32_BE (data + 12);
736   b->chunk_offset = GST_READ_UINT64_BE (data + 16);
737   b->sync = data[24] != 0;
738   b->do_pts = data[25] != 0;
739   b->pts_offset = GST_READ_UINT64_BE (data + 26);
740   return TRUE;
741 }
742
743 static gboolean
744 mdat_recov_add_sample (MdatRecovFile * mdatrf, guint32 size)
745 {
746   /* test if this data exists */
747   if (mdatrf->mdat_size - mdatrf->mdat_header_size + size > mdatrf->data_size)
748     return FALSE;
749
750   mdatrf->mdat_size += size;
751   return TRUE;
752 }
753
754 static TrakRecovData *
755 moov_recov_get_trak (MoovRecovFile * moovrf, guint32 id)
756 {
757   gint i;
758   for (i = 0; i < moovrf->num_traks; i++) {
759     if (moovrf->traks_rd[i].trak_id == id)
760       return &(moovrf->traks_rd[i]);
761   }
762   return NULL;
763 }
764
765 static void
766 trak_recov_data_add_sample (TrakRecovData * trak, TrakBufferEntryInfo * b)
767 {
768   trak->duration += b->nsamples * b->delta;
769   atom_stbl_add_samples (&trak->stbl, b->nsamples, b->delta, b->size,
770       b->chunk_offset, b->sync, b->pts_offset);
771 }
772
773 /**
774  * Parses the buffer entries in the MoovRecovFile and matches the inputs
775  * with the data in the MdatRecovFile. Whenever a buffer entry of that
776  * represents 'x' bytes of data, the same amount of data is 'validated' in
777  * the MdatRecovFile and will be inluded in the generated moovie file.
778  */
779 gboolean
780 moov_recov_parse_buffers (MoovRecovFile * moovrf, MdatRecovFile * mdatrf,
781     GError ** err)
782 {
783   TrakBufferEntryInfo entry;
784   TrakRecovData *trak;
785
786   /* we assume both moovrf and mdatrf are at the starting points of their
787    * data reading */
788   while (moov_recov_parse_buffer_entry (moovrf, &entry)) {
789     /* be sure we still have this data in mdat */
790     trak = moov_recov_get_trak (moovrf, entry.track_id);
791     if (trak == NULL) {
792       g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_PARSING,
793           "Invalid trak id found in buffer entry");
794       return FALSE;
795     }
796     if (!mdat_recov_add_sample (mdatrf, entry.size))
797       break;
798     trak_recov_data_add_sample (trak, &entry);
799   }
800   return TRUE;
801 }
802
803 static guint32
804 trak_recov_data_get_trak_atom_size (TrakRecovData * trak)
805 {
806   AtomSTBL *stbl = &trak->stbl;
807   guint64 offset;
808
809   /* write out our stbl child atoms */
810   offset = 0;
811
812   if (!atom_stts_copy_data (&stbl->stts, NULL, NULL, &offset)) {
813     goto fail;
814   }
815   if (atom_array_get_len (&stbl->stss.entries) > 0) {
816     if (!atom_stss_copy_data (&stbl->stss, NULL, NULL, &offset)) {
817       goto fail;
818     }
819   }
820   if (!atom_stsc_copy_data (&stbl->stsc, NULL, NULL, &offset)) {
821     goto fail;
822   }
823   if (!atom_stsz_copy_data (&stbl->stsz, NULL, NULL, &offset)) {
824     goto fail;
825   }
826   if (stbl->ctts) {
827     if (!atom_ctts_copy_data (stbl->ctts, NULL, NULL, &offset)) {
828       goto fail;
829     }
830   }
831   if (!atom_stco64_copy_data (&stbl->stco64, NULL, NULL, &offset)) {
832     goto fail;
833   }
834
835   return trak->trak_size + ((trak->stsd_size + offset + 8) - trak->stbl_size);
836
837 fail:
838   return 0;
839 }
840
841 static guint8 *
842 moov_recov_get_stbl_children_data (MoovRecovFile * moovrf, TrakRecovData * trak,
843     guint64 * p_size)
844 {
845   AtomSTBL *stbl = &trak->stbl;
846   guint8 *buffer;
847   guint64 size;
848   guint64 offset;
849
850   /* write out our stbl child atoms
851    *
852    * Use 1MB as a starting size, *_copy_data functions
853    * will grow the buffer if needed.
854    */
855   size = 1024 * 1024;
856   buffer = g_malloc0 (size);
857   offset = 0;
858
859   if (!atom_stts_copy_data (&stbl->stts, &buffer, &size, &offset)) {
860     goto fail;
861   }
862   if (atom_array_get_len (&stbl->stss.entries) > 0) {
863     if (!atom_stss_copy_data (&stbl->stss, &buffer, &size, &offset)) {
864       goto fail;
865     }
866   }
867   if (!atom_stsc_copy_data (&stbl->stsc, &buffer, &size, &offset)) {
868     goto fail;
869   }
870   if (!atom_stsz_copy_data (&stbl->stsz, &buffer, &size, &offset)) {
871     goto fail;
872   }
873   if (stbl->ctts) {
874     if (!atom_ctts_copy_data (stbl->ctts, &buffer, &size, &offset)) {
875       goto fail;
876     }
877   }
878   if (!atom_stco64_copy_data (&stbl->stco64, &buffer, &size, &offset)) {
879     goto fail;
880   }
881   *p_size = offset;
882   return buffer;
883
884 fail:
885   g_free (buffer);
886   return NULL;
887 }
888
889 gboolean
890 moov_recov_write_file (MoovRecovFile * moovrf, MdatRecovFile * mdatrf,
891     FILE * outf, GError ** err)
892 {
893   guint8 auxdata[16];
894   guint8 *data = NULL;
895   guint8 *prefix_data = NULL;
896   guint8 *mvhd_data = NULL;
897   guint8 *trak_data = NULL;
898   guint32 moov_size = 0;
899   gint i;
900   guint64 stbl_children_size = 0;
901   guint8 *stbl_children = NULL;
902   guint32 longest_duration = 0;
903   guint16 version;
904
905   /* check the version */
906   if (fseek (moovrf->file, 0, SEEK_SET) != 0) {
907     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
908         "Failed to seek to the start of the moov recovery file");
909     goto fail;
910   }
911   if (fread (auxdata, 1, 2, moovrf->file) != 2) {
912     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
913         "Failed to read version from file");
914   }
915
916   version = GST_READ_UINT16_BE (auxdata);
917   if (version != ATOMS_RECOV_FILE_VERSION) {
918     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_VERSION,
919         "Input file version (%u) is not supported in this version (%u)",
920         version, ATOMS_RECOV_FILE_VERSION);
921     return FALSE;
922   }
923
924   /* write the ftyp */
925   prefix_data = g_malloc (moovrf->prefix_size);
926   if (fread (prefix_data, 1, moovrf->prefix_size,
927           moovrf->file) != moovrf->prefix_size) {
928     g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
929         "Failed to read the ftyp atom from file");
930     goto fail;
931   }
932   if (fwrite (prefix_data, 1, moovrf->prefix_size, outf) != moovrf->prefix_size) {
933     ATOMS_RECOV_OUTPUT_WRITE_ERROR (err);
934     goto fail;
935   }
936   g_free (prefix_data);
937   prefix_data = NULL;
938
939   /* need to calculate the moov size beforehand to add the offset to
940    * chunk offset entries */
941   moov_size += moovrf->mvhd_size + 8;   /* mvhd + moov size + fourcc */
942   for (i = 0; i < moovrf->num_traks; i++) {
943     TrakRecovData *trak = &(moovrf->traks_rd[i]);
944     guint32 duration;           /* in moov's timescale */
945     guint32 trak_size;
946
947     /* convert trak duration to moov's duration */
948     duration = gst_util_uint64_scale_round (trak->duration, moovrf->timescale,
949         trak->timescale);
950
951     if (duration > longest_duration)
952       longest_duration = duration;
953     trak_size = trak_recov_data_get_trak_atom_size (trak);
954     if (trak_size == 0) {
955       g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_GENERIC,
956           "Failed to estimate trak atom size");
957       goto fail;
958     }
959     moov_size += trak_size;
960   }
961
962   /* add chunks offsets */
963   for (i = 0; i < moovrf->num_traks; i++) {
964     TrakRecovData *trak = &(moovrf->traks_rd[i]);
965     /* 16 for the mdat header */
966     gint64 offset = moov_size + ftell (outf) + 16;
967     atom_stco64_chunks_add_offset (&trak->stbl.stco64, offset);
968   }
969
970   /* write the moov */
971   GST_WRITE_UINT32_BE (auxdata, moov_size);
972   GST_WRITE_UINT32_LE (auxdata + 4, FOURCC_moov);
973   if (fwrite (auxdata, 1, 8, outf) != 8) {
974     ATOMS_RECOV_OUTPUT_WRITE_ERROR (err);
975     goto fail;
976   }
977
978   /* write the mvhd */
979   mvhd_data = g_malloc (moovrf->mvhd_size);
980   if (fseek (moovrf->file, moovrf->mvhd_pos, SEEK_SET) != 0)
981     goto fail;
982   if (fread (mvhd_data, 1, moovrf->mvhd_size,
983           moovrf->file) != moovrf->mvhd_size)
984     goto fail;
985   GST_WRITE_UINT32_BE (mvhd_data + 20, moovrf->timescale);
986   GST_WRITE_UINT32_BE (mvhd_data + 24, longest_duration);
987   if (fwrite (mvhd_data, 1, moovrf->mvhd_size, outf) != moovrf->mvhd_size) {
988     ATOMS_RECOV_OUTPUT_WRITE_ERROR (err);
989     goto fail;
990   }
991   g_free (mvhd_data);
992   mvhd_data = NULL;
993
994   /* write the traks, this is the tough part because we need to update:
995    * - stbl atom
996    * - sizes of atoms from stbl to trak
997    * - trak duration
998    */
999   for (i = 0; i < moovrf->num_traks; i++) {
1000     TrakRecovData *trak = &(moovrf->traks_rd[i]);
1001     guint trak_data_size;
1002     guint32 stbl_new_size;
1003     guint32 minf_new_size;
1004     guint32 mdia_new_size;
1005     guint32 trak_new_size;
1006     guint32 size_diff;
1007     guint32 duration;           /* in moov's timescale */
1008
1009     /* convert trak duration to moov's duration */
1010     duration = gst_util_uint64_scale_round (trak->duration, moovrf->timescale,
1011         trak->timescale);
1012
1013     stbl_children = moov_recov_get_stbl_children_data (moovrf, trak,
1014         &stbl_children_size);
1015     if (stbl_children == NULL)
1016       goto fail;
1017
1018     /* calc the new size of the atoms from stbl to trak in the atoms tree */
1019     stbl_new_size = trak->stsd_size + stbl_children_size + 8;
1020     size_diff = stbl_new_size - trak->stbl_size;
1021     minf_new_size = trak->minf_size + size_diff;
1022     mdia_new_size = trak->mdia_size + size_diff;
1023     trak_new_size = trak->trak_size + size_diff;
1024
1025     if (fseek (moovrf->file, trak->file_offset, SEEK_SET) != 0)
1026       goto fail;
1027     trak_data_size = trak->post_stsd_offset - trak->file_offset;
1028     trak_data = g_malloc (trak_data_size);
1029     if (fread (trak_data, 1, trak_data_size, moovrf->file) != trak_data_size) {
1030       goto fail;
1031     }
1032     /* update the size values in those read atoms before writing */
1033     GST_WRITE_UINT32_BE (trak_data, trak_new_size);
1034     GST_WRITE_UINT32_BE (trak_data + (trak->mdia_file_offset -
1035             trak->file_offset), mdia_new_size);
1036     GST_WRITE_UINT32_BE (trak_data + (trak->minf_file_offset -
1037             trak->file_offset), minf_new_size);
1038     GST_WRITE_UINT32_BE (trak_data + (trak->stbl_file_offset -
1039             trak->file_offset), stbl_new_size);
1040
1041     /* update duration values in tkhd and mdhd */
1042     GST_WRITE_UINT32_BE (trak_data + (trak->tkhd_file_offset -
1043             trak->file_offset) + 28, duration);
1044     GST_WRITE_UINT32_BE (trak_data + (trak->mdhd_file_offset -
1045             trak->file_offset) + 24, trak->duration);
1046
1047     if (fwrite (trak_data, 1, trak_data_size, outf) != trak_data_size) {
1048       ATOMS_RECOV_OUTPUT_WRITE_ERROR (err);
1049       goto fail;
1050     }
1051     if (fwrite (stbl_children, 1, stbl_children_size, outf) !=
1052         stbl_children_size) {
1053       ATOMS_RECOV_OUTPUT_WRITE_ERROR (err);
1054       goto fail;
1055     }
1056     g_free (trak_data);
1057     trak_data = NULL;
1058     g_free (stbl_children);
1059     stbl_children = NULL;
1060   }
1061
1062   /* write the mdat */
1063   /* write the header first */
1064   GST_WRITE_UINT32_BE (auxdata, 1);
1065   GST_WRITE_UINT32_LE (auxdata + 4, FOURCC_mdat);
1066   GST_WRITE_UINT64_BE (auxdata + 8, mdatrf->mdat_size);
1067   if (fwrite (auxdata, 1, 16, outf) != 16) {
1068     ATOMS_RECOV_OUTPUT_WRITE_ERROR (err);
1069     goto fail;
1070   }
1071
1072   /* now read the mdat data and output to the file */
1073   if (fseek (mdatrf->file, mdatrf->mdat_start +
1074           (mdatrf->rawfile ? 0 : mdatrf->mdat_header_size), SEEK_SET) != 0)
1075     goto fail;
1076
1077   data = g_malloc (4096);
1078   while (!feof (mdatrf->file)) {
1079     gint read, write;
1080
1081     read = fread (data, 1, 4096, mdatrf->file);
1082     write = fwrite (data, 1, read, outf);
1083
1084     if (write != read) {
1085       g_set_error (err, ATOMS_RECOV_QUARK, ATOMS_RECOV_ERR_FILE,
1086           "Failed to copy data to output file: %s", g_strerror (errno));
1087       goto fail;
1088     }
1089   }
1090   g_free (data);
1091
1092   return TRUE;
1093
1094 fail:
1095   g_free (stbl_children);
1096   g_free (mvhd_data);
1097   g_free (prefix_data);
1098   g_free (trak_data);
1099   g_free (data);
1100   return FALSE;
1101 }