qtdemux: Forward upstream time-format segment without mapping
[platform/upstream/gst-plugins-good.git] / gst / isomp4 / atoms.c
1 /* Quicktime muxer plugin for GStreamer
2  * Copyright (C) 2008-2010 Thiago Santos <thiagoss@embedded.ufcg.edu.br>
3  * Copyright (C) 2008 Mark Nauwelaerts <mnauw@users.sf.net>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20 /*
21  * Unless otherwise indicated, Source Code is licensed under MIT license.
22  * See further explanation attached in License Statement (distributed in the file
23  * LICENSE).
24  *
25  * Permission is hereby granted, free of charge, to any person obtaining a copy of
26  * this software and associated documentation files (the "Software"), to deal in
27  * the Software without restriction, including without limitation the rights to
28  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
29  * of the Software, and to permit persons to whom the Software is furnished to do
30  * so, subject to the following conditions:
31  *
32  * The above copyright notice and this permission notice shall be included in all
33  * copies or substantial portions of the Software.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
41  * SOFTWARE.
42  */
43
44 #include "atoms.h"
45 #include <string.h>
46 #include <glib.h>
47
48 #include <gst/gst.h>
49 #include <gst/base/gstbytewriter.h>
50 #include <gst/tag/tag.h>
51 #include <gst/video/video.h>
52
53 /*
54  * Creates a new AtomsContext for the given flavor.
55  */
56 AtomsContext *
57 atoms_context_new (AtomsTreeFlavor flavor)
58 {
59   AtomsContext *context = g_new0 (AtomsContext, 1);
60   context->flavor = flavor;
61   return context;
62 }
63
64 /*
65  * Frees an AtomsContext and all memory associated with it
66  */
67 void
68 atoms_context_free (AtomsContext * context)
69 {
70   g_free (context);
71 }
72
73 /* -- creation, initialization, clear and free functions -- */
74
75 #define SECS_PER_DAY (24 * 60 * 60)
76 #define LEAP_YEARS_FROM_1904_TO_1970 17
77
78 guint64
79 atoms_get_current_qt_time (void)
80 {
81   GTimeVal timeval;
82
83   g_get_current_time (&timeval);
84   /* FIXME this should use UTC coordinated time */
85   return timeval.tv_sec + (((1970 - 1904) * (guint64) 365) +
86       LEAP_YEARS_FROM_1904_TO_1970) * SECS_PER_DAY;
87 }
88
89 static void
90 common_time_info_init (TimeInfo * ti)
91 {
92   ti->creation_time = ti->modification_time = atoms_get_current_qt_time ();
93   ti->timescale = 0;
94   ti->duration = 0;
95 }
96
97 static void
98 atom_header_set (Atom * header, guint32 fourcc, gint32 size, gint64 ext_size)
99 {
100   header->type = fourcc;
101   header->size = size;
102   header->extended_size = ext_size;
103 }
104
105 static void
106 atom_clear (Atom * atom)
107 {
108 }
109
110 static void
111 atom_full_init (AtomFull * full, guint32 fourcc, gint32 size, gint64 ext_size,
112     guint8 version, guint8 flags[3])
113 {
114   atom_header_set (&(full->header), fourcc, size, ext_size);
115   full->version = version;
116   full->flags[0] = flags[0];
117   full->flags[1] = flags[1];
118   full->flags[2] = flags[2];
119 }
120
121 static void
122 atom_full_clear (AtomFull * full)
123 {
124   atom_clear (&full->header);
125 }
126
127 static void
128 atom_full_free (AtomFull * full)
129 {
130   atom_full_clear (full);
131   g_free (full);
132 }
133
134 static guint32
135 atom_full_get_flags_as_uint (AtomFull * full)
136 {
137   return full->flags[0] << 16 | full->flags[1] << 8 | full->flags[2];
138 }
139
140 static void
141 atom_full_set_flags_as_uint (AtomFull * full, guint32 flags_as_uint)
142 {
143   full->flags[2] = flags_as_uint & 0xFF;
144   full->flags[1] = (flags_as_uint & 0xFF00) >> 8;
145   full->flags[0] = (flags_as_uint & 0xFF0000) >> 16;
146 }
147
148 static AtomInfo *
149 build_atom_info_wrapper (Atom * atom, gpointer copy_func, gpointer free_func)
150 {
151   AtomInfo *info = NULL;
152
153   if (atom) {
154     info = g_new0 (AtomInfo, 1);
155
156     info->atom = atom;
157     info->copy_data_func = copy_func;
158     info->free_func = free_func;
159   }
160
161   return info;
162 }
163
164 static GList *
165 atom_info_list_prepend_atom (GList * ai, Atom * atom,
166     AtomCopyDataFunc copy_func, AtomFreeFunc free_func)
167 {
168   if (atom)
169     return g_list_prepend (ai,
170         build_atom_info_wrapper (atom, copy_func, free_func));
171   else
172     return ai;
173 }
174
175 static void
176 atom_info_list_free (GList * ai)
177 {
178   while (ai) {
179     AtomInfo *info = (AtomInfo *) ai->data;
180
181     info->free_func (info->atom);
182     g_free (info);
183     ai = g_list_delete_link (ai, ai);
184   }
185 }
186
187 static AtomData *
188 atom_data_new (guint32 fourcc)
189 {
190   AtomData *data = g_new0 (AtomData, 1);
191
192   atom_header_set (&data->header, fourcc, 0, 0);
193   return data;
194 }
195
196 static void
197 atom_data_alloc_mem (AtomData * data, guint32 size)
198 {
199   g_free (data->data);
200   data->data = g_new0 (guint8, size);
201   data->datalen = size;
202 }
203
204 static AtomData *
205 atom_data_new_from_data (guint32 fourcc, const guint8 * mem, gsize size)
206 {
207   AtomData *data = atom_data_new (fourcc);
208
209   atom_data_alloc_mem (data, size);
210   memcpy (data->data, mem, size);
211   return data;
212 }
213
214 static AtomData *
215 atom_data_new_from_gst_buffer (guint32 fourcc, const GstBuffer * buf)
216 {
217   AtomData *data = atom_data_new (fourcc);
218   gsize size = gst_buffer_get_size ((GstBuffer *) buf);
219
220   atom_data_alloc_mem (data, size);
221   gst_buffer_extract ((GstBuffer *) buf, 0, data->data, size);
222   return data;
223 }
224
225 static void
226 atom_data_free (AtomData * data)
227 {
228   atom_clear (&data->header);
229   g_free (data->data);
230   g_free (data);
231 }
232
233 static AtomUUID *
234 atom_uuid_new (void)
235 {
236   AtomUUID *uuid = g_new0 (AtomUUID, 1);
237
238   atom_header_set (&uuid->header, FOURCC_uuid, 0, 0);
239   return uuid;
240 }
241
242 static void
243 atom_uuid_free (AtomUUID * data)
244 {
245   atom_clear (&data->header);
246   g_free (data->data);
247   g_free (data);
248 }
249
250 static void
251 atom_ftyp_init (AtomFTYP * ftyp, guint32 major, guint32 version, GList * brands)
252 {
253   gint index;
254   GList *it = NULL;
255
256   atom_header_set (&ftyp->header, FOURCC_ftyp, 16, 0);
257   ftyp->major_brand = major;
258   ftyp->version = version;
259
260   /* always include major brand as compatible brand */
261   ftyp->compatible_brands_size = g_list_length (brands) + 1;
262   ftyp->compatible_brands = g_new (guint32, ftyp->compatible_brands_size);
263
264   ftyp->compatible_brands[0] = major;
265   index = 1;
266   for (it = brands; it != NULL; it = g_list_next (it)) {
267     ftyp->compatible_brands[index++] = GPOINTER_TO_UINT (it->data);
268   }
269 }
270
271 AtomFTYP *
272 atom_ftyp_new (AtomsContext * context, guint32 major, guint32 version,
273     GList * brands)
274 {
275   AtomFTYP *ftyp = g_new0 (AtomFTYP, 1);
276
277   atom_ftyp_init (ftyp, major, version, brands);
278   return ftyp;
279 }
280
281 void
282 atom_ftyp_free (AtomFTYP * ftyp)
283 {
284   atom_clear (&ftyp->header);
285   g_free (ftyp->compatible_brands);
286   ftyp->compatible_brands = NULL;
287   g_free (ftyp);
288 }
289
290 static void
291 atom_esds_init (AtomESDS * esds)
292 {
293   guint8 flags[3] = { 0, 0, 0 };
294
295   atom_full_init (&esds->header, FOURCC_esds, 0, 0, 0, flags);
296   desc_es_init (&esds->es);
297 }
298
299 static AtomESDS *
300 atom_esds_new (void)
301 {
302   AtomESDS *esds = g_new0 (AtomESDS, 1);
303
304   atom_esds_init (esds);
305   return esds;
306 }
307
308 static void
309 atom_esds_free (AtomESDS * esds)
310 {
311   atom_full_clear (&esds->header);
312   desc_es_descriptor_clear (&esds->es);
313   g_free (esds);
314 }
315
316 static AtomFRMA *
317 atom_frma_new (void)
318 {
319   AtomFRMA *frma = g_new0 (AtomFRMA, 1);
320
321   atom_header_set (&frma->header, FOURCC_frma, 0, 0);
322   return frma;
323 }
324
325 static void
326 atom_frma_free (AtomFRMA * frma)
327 {
328   atom_clear (&frma->header);
329   g_free (frma);
330 }
331
332 static AtomWAVE *
333 atom_wave_new (void)
334 {
335   AtomWAVE *wave = g_new0 (AtomWAVE, 1);
336
337   atom_header_set (&wave->header, FOURCC_wave, 0, 0);
338   return wave;
339 }
340
341 static void
342 atom_wave_free (AtomWAVE * wave)
343 {
344   atom_clear (&wave->header);
345   atom_info_list_free (wave->extension_atoms);
346   g_free (wave);
347 }
348
349 static void
350 atom_elst_init (AtomELST * elst)
351 {
352   guint8 flags[3] = { 0, 0, 0 };
353   atom_full_init (&elst->header, FOURCC_elst, 0, 0, 0, flags);
354   elst->entries = 0;
355 }
356
357 static void
358 atom_elst_clear (AtomELST * elst)
359 {
360   GSList *walker;
361
362   atom_full_clear (&elst->header);
363   walker = elst->entries;
364   while (walker) {
365     g_free ((EditListEntry *) walker->data);
366     walker = g_slist_next (walker);
367   }
368   g_slist_free (elst->entries);
369 }
370
371 static void
372 atom_edts_init (AtomEDTS * edts)
373 {
374   atom_header_set (&edts->header, FOURCC_edts, 0, 0);
375   atom_elst_init (&edts->elst);
376 }
377
378 static void
379 atom_edts_clear (AtomEDTS * edts)
380 {
381   atom_clear (&edts->header);
382   atom_elst_clear (&edts->elst);
383 }
384
385 static AtomEDTS *
386 atom_edts_new (void)
387 {
388   AtomEDTS *edts = g_new0 (AtomEDTS, 1);
389   atom_edts_init (edts);
390   return edts;
391 }
392
393 static void
394 atom_edts_free (AtomEDTS * edts)
395 {
396   atom_edts_clear (edts);
397   g_free (edts);
398 }
399
400 static void
401 atom_tcmi_init (AtomTCMI * tcmi)
402 {
403   guint8 flags[3] = { 0, 0, 0 };
404
405   atom_full_init (&tcmi->header, FOURCC_tcmi, 0, 0, 0, flags);
406 }
407
408 static void
409 atom_tcmi_clear (AtomTCMI * tcmi)
410 {
411   atom_full_clear (&tcmi->header);
412   tcmi->text_font = 0;
413   tcmi->text_face = 0;
414   tcmi->text_size = 0;
415   tcmi->text_color[0] = 0;
416   tcmi->text_color[1] = 0;
417   tcmi->text_color[2] = 0;
418   tcmi->bg_color[0] = 0;
419   tcmi->bg_color[1] = 0;
420   tcmi->bg_color[2] = 0;
421   g_free (tcmi->font_name);
422   tcmi->font_name = NULL;
423 }
424
425 static AtomTMCD *
426 atom_tmcd_new (void)
427 {
428   AtomTMCD *tmcd = g_new0 (AtomTMCD, 1);
429
430   atom_header_set (&tmcd->header, FOURCC_tmcd, 0, 0);
431   atom_tcmi_init (&tmcd->tcmi);
432
433   return tmcd;
434 }
435
436 static void
437 atom_tmcd_free (AtomTMCD * tmcd)
438 {
439   atom_clear (&tmcd->header);
440   atom_tcmi_clear (&tmcd->tcmi);
441   g_free (tmcd);
442 }
443
444 static void
445 atom_gmin_init (AtomGMIN * gmin)
446 {
447   guint8 flags[3] = { 0, 0, 0 };
448
449   atom_full_init (&gmin->header, FOURCC_gmin, 0, 0, 0, flags);
450 }
451
452 static void
453 atom_gmin_clear (AtomGMIN * gmin)
454 {
455   atom_full_clear (&gmin->header);
456   gmin->graphics_mode = 0;
457   gmin->opcolor[0] = 0;
458   gmin->opcolor[1] = 0;
459   gmin->opcolor[2] = 0;
460   gmin->balance = 0;
461   gmin->reserved = 0;
462 }
463
464 static void
465 atom_gmhd_init (AtomGMHD * gmhd)
466 {
467   atom_header_set (&gmhd->header, FOURCC_gmhd, 0, 0);
468   atom_gmin_init (&gmhd->gmin);
469 }
470
471 static void
472 atom_gmhd_clear (AtomGMHD * gmhd)
473 {
474   atom_clear (&gmhd->header);
475   atom_gmin_clear (&gmhd->gmin);
476   if (gmhd->tmcd) {
477     atom_tmcd_free (gmhd->tmcd);
478     gmhd->tmcd = NULL;
479   }
480 }
481
482 static AtomGMHD *
483 atom_gmhd_new (void)
484 {
485   AtomGMHD *gmhd = g_new0 (AtomGMHD, 1);
486   atom_gmhd_init (gmhd);
487   return gmhd;
488 }
489
490 static void
491 atom_gmhd_free (AtomGMHD * gmhd)
492 {
493   atom_gmhd_clear (gmhd);
494   g_free (gmhd);
495 }
496
497 static void
498 atom_sample_entry_init (SampleTableEntry * se, guint32 type)
499 {
500   atom_header_set (&se->header, type, 0, 0);
501
502   memset (se->reserved, 0, sizeof (guint8) * 6);
503   se->data_reference_index = 0;
504 }
505
506 static void
507 atom_sample_entry_free (SampleTableEntry * se)
508 {
509   atom_clear (&se->header);
510 }
511
512 static void
513 sample_entry_mp4a_init (SampleTableEntryMP4A * mp4a)
514 {
515   atom_sample_entry_init (&mp4a->se, FOURCC_mp4a);
516
517   mp4a->version = 0;
518   mp4a->revision_level = 0;
519   mp4a->vendor = 0;
520   mp4a->channels = 2;
521   mp4a->sample_size = 16;
522   mp4a->compression_id = 0;
523   mp4a->packet_size = 0;
524   mp4a->sample_rate = 0;
525   /* following only used if version is 1 */
526   mp4a->samples_per_packet = 0;
527   mp4a->bytes_per_packet = 0;
528   mp4a->bytes_per_frame = 0;
529   mp4a->bytes_per_sample = 0;
530
531   mp4a->extension_atoms = NULL;
532 }
533
534 static SampleTableEntryMP4A *
535 sample_entry_mp4a_new (void)
536 {
537   SampleTableEntryMP4A *mp4a = g_new0 (SampleTableEntryMP4A, 1);
538
539   sample_entry_mp4a_init (mp4a);
540   return mp4a;
541 }
542
543 static void
544 sample_entry_mp4a_free (SampleTableEntryMP4A * mp4a)
545 {
546   atom_sample_entry_free (&mp4a->se);
547   atom_info_list_free (mp4a->extension_atoms);
548   g_free (mp4a);
549 }
550
551 static void
552 sample_entry_tmcd_init (SampleTableEntryTMCD * tmcd)
553 {
554   atom_sample_entry_init (&tmcd->se, FOURCC_tmcd);
555
556   tmcd->tc_flags = 0;
557   tmcd->timescale = 0;
558   tmcd->frame_duration = 0;
559   tmcd->n_frames = 0;
560
561   tmcd->name.language_code = 0;
562   g_free (tmcd->name.name);
563   tmcd->name.name = NULL;
564 }
565
566 static SampleTableEntryTMCD *
567 sample_entry_tmcd_new (void)
568 {
569   SampleTableEntryTMCD *tmcd = g_new0 (SampleTableEntryTMCD, 1);
570
571   sample_entry_tmcd_init (tmcd);
572   return tmcd;
573 }
574
575 static void
576 sample_entry_tmcd_free (SampleTableEntryTMCD * tmcd)
577 {
578   atom_sample_entry_free (&tmcd->se);
579   g_free (tmcd->name.name);
580   g_free (tmcd);
581 }
582
583 static void
584 sample_entry_mp4v_init (SampleTableEntryMP4V * mp4v, AtomsContext * context)
585 {
586   atom_sample_entry_init (&mp4v->se, FOURCC_mp4v);
587
588   mp4v->version = 0;
589   mp4v->revision_level = 0;
590   mp4v->vendor = 0;
591
592   mp4v->temporal_quality = 0;
593   mp4v->spatial_quality = 0;
594
595   /* qt and ISO base media do not contradict, and examples agree */
596   mp4v->horizontal_resolution = 0x00480000;
597   mp4v->vertical_resolution = 0x00480000;
598
599   mp4v->datasize = 0;
600   mp4v->frame_count = 1;
601
602   memset (mp4v->compressor, 0, sizeof (guint8) * 32);
603
604   mp4v->depth = 0;
605   mp4v->color_table_id = 0;
606
607   mp4v->extension_atoms = NULL;
608 }
609
610 static void
611 sample_entry_mp4v_free (SampleTableEntryMP4V * mp4v)
612 {
613   atom_sample_entry_free (&mp4v->se);
614   atom_info_list_free (mp4v->extension_atoms);
615   g_free (mp4v);
616 }
617
618 static SampleTableEntryMP4V *
619 sample_entry_mp4v_new (AtomsContext * context)
620 {
621   SampleTableEntryMP4V *mp4v = g_new0 (SampleTableEntryMP4V, 1);
622
623   sample_entry_mp4v_init (mp4v, context);
624   return mp4v;
625 }
626
627 static void
628 sample_entry_tx3g_init (SampleTableEntryTX3G * tx3g)
629 {
630   atom_sample_entry_init (&tx3g->se, FOURCC_tx3g);
631
632   tx3g->display_flags = 0;
633   tx3g->font_id = 1;            /* must be 1 as there is a single font */
634   tx3g->font_face = 0;
635   tx3g->foreground_color_rgba = 0xFFFFFFFF;     /* white, opaque */
636
637   /* can't set this now */
638   tx3g->default_text_box = 0;
639   tx3g->font_size = 0;
640 }
641
642 static void
643 sample_entry_tx3g_free (SampleTableEntryTX3G * tx3g)
644 {
645   atom_sample_entry_free (&tx3g->se);
646   g_free (tx3g);
647 }
648
649 static SampleTableEntryTX3G *
650 sample_entry_tx3g_new (void)
651 {
652   SampleTableEntryTX3G *tx3g = g_new0 (SampleTableEntryTX3G, 1);
653
654   sample_entry_tx3g_init (tx3g);
655   return tx3g;
656 }
657
658
659 static void
660 atom_stsd_init (AtomSTSD * stsd)
661 {
662   guint8 flags[3] = { 0, 0, 0 };
663
664   atom_full_init (&stsd->header, FOURCC_stsd, 0, 0, 0, flags);
665   stsd->entries = NULL;
666   stsd->n_entries = 0;
667 }
668
669 static void
670 atom_stsd_remove_entries (AtomSTSD * stsd)
671 {
672   GList *walker;
673
674   walker = stsd->entries;
675   while (walker) {
676     GList *aux = walker;
677     SampleTableEntry *se = (SampleTableEntry *) aux->data;
678
679     walker = g_list_next (walker);
680     stsd->entries = g_list_remove_link (stsd->entries, aux);
681
682     switch (se->kind) {
683       case AUDIO:
684         sample_entry_mp4a_free ((SampleTableEntryMP4A *) se);
685         break;
686       case VIDEO:
687         sample_entry_mp4v_free ((SampleTableEntryMP4V *) se);
688         break;
689       case SUBTITLE:
690         sample_entry_tx3g_free ((SampleTableEntryTX3G *) se);
691         break;
692       case TIMECODE:
693         sample_entry_tmcd_free ((SampleTableEntryTMCD *) se);
694         break;
695       case CLOSEDCAPTION:
696       default:
697         /* best possible cleanup */
698         atom_sample_entry_free (se);
699     }
700     g_list_free (aux);
701   }
702   stsd->n_entries = 0;
703 }
704
705 static void
706 atom_stsd_clear (AtomSTSD * stsd)
707 {
708   atom_stsd_remove_entries (stsd);
709   atom_full_clear (&stsd->header);
710 }
711
712 static void
713 atom_ctts_init (AtomCTTS * ctts)
714 {
715   guint8 flags[3] = { 0, 0, 0 };
716
717   atom_full_init (&ctts->header, FOURCC_ctts, 0, 0, 0, flags);
718   atom_array_init (&ctts->entries, 128);
719   ctts->do_pts = FALSE;
720 }
721
722 static AtomCTTS *
723 atom_ctts_new (void)
724 {
725   AtomCTTS *ctts = g_new0 (AtomCTTS, 1);
726
727   atom_ctts_init (ctts);
728   return ctts;
729 }
730
731 static void
732 atom_ctts_free (AtomCTTS * ctts)
733 {
734   atom_full_clear (&ctts->header);
735   atom_array_clear (&ctts->entries);
736   g_free (ctts);
737 }
738
739 static void
740 atom_svmi_init (AtomSVMI * svmi)
741 {
742   guint8 flags[3] = { 0, 0, 0 };
743
744   atom_full_init (&svmi->header, FOURCC_svmi, 0, 0, 0, flags);
745   svmi->stereoscopic_composition_type = 0x00;
746   svmi->is_left_first = FALSE;
747 }
748
749 AtomSVMI *
750 atom_svmi_new (guint8 stereoscopic_composition_type, gboolean is_left_first)
751 {
752   AtomSVMI *svmi = g_new0 (AtomSVMI, 1);
753
754   atom_svmi_init (svmi);
755   svmi->stereoscopic_composition_type = stereoscopic_composition_type;
756   svmi->is_left_first = is_left_first;
757   return svmi;
758 }
759
760 static void
761 atom_svmi_free (AtomSVMI * svmi)
762 {
763   g_free (svmi);
764 }
765
766 static void
767 atom_stts_init (AtomSTTS * stts)
768 {
769   guint8 flags[3] = { 0, 0, 0 };
770
771   atom_full_init (&stts->header, FOURCC_stts, 0, 0, 0, flags);
772   atom_array_init (&stts->entries, 512);
773 }
774
775 static void
776 atom_stts_clear (AtomSTTS * stts)
777 {
778   atom_full_clear (&stts->header);
779   atom_array_clear (&stts->entries);
780 }
781
782 static void
783 atom_stsz_init (AtomSTSZ * stsz)
784 {
785   guint8 flags[3] = { 0, 0, 0 };
786
787   atom_full_init (&stsz->header, FOURCC_stsz, 0, 0, 0, flags);
788   atom_array_init (&stsz->entries, 1024);
789   stsz->sample_size = 0;
790   stsz->table_size = 0;
791 }
792
793 static void
794 atom_stsz_clear (AtomSTSZ * stsz)
795 {
796   atom_full_clear (&stsz->header);
797   atom_array_clear (&stsz->entries);
798   stsz->table_size = 0;
799 }
800
801 static void
802 atom_stsc_init (AtomSTSC * stsc)
803 {
804   guint8 flags[3] = { 0, 0, 0 };
805
806   atom_full_init (&stsc->header, FOURCC_stsc, 0, 0, 0, flags);
807   atom_array_init (&stsc->entries, 128);
808 }
809
810 static void
811 atom_stsc_clear (AtomSTSC * stsc)
812 {
813   atom_full_clear (&stsc->header);
814   atom_array_clear (&stsc->entries);
815 }
816
817 static void
818 atom_co64_init (AtomSTCO64 * co64)
819 {
820   guint8 flags[3] = { 0, 0, 0 };
821
822   atom_full_init (&co64->header, FOURCC_stco, 0, 0, 0, flags);
823   atom_array_init (&co64->entries, 256);
824 }
825
826 static void
827 atom_stco64_clear (AtomSTCO64 * stco64)
828 {
829   atom_full_clear (&stco64->header);
830   atom_array_clear (&stco64->entries);
831 }
832
833 static void
834 atom_stss_init (AtomSTSS * stss)
835 {
836   guint8 flags[3] = { 0, 0, 0 };
837
838   atom_full_init (&stss->header, FOURCC_stss, 0, 0, 0, flags);
839   atom_array_init (&stss->entries, 128);
840 }
841
842 static void
843 atom_stss_clear (AtomSTSS * stss)
844 {
845   atom_full_clear (&stss->header);
846   atom_array_clear (&stss->entries);
847 }
848
849 void
850 atom_stbl_init (AtomSTBL * stbl)
851 {
852   atom_header_set (&stbl->header, FOURCC_stbl, 0, 0);
853
854   atom_stts_init (&stbl->stts);
855   atom_stss_init (&stbl->stss);
856   atom_stsd_init (&stbl->stsd);
857   atom_stsz_init (&stbl->stsz);
858   atom_stsc_init (&stbl->stsc);
859   stbl->ctts = NULL;
860   stbl->svmi = NULL;
861
862   atom_co64_init (&stbl->stco64);
863 }
864
865 void
866 atom_stbl_clear (AtomSTBL * stbl)
867 {
868   atom_clear (&stbl->header);
869   atom_stsd_clear (&stbl->stsd);
870   atom_stts_clear (&stbl->stts);
871   atom_stss_clear (&stbl->stss);
872   atom_stsc_clear (&stbl->stsc);
873   atom_stsz_clear (&stbl->stsz);
874   if (stbl->ctts) {
875     atom_ctts_free (stbl->ctts);
876   }
877   if (stbl->svmi) {
878     atom_svmi_free (stbl->svmi);
879   }
880   atom_stco64_clear (&stbl->stco64);
881 }
882
883 static void
884 atom_vmhd_init (AtomVMHD * vmhd, AtomsContext * context)
885 {
886   guint8 flags[3] = { 0, 0, 1 };
887
888   atom_full_init (&vmhd->header, FOURCC_vmhd, 0, 0, 0, flags);
889   vmhd->graphics_mode = 0x0;
890   memset (vmhd->opcolor, 0, sizeof (guint16) * 3);
891
892   if (context->flavor == ATOMS_TREE_FLAVOR_MOV) {
893     vmhd->graphics_mode = 0x40;
894     vmhd->opcolor[0] = 32768;
895     vmhd->opcolor[1] = 32768;
896     vmhd->opcolor[2] = 32768;
897   }
898 }
899
900 static AtomVMHD *
901 atom_vmhd_new (AtomsContext * context)
902 {
903   AtomVMHD *vmhd = g_new0 (AtomVMHD, 1);
904
905   atom_vmhd_init (vmhd, context);
906   return vmhd;
907 }
908
909 static void
910 atom_vmhd_free (AtomVMHD * vmhd)
911 {
912   atom_full_clear (&vmhd->header);
913   g_free (vmhd);
914 }
915
916 static void
917 atom_smhd_init (AtomSMHD * smhd)
918 {
919   guint8 flags[3] = { 0, 0, 0 };
920
921   atom_full_init (&smhd->header, FOURCC_smhd, 0, 0, 0, flags);
922   smhd->balance = 0;
923   smhd->reserved = 0;
924 }
925
926 static AtomSMHD *
927 atom_smhd_new (void)
928 {
929   AtomSMHD *smhd = g_new0 (AtomSMHD, 1);
930
931   atom_smhd_init (smhd);
932   return smhd;
933 }
934
935 static void
936 atom_smhd_free (AtomSMHD * smhd)
937 {
938   atom_full_clear (&smhd->header);
939   g_free (smhd);
940 }
941
942 static void
943 atom_hmhd_free (AtomHMHD * hmhd)
944 {
945   atom_full_clear (&hmhd->header);
946   g_free (hmhd);
947 }
948
949 static void
950 atom_hdlr_init (AtomHDLR * hdlr, AtomsContext * context)
951 {
952   guint8 flags[3] = { 0, 0, 0 };
953
954   atom_full_init (&hdlr->header, FOURCC_hdlr, 0, 0, 0, flags);
955
956   hdlr->component_type = 0;
957   hdlr->handler_type = 0;
958   hdlr->manufacturer = 0;
959   hdlr->flags = 0;
960   hdlr->flags_mask = 0;
961   hdlr->name = g_strdup ("");
962
963   /* Store the flavor to know how to serialize the 'name' string */
964   hdlr->flavor = context->flavor;
965 }
966
967 static AtomHDLR *
968 atom_hdlr_new (AtomsContext * context)
969 {
970   AtomHDLR *hdlr = g_new0 (AtomHDLR, 1);
971
972   atom_hdlr_init (hdlr, context);
973   return hdlr;
974 }
975
976 static void
977 atom_hdlr_clear (AtomHDLR * hdlr)
978 {
979   atom_full_clear (&hdlr->header);
980   if (hdlr->name) {
981     g_free (hdlr->name);
982     hdlr->name = NULL;
983   }
984 }
985
986 static void
987 atom_hdlr_free (AtomHDLR * hdlr)
988 {
989   atom_hdlr_clear (hdlr);
990   g_free (hdlr);
991 }
992
993 static void
994 atom_url_init (AtomURL * url)
995 {
996   guint8 flags[3] = { 0, 0, 1 };
997
998   atom_full_init (&url->header, FOURCC_url_, 0, 0, 0, flags);
999   url->location = NULL;
1000 }
1001
1002 static void
1003 atom_url_free (AtomURL * url)
1004 {
1005   atom_full_clear (&url->header);
1006   if (url->location) {
1007     g_free (url->location);
1008     url->location = NULL;
1009   }
1010   g_free (url);
1011 }
1012
1013 static AtomURL *
1014 atom_url_new (void)
1015 {
1016   AtomURL *url = g_new0 (AtomURL, 1);
1017
1018   atom_url_init (url);
1019   return url;
1020 }
1021
1022 static AtomFull *
1023 atom_alis_new (void)
1024 {
1025   guint8 flags[3] = { 0, 0, 1 };
1026   AtomFull *alis = g_new0 (AtomFull, 1);
1027
1028   atom_full_init (alis, FOURCC_alis, 0, 0, 0, flags);
1029   return alis;
1030 }
1031
1032 static void
1033 atom_dref_init (AtomDREF * dref, AtomsContext * context)
1034 {
1035   guint8 flags[3] = { 0, 0, 0 };
1036
1037   atom_full_init (&dref->header, FOURCC_dref, 0, 0, 0, flags);
1038
1039   /* in either case, alis or url init arranges to set self-contained flag */
1040   if (context->flavor == ATOMS_TREE_FLAVOR_MOV) {
1041     /* alis dref for qt */
1042     AtomFull *alis = atom_alis_new ();
1043     dref->entries = g_list_append (dref->entries, alis);
1044   } else {
1045     /* url for iso spec, as 'alis' not specified there */
1046     AtomURL *url = atom_url_new ();
1047     dref->entries = g_list_append (dref->entries, url);
1048   }
1049 }
1050
1051 static void
1052 atom_dref_clear (AtomDREF * dref)
1053 {
1054   GList *walker;
1055
1056   atom_full_clear (&dref->header);
1057   walker = dref->entries;
1058   while (walker) {
1059     GList *aux = walker;
1060     Atom *atom = (Atom *) aux->data;
1061
1062     walker = g_list_next (walker);
1063     dref->entries = g_list_remove_link (dref->entries, aux);
1064     switch (atom->type) {
1065       case FOURCC_alis:
1066         atom_full_free ((AtomFull *) atom);
1067         break;
1068       case FOURCC_url_:
1069         atom_url_free ((AtomURL *) atom);
1070         break;
1071       default:
1072         /* we do nothing, better leak than crash */
1073         break;
1074     }
1075     g_list_free (aux);
1076   }
1077 }
1078
1079 static void
1080 atom_dinf_init (AtomDINF * dinf, AtomsContext * context)
1081 {
1082   atom_header_set (&dinf->header, FOURCC_dinf, 0, 0);
1083   atom_dref_init (&dinf->dref, context);
1084 }
1085
1086 static void
1087 atom_dinf_clear (AtomDINF * dinf)
1088 {
1089   atom_clear (&dinf->header);
1090   atom_dref_clear (&dinf->dref);
1091 }
1092
1093 static void
1094 atom_minf_init (AtomMINF * minf, AtomsContext * context)
1095 {
1096   atom_header_set (&minf->header, FOURCC_minf, 0, 0);
1097
1098   minf->vmhd = NULL;
1099   minf->smhd = NULL;
1100   minf->hmhd = NULL;
1101   minf->gmhd = NULL;
1102
1103   if (context->flavor == ATOMS_TREE_FLAVOR_MOV) {
1104     minf->hdlr = atom_hdlr_new (context);
1105     minf->hdlr->component_type = FOURCC_dhlr;
1106     minf->hdlr->handler_type = FOURCC_alis;
1107   } else {
1108     minf->hdlr = NULL;
1109   }
1110   atom_dinf_init (&minf->dinf, context);
1111   atom_stbl_init (&minf->stbl);
1112 }
1113
1114 static void
1115 atom_minf_clear_handlers (AtomMINF * minf)
1116 {
1117   if (minf->vmhd) {
1118     atom_vmhd_free (minf->vmhd);
1119     minf->vmhd = NULL;
1120   }
1121   if (minf->smhd) {
1122     atom_smhd_free (minf->smhd);
1123     minf->smhd = NULL;
1124   }
1125   if (minf->hmhd) {
1126     atom_hmhd_free (minf->hmhd);
1127     minf->hmhd = NULL;
1128   }
1129   if (minf->gmhd) {
1130     atom_gmhd_free (minf->gmhd);
1131     minf->gmhd = NULL;
1132   }
1133 }
1134
1135 static void
1136 atom_minf_clear (AtomMINF * minf)
1137 {
1138   atom_clear (&minf->header);
1139   atom_minf_clear_handlers (minf);
1140   if (minf->hdlr) {
1141     atom_hdlr_free (minf->hdlr);
1142   }
1143   atom_dinf_clear (&minf->dinf);
1144   atom_stbl_clear (&minf->stbl);
1145 }
1146
1147 static void
1148 atom_mdhd_init (AtomMDHD * mdhd)
1149 {
1150   guint8 flags[3] = { 0, 0, 0 };
1151
1152   atom_full_init (&mdhd->header, FOURCC_mdhd, 0, 0, 0, flags);
1153   common_time_info_init (&mdhd->time_info);
1154   /* tempting as it may be to simply 0-initialize,
1155    * that will have the demuxer (correctly) come up with 'eng' as language
1156    * so explicitly specify undefined instead */
1157   mdhd->language_code =
1158       ('u' - 0x60) * 0x400 + ('n' - 0x60) * 0x20 + ('d' - 0x60);
1159   mdhd->quality = 0;
1160 }
1161
1162 static void
1163 atom_mdhd_clear (AtomMDHD * mdhd)
1164 {
1165   atom_full_clear (&mdhd->header);
1166 }
1167
1168 static void
1169 atom_mdia_init (AtomMDIA * mdia, AtomsContext * context)
1170 {
1171   atom_header_set (&mdia->header, FOURCC_mdia, 0, 0);
1172
1173   atom_mdhd_init (&mdia->mdhd);
1174   atom_hdlr_init (&mdia->hdlr, context);
1175   atom_minf_init (&mdia->minf, context);
1176 }
1177
1178 static void
1179 atom_mdia_clear (AtomMDIA * mdia)
1180 {
1181   atom_clear (&mdia->header);
1182   atom_mdhd_clear (&mdia->mdhd);
1183   atom_hdlr_clear (&mdia->hdlr);
1184   atom_minf_clear (&mdia->minf);
1185 }
1186
1187 static void
1188 atom_tkhd_init (AtomTKHD * tkhd, AtomsContext * context)
1189 {
1190   /*
1191    * flags info
1192    * 1 -> track enabled
1193    * 2 -> track in movie
1194    * 4 -> track in preview
1195    */
1196   guint8 flags[3] = { 0, 0, 7 };
1197
1198   atom_full_init (&tkhd->header, FOURCC_tkhd, 0, 0, 0, flags);
1199
1200   tkhd->creation_time = tkhd->modification_time = atoms_get_current_qt_time ();
1201   tkhd->duration = 0;
1202   tkhd->track_ID = 0;
1203   tkhd->reserved = 0;
1204
1205   tkhd->reserved2[0] = tkhd->reserved2[1] = 0;
1206   tkhd->layer = 0;
1207   tkhd->alternate_group = 0;
1208   tkhd->volume = 0;
1209   tkhd->reserved3 = 0;
1210   memset (tkhd->matrix, 0, sizeof (guint32) * 9);
1211   tkhd->matrix[0] = 1 << 16;
1212   tkhd->matrix[4] = 1 << 16;
1213   tkhd->matrix[8] = 16384 << 16;
1214   tkhd->width = 0;
1215   tkhd->height = 0;
1216 }
1217
1218 static void
1219 atom_tkhd_clear (AtomTKHD * tkhd)
1220 {
1221   atom_full_clear (&tkhd->header);
1222 }
1223
1224 static void
1225 atom_ilst_init (AtomILST * ilst)
1226 {
1227   atom_header_set (&ilst->header, FOURCC_ilst, 0, 0);
1228   ilst->entries = NULL;
1229 }
1230
1231 static AtomILST *
1232 atom_ilst_new (void)
1233 {
1234   AtomILST *ilst = g_new0 (AtomILST, 1);
1235
1236   atom_ilst_init (ilst);
1237   return ilst;
1238 }
1239
1240 static void
1241 atom_ilst_free (AtomILST * ilst)
1242 {
1243   if (ilst->entries)
1244     atom_info_list_free (ilst->entries);
1245   atom_clear (&ilst->header);
1246   g_free (ilst);
1247 }
1248
1249 static void
1250 atom_meta_init (AtomMETA * meta, AtomsContext * context)
1251 {
1252   guint8 flags[3] = { 0, 0, 0 };
1253
1254   atom_full_init (&meta->header, FOURCC_meta, 0, 0, 0, flags);
1255   atom_hdlr_init (&meta->hdlr, context);
1256   /* FIXME (ISOM says this is always 0) */
1257   meta->hdlr.component_type = FOURCC_mhlr;
1258   meta->hdlr.handler_type = FOURCC_mdir;
1259   meta->ilst = NULL;
1260 }
1261
1262 static AtomMETA *
1263 atom_meta_new (AtomsContext * context)
1264 {
1265   AtomMETA *meta = g_new0 (AtomMETA, 1);
1266
1267   atom_meta_init (meta, context);
1268   return meta;
1269 }
1270
1271 static void
1272 atom_meta_free (AtomMETA * meta)
1273 {
1274   atom_full_clear (&meta->header);
1275   atom_hdlr_clear (&meta->hdlr);
1276   if (meta->ilst)
1277     atom_ilst_free (meta->ilst);
1278   meta->ilst = NULL;
1279   g_free (meta);
1280 }
1281
1282 static void
1283 atom_udta_init_metatags (AtomUDTA * udta, AtomsContext * context)
1284 {
1285   if (context->flavor != ATOMS_TREE_FLAVOR_3GP) {
1286     if (!udta->meta) {
1287       udta->meta = atom_meta_new (context);
1288     }
1289     if (!udta->meta->ilst) {
1290       udta->meta->ilst = atom_ilst_new ();
1291     }
1292   }
1293 }
1294
1295 static void
1296 atom_udta_init (AtomUDTA * udta, AtomsContext * context)
1297 {
1298   atom_header_set (&udta->header, FOURCC_udta, 0, 0);
1299   udta->meta = NULL;
1300   udta->context = context;
1301
1302   atom_udta_init_metatags (udta, context);
1303 }
1304
1305 static void
1306 atom_udta_clear (AtomUDTA * udta)
1307 {
1308   atom_clear (&udta->header);
1309   if (udta->meta)
1310     atom_meta_free (udta->meta);
1311   udta->meta = NULL;
1312   if (udta->entries)
1313     atom_info_list_free (udta->entries);
1314 }
1315
1316 static void
1317 atom_tref_init (AtomTREF * tref, guint32 reftype)
1318 {
1319   atom_header_set (&tref->header, FOURCC_tref, 0, 0);
1320   tref->reftype = reftype;
1321   atom_array_init (&tref->entries, 128);
1322 }
1323
1324 static void
1325 atom_tref_clear (AtomTREF * tref)
1326 {
1327   atom_clear (&tref->header);
1328   tref->reftype = 0;
1329   atom_array_clear (&tref->entries);
1330 }
1331
1332 AtomTREF *
1333 atom_tref_new (guint32 reftype)
1334 {
1335   AtomTREF *tref;
1336
1337   tref = g_new0 (AtomTREF, 1);
1338   atom_tref_init (tref, reftype);
1339
1340   return tref;
1341 }
1342
1343 static void
1344 atom_tref_free (AtomTREF * tref)
1345 {
1346   atom_tref_clear (tref);
1347   g_free (tref);
1348 }
1349
1350 /* Clear added tags, but keep the context/flavor the same */
1351 void
1352 atom_udta_clear_tags (AtomUDTA * udta)
1353 {
1354   if (udta->entries) {
1355     atom_info_list_free (udta->entries);
1356     udta->entries = NULL;
1357   }
1358   if (udta->meta && udta->meta->ilst->entries) {
1359     atom_info_list_free (udta->meta->ilst->entries);
1360     udta->meta->ilst->entries = NULL;
1361   }
1362 }
1363
1364 static void
1365 atom_tag_data_init (AtomTagData * data)
1366 {
1367   guint8 flags[] = { 0, 0, 0 };
1368
1369   atom_full_init (&data->header, FOURCC_data, 0, 0, 0, flags);
1370 }
1371
1372 static void
1373 atom_tag_data_clear (AtomTagData * data)
1374 {
1375   atom_full_clear (&data->header);
1376   g_free (data->data);
1377   data->datalen = 0;
1378 }
1379
1380 /*
1381  * Fourcc is the tag fourcc
1382  * flags will be truncated to 24bits
1383  */
1384 static AtomTag *
1385 atom_tag_new (guint32 fourcc, guint32 flags_as_uint)
1386 {
1387   AtomTag *tag = g_new0 (AtomTag, 1);
1388
1389   tag->header.type = fourcc;
1390   atom_tag_data_init (&tag->data);
1391   atom_full_set_flags_as_uint (&tag->data.header, flags_as_uint);
1392   return tag;
1393 }
1394
1395 static void
1396 atom_tag_free (AtomTag * tag)
1397 {
1398   atom_clear (&tag->header);
1399   atom_tag_data_clear (&tag->data);
1400   g_free (tag);
1401 }
1402
1403 static void
1404 atom_mvhd_init (AtomMVHD * mvhd)
1405 {
1406   guint8 flags[3] = { 0, 0, 0 };
1407
1408   atom_full_init (&(mvhd->header), FOURCC_mvhd, sizeof (AtomMVHD), 0, 0, flags);
1409
1410   common_time_info_init (&mvhd->time_info);
1411
1412   mvhd->prefered_rate = 1 << 16;
1413   mvhd->volume = 1 << 8;
1414   mvhd->reserved3 = 0;
1415   memset (mvhd->reserved4, 0, sizeof (guint32[2]));
1416
1417   memset (mvhd->matrix, 0, sizeof (guint32[9]));
1418   mvhd->matrix[0] = 1 << 16;
1419   mvhd->matrix[4] = 1 << 16;
1420   mvhd->matrix[8] = 16384 << 16;
1421
1422   mvhd->preview_time = 0;
1423   mvhd->preview_duration = 0;
1424   mvhd->poster_time = 0;
1425   mvhd->selection_time = 0;
1426   mvhd->selection_duration = 0;
1427   mvhd->current_time = 0;
1428
1429   mvhd->next_track_id = 1;
1430 }
1431
1432 static void
1433 atom_mvhd_clear (AtomMVHD * mvhd)
1434 {
1435   atom_full_clear (&mvhd->header);
1436 }
1437
1438 static void
1439 atom_mehd_init (AtomMEHD * mehd)
1440 {
1441   guint8 flags[3] = { 0, 0, 0 };
1442
1443   atom_full_init (&mehd->header, FOURCC_mehd, 0, 0, 1, flags);
1444   mehd->fragment_duration = 0;
1445 }
1446
1447 static void
1448 atom_mvex_init (AtomMVEX * mvex)
1449 {
1450   atom_header_set (&mvex->header, FOURCC_mvex, 0, 0);
1451   atom_mehd_init (&mvex->mehd);
1452   mvex->trexs = NULL;
1453 }
1454
1455 static void
1456 atom_trak_init (AtomTRAK * trak, AtomsContext * context)
1457 {
1458   atom_header_set (&trak->header, FOURCC_trak, 0, 0);
1459
1460   atom_tkhd_init (&trak->tkhd, context);
1461   trak->context = context;
1462   atom_udta_init (&trak->udta, context);
1463   trak->edts = NULL;
1464   atom_mdia_init (&trak->mdia, context);
1465   trak->tref = NULL;
1466 }
1467
1468 AtomTRAK *
1469 atom_trak_new (AtomsContext * context)
1470 {
1471   AtomTRAK *trak = g_new0 (AtomTRAK, 1);
1472
1473   atom_trak_init (trak, context);
1474   return trak;
1475 }
1476
1477 static void
1478 atom_trak_clear (AtomTRAK * trak)
1479 {
1480   atom_clear (&trak->header);
1481   atom_tkhd_clear (&trak->tkhd);
1482   if (trak->edts)
1483     atom_edts_free (trak->edts);
1484   atom_udta_clear (&trak->udta);
1485   atom_mdia_clear (&trak->mdia);
1486   if (trak->tref)
1487     atom_tref_free (trak->tref);
1488 }
1489
1490 static void
1491 atom_trak_free (AtomTRAK * trak)
1492 {
1493   atom_trak_clear (trak);
1494   g_free (trak);
1495 }
1496
1497
1498 static void
1499 atom_moov_init (AtomMOOV * moov, AtomsContext * context)
1500 {
1501   atom_header_set (&(moov->header), FOURCC_moov, 0, 0);
1502   atom_mvhd_init (&(moov->mvhd));
1503   atom_mvex_init (&(moov->mvex));
1504   atom_udta_init (&moov->udta, context);
1505   moov->traks = NULL;
1506   moov->context = *context;
1507 }
1508
1509 AtomMOOV *
1510 atom_moov_new (AtomsContext * context)
1511 {
1512   AtomMOOV *moov = g_new0 (AtomMOOV, 1);
1513
1514   atom_moov_init (moov, context);
1515   return moov;
1516 }
1517
1518 static void
1519 atom_trex_free (AtomTREX * trex)
1520 {
1521   atom_full_clear (&trex->header);
1522   g_free (trex);
1523 }
1524
1525 static void
1526 atom_mvex_clear (AtomMVEX * mvex)
1527 {
1528   GList *walker;
1529
1530   atom_clear (&mvex->header);
1531   walker = mvex->trexs;
1532   while (walker) {
1533     atom_trex_free ((AtomTREX *) walker->data);
1534     walker = g_list_next (walker);
1535   }
1536   g_list_free (mvex->trexs);
1537   mvex->trexs = NULL;
1538 }
1539
1540 void
1541 atom_moov_free (AtomMOOV * moov)
1542 {
1543   GList *walker;
1544
1545   atom_clear (&moov->header);
1546   atom_mvhd_clear (&moov->mvhd);
1547
1548   walker = moov->traks;
1549   while (walker) {
1550     atom_trak_free ((AtomTRAK *) walker->data);
1551     walker = g_list_next (walker);
1552   }
1553   g_list_free (moov->traks);
1554   moov->traks = NULL;
1555
1556   atom_udta_clear (&moov->udta);
1557   atom_mvex_clear (&moov->mvex);
1558
1559   g_free (moov);
1560 }
1561
1562 /* -- end of init / free -- */
1563
1564 /* -- copy data functions -- */
1565
1566 static guint8
1567 atom_full_get_version (AtomFull * full)
1568 {
1569   return full->version;
1570 }
1571
1572 static guint64
1573 common_time_info_copy_data (TimeInfo * ti, gboolean trunc_to_32,
1574     guint8 ** buffer, guint64 * size, guint64 * offset)
1575 {
1576   guint64 original_offset = *offset;
1577
1578   if (trunc_to_32) {
1579     prop_copy_uint32 ((guint32) ti->creation_time, buffer, size, offset);
1580     prop_copy_uint32 ((guint32) ti->modification_time, buffer, size, offset);
1581     prop_copy_uint32 (ti->timescale, buffer, size, offset);
1582     prop_copy_uint32 ((guint32) ti->duration, buffer, size, offset);
1583   } else {
1584     prop_copy_uint64 (ti->creation_time, buffer, size, offset);
1585     prop_copy_uint64 (ti->modification_time, buffer, size, offset);
1586     prop_copy_uint32 (ti->timescale, buffer, size, offset);
1587     prop_copy_uint64 (ti->duration, buffer, size, offset);
1588   }
1589   return *offset - original_offset;
1590 }
1591
1592 static void
1593 atom_write_size (guint8 ** buffer, guint64 * size, guint64 * offset,
1594     guint64 atom_pos)
1595 {
1596   /* this only works for non-extended atom size, which is OK
1597    * (though it could be made to do mem_move, etc and write extended size) */
1598   prop_copy_uint32 (*offset - atom_pos, buffer, size, &atom_pos);
1599 }
1600
1601 static guint64
1602 atom_copy_empty (Atom * atom, guint8 ** buffer, guint64 * size,
1603     guint64 * offset)
1604 {
1605   guint64 original_offset = *offset;
1606
1607   prop_copy_uint32 (0, buffer, size, offset);
1608
1609   return *offset - original_offset;
1610 }
1611
1612 guint64
1613 atom_copy_data (Atom * atom, guint8 ** buffer, guint64 * size, guint64 * offset)
1614 {
1615   guint64 original_offset = *offset;
1616
1617   /* copies type and size */
1618   prop_copy_uint32 (atom->size, buffer, size, offset);
1619   prop_copy_fourcc (atom->type, buffer, size, offset);
1620
1621   /* extended size needed */
1622   if (atom->size == 1) {
1623     /* really should not happen other than with mdat atom;
1624      * would be a problem for size (re)write code, not to mention memory */
1625     g_return_val_if_fail (atom->type == FOURCC_mdat, 0);
1626     prop_copy_uint64 (atom->extended_size, buffer, size, offset);
1627   }
1628
1629   return *offset - original_offset;
1630 }
1631
1632 static guint64
1633 atom_full_copy_data (AtomFull * atom, guint8 ** buffer, guint64 * size,
1634     guint64 * offset)
1635 {
1636   guint64 original_offset = *offset;
1637
1638   if (!atom_copy_data (&atom->header, buffer, size, offset)) {
1639     return 0;
1640   }
1641
1642   prop_copy_uint8 (atom->version, buffer, size, offset);
1643   prop_copy_uint8_array (atom->flags, 3, buffer, size, offset);
1644
1645   atom_write_size (buffer, size, offset, original_offset);
1646   return *offset - original_offset;
1647 }
1648
1649 static guint64
1650 atom_info_list_copy_data (GList * ai, guint8 ** buffer, guint64 * size,
1651     guint64 * offset)
1652 {
1653   guint64 original_offset = *offset;
1654
1655   while (ai) {
1656     AtomInfo *info = (AtomInfo *) ai->data;
1657
1658     if (!info->copy_data_func (info->atom, buffer, size, offset)) {
1659       return 0;
1660     }
1661     ai = g_list_next (ai);
1662   }
1663
1664   return *offset - original_offset;
1665 }
1666
1667 static guint64
1668 atom_data_copy_data (AtomData * data, guint8 ** buffer, guint64 * size,
1669     guint64 * offset)
1670 {
1671   guint64 original_offset = *offset;
1672
1673   if (!atom_copy_data (&data->header, buffer, size, offset)) {
1674     return 0;
1675   }
1676   if (data->datalen)
1677     prop_copy_uint8_array (data->data, data->datalen, buffer, size, offset);
1678
1679   atom_write_size (buffer, size, offset, original_offset);
1680   return *offset - original_offset;
1681 }
1682
1683 static guint64
1684 atom_uuid_copy_data (AtomUUID * uuid, guint8 ** buffer, guint64 * size,
1685     guint64 * offset)
1686 {
1687   guint64 original_offset = *offset;
1688
1689   if (!atom_copy_data (&uuid->header, buffer, size, offset)) {
1690     return 0;
1691   }
1692   prop_copy_uint8_array (uuid->uuid, 16, buffer, size, offset);
1693   if (uuid->datalen)
1694     prop_copy_uint8_array (uuid->data, uuid->datalen, buffer, size, offset);
1695
1696   atom_write_size (buffer, size, offset, original_offset);
1697   return *offset - original_offset;
1698 }
1699
1700 guint64
1701 atom_ftyp_copy_data (AtomFTYP * ftyp, guint8 ** buffer, guint64 * size,
1702     guint64 * offset)
1703 {
1704   guint64 original_offset = *offset;
1705
1706   if (!atom_copy_data (&ftyp->header, buffer, size, offset)) {
1707     return 0;
1708   }
1709   prop_copy_fourcc (ftyp->major_brand, buffer, size, offset);
1710   prop_copy_uint32 (ftyp->version, buffer, size, offset);
1711
1712   prop_copy_fourcc_array (ftyp->compatible_brands, ftyp->compatible_brands_size,
1713       buffer, size, offset);
1714
1715   atom_write_size (buffer, size, offset, original_offset);
1716   return *offset - original_offset;
1717 }
1718
1719 guint64
1720 atom_mvhd_copy_data (AtomMVHD * atom, guint8 ** buffer, guint64 * size,
1721     guint64 * offset)
1722 {
1723   guint8 version;
1724   guint64 original_offset = *offset;
1725
1726   if (!atom_full_copy_data (&(atom->header), buffer, size, offset)) {
1727     return 0;
1728   }
1729
1730   version = atom_full_get_version (&(atom->header));
1731   if (version == 0) {
1732     common_time_info_copy_data (&atom->time_info, TRUE, buffer, size, offset);
1733   } else if (version == 1) {
1734     common_time_info_copy_data (&atom->time_info, FALSE, buffer, size, offset);
1735   } else {
1736     *offset = original_offset;
1737     return 0;
1738   }
1739
1740   prop_copy_uint32 (atom->prefered_rate, buffer, size, offset);
1741   prop_copy_uint16 (atom->volume, buffer, size, offset);
1742   prop_copy_uint16 (atom->reserved3, buffer, size, offset);
1743   prop_copy_uint32_array (atom->reserved4, 2, buffer, size, offset);
1744   prop_copy_uint32_array (atom->matrix, 9, buffer, size, offset);
1745   prop_copy_uint32 (atom->preview_time, buffer, size, offset);
1746   prop_copy_uint32 (atom->preview_duration, buffer, size, offset);
1747   prop_copy_uint32 (atom->poster_time, buffer, size, offset);
1748   prop_copy_uint32 (atom->selection_time, buffer, size, offset);
1749   prop_copy_uint32 (atom->selection_duration, buffer, size, offset);
1750   prop_copy_uint32 (atom->current_time, buffer, size, offset);
1751
1752   prop_copy_uint32 (atom->next_track_id, buffer, size, offset);
1753
1754   atom_write_size (buffer, size, offset, original_offset);
1755   return *offset - original_offset;
1756 }
1757
1758 static guint64
1759 atom_tkhd_copy_data (AtomTKHD * tkhd, guint8 ** buffer, guint64 * size,
1760     guint64 * offset)
1761 {
1762   guint64 original_offset = *offset;
1763
1764   if (!atom_full_copy_data (&tkhd->header, buffer, size, offset)) {
1765     return 0;
1766   }
1767
1768   if (atom_full_get_version (&tkhd->header) == 0) {
1769     prop_copy_uint32 ((guint32) tkhd->creation_time, buffer, size, offset);
1770     prop_copy_uint32 ((guint32) tkhd->modification_time, buffer, size, offset);
1771     prop_copy_uint32 (tkhd->track_ID, buffer, size, offset);
1772     prop_copy_uint32 (tkhd->reserved, buffer, size, offset);
1773     prop_copy_uint32 ((guint32) tkhd->duration, buffer, size, offset);
1774   } else {
1775     prop_copy_uint64 (tkhd->creation_time, buffer, size, offset);
1776     prop_copy_uint64 (tkhd->modification_time, buffer, size, offset);
1777     prop_copy_uint32 (tkhd->track_ID, buffer, size, offset);
1778     prop_copy_uint32 (tkhd->reserved, buffer, size, offset);
1779     prop_copy_uint64 (tkhd->duration, buffer, size, offset);
1780   }
1781
1782   prop_copy_uint32_array (tkhd->reserved2, 2, buffer, size, offset);
1783   prop_copy_uint16 (tkhd->layer, buffer, size, offset);
1784   prop_copy_uint16 (tkhd->alternate_group, buffer, size, offset);
1785   prop_copy_uint16 (tkhd->volume, buffer, size, offset);
1786   prop_copy_uint16 (tkhd->reserved3, buffer, size, offset);
1787   prop_copy_uint32_array (tkhd->matrix, 9, buffer, size, offset);
1788
1789   prop_copy_uint32 (tkhd->width, buffer, size, offset);
1790   prop_copy_uint32 (tkhd->height, buffer, size, offset);
1791
1792   atom_write_size (buffer, size, offset, original_offset);
1793   return *offset - original_offset;
1794 }
1795
1796 static guint64
1797 atom_hdlr_copy_data (AtomHDLR * hdlr, guint8 ** buffer, guint64 * size,
1798     guint64 * offset)
1799 {
1800   guint64 original_offset = *offset;
1801
1802   if (!atom_full_copy_data (&hdlr->header, buffer, size, offset)) {
1803     return 0;
1804   }
1805
1806   prop_copy_fourcc (hdlr->component_type, buffer, size, offset);
1807   prop_copy_fourcc (hdlr->handler_type, buffer, size, offset);
1808   prop_copy_fourcc (hdlr->manufacturer, buffer, size, offset);
1809   prop_copy_uint32 (hdlr->flags, buffer, size, offset);
1810   prop_copy_uint32 (hdlr->flags_mask, buffer, size, offset);
1811
1812   if (hdlr->flavor == ATOMS_TREE_FLAVOR_MOV) {
1813     prop_copy_size_string ((guint8 *) hdlr->name, strlen (hdlr->name), buffer,
1814         size, offset);
1815   } else {
1816     /* assume isomedia base is more generic and use null terminated */
1817     prop_copy_null_terminated_string (hdlr->name, buffer, size, offset);
1818   }
1819
1820   atom_write_size (buffer, size, offset, original_offset);
1821   return *offset - original_offset;
1822 }
1823
1824 static guint64
1825 atom_vmhd_copy_data (AtomVMHD * vmhd, guint8 ** buffer, guint64 * size,
1826     guint64 * offset)
1827 {
1828   guint64 original_offset = *offset;
1829
1830   if (!atom_full_copy_data (&vmhd->header, buffer, size, offset)) {
1831     return 0;
1832   }
1833   prop_copy_uint16 (vmhd->graphics_mode, buffer, size, offset);
1834   prop_copy_uint16_array (vmhd->opcolor, 3, buffer, size, offset);
1835
1836   atom_write_size (buffer, size, offset, original_offset);
1837   return original_offset - *offset;
1838 }
1839
1840 static guint64
1841 atom_smhd_copy_data (AtomSMHD * smhd, guint8 ** buffer, guint64 * size,
1842     guint64 * offset)
1843 {
1844   guint64 original_offset = *offset;
1845
1846   if (!atom_full_copy_data (&smhd->header, buffer, size, offset)) {
1847     return 0;
1848   }
1849   prop_copy_uint16 (smhd->balance, buffer, size, offset);
1850   prop_copy_uint16 (smhd->reserved, buffer, size, offset);
1851
1852   atom_write_size (buffer, size, offset, original_offset);
1853   return original_offset - *offset;
1854 }
1855
1856 static guint64
1857 atom_hmhd_copy_data (AtomHMHD * hmhd, guint8 ** buffer, guint64 * size,
1858     guint64 * offset)
1859 {
1860   guint64 original_offset = *offset;
1861
1862   if (!atom_full_copy_data (&hmhd->header, buffer, size, offset)) {
1863     return 0;
1864   }
1865   prop_copy_uint16 (hmhd->max_pdu_size, buffer, size, offset);
1866   prop_copy_uint16 (hmhd->avg_pdu_size, buffer, size, offset);
1867   prop_copy_uint32 (hmhd->max_bitrate, buffer, size, offset);
1868   prop_copy_uint32 (hmhd->avg_bitrate, buffer, size, offset);
1869   prop_copy_uint32 (hmhd->sliding_avg_bitrate, buffer, size, offset);
1870
1871   atom_write_size (buffer, size, offset, original_offset);
1872   return original_offset - *offset;
1873 }
1874
1875 static guint64
1876 atom_tcmi_copy_data (AtomTCMI * tcmi, guint8 ** buffer, guint64 * size,
1877     guint64 * offset)
1878 {
1879   guint64 original_offset = *offset;
1880
1881   if (!atom_full_copy_data (&tcmi->header, buffer, size, offset)) {
1882     return 0;
1883   }
1884   prop_copy_uint16 (tcmi->text_font, buffer, size, offset);
1885   prop_copy_uint16 (tcmi->text_face, buffer, size, offset);
1886   prop_copy_uint16 (tcmi->text_size, buffer, size, offset);
1887   prop_copy_uint16 (tcmi->text_color[0], buffer, size, offset);
1888   prop_copy_uint16 (tcmi->text_color[1], buffer, size, offset);
1889   prop_copy_uint16 (tcmi->text_color[2], buffer, size, offset);
1890   prop_copy_uint16 (tcmi->bg_color[0], buffer, size, offset);
1891   prop_copy_uint16 (tcmi->bg_color[1], buffer, size, offset);
1892   prop_copy_uint16 (tcmi->bg_color[2], buffer, size, offset);
1893   /* reserved */
1894   prop_copy_uint16 (0, buffer, size, offset);
1895   prop_copy_size_string ((guint8 *) tcmi->font_name, strlen (tcmi->font_name),
1896       buffer, size, offset);
1897
1898   atom_write_size (buffer, size, offset, original_offset);
1899   return original_offset - *offset;
1900 }
1901
1902 static guint64
1903 atom_tmcd_copy_data (AtomTMCD * tmcd, guint8 ** buffer, guint64 * size,
1904     guint64 * offset)
1905 {
1906   guint64 original_offset = *offset;
1907
1908   if (!atom_copy_data (&tmcd->header, buffer, size, offset)) {
1909     return 0;
1910   }
1911   if (!atom_tcmi_copy_data (&tmcd->tcmi, buffer, size, offset)) {
1912     return 0;
1913   }
1914
1915   atom_write_size (buffer, size, offset, original_offset);
1916   return original_offset - *offset;
1917 }
1918
1919 static guint64
1920 atom_gmin_copy_data (AtomGMIN * gmin, guint8 ** buffer, guint64 * size,
1921     guint64 * offset)
1922 {
1923   guint64 original_offset = *offset;
1924
1925   if (!atom_full_copy_data (&gmin->header, buffer, size, offset)) {
1926     return 0;
1927   }
1928   prop_copy_uint16 (gmin->graphics_mode, buffer, size, offset);
1929   prop_copy_uint16 (gmin->opcolor[0], buffer, size, offset);
1930   prop_copy_uint16 (gmin->opcolor[1], buffer, size, offset);
1931   prop_copy_uint16 (gmin->opcolor[2], buffer, size, offset);
1932   prop_copy_uint8 (gmin->balance, buffer, size, offset);
1933   /* reserved */
1934   prop_copy_uint8 (0, buffer, size, offset);
1935
1936   atom_write_size (buffer, size, offset, original_offset);
1937   return original_offset - *offset;
1938 }
1939
1940 static guint64
1941 atom_gmhd_copy_data (AtomGMHD * gmhd, guint8 ** buffer, guint64 * size,
1942     guint64 * offset)
1943 {
1944   guint64 original_offset = *offset;
1945
1946   if (!atom_copy_data (&gmhd->header, buffer, size, offset)) {
1947     return 0;
1948   }
1949   if (!atom_gmin_copy_data (&gmhd->gmin, buffer, size, offset)) {
1950     return 0;
1951   }
1952   if (gmhd->tmcd && !atom_tmcd_copy_data (gmhd->tmcd, buffer, size, offset)) {
1953     return 0;
1954   }
1955
1956   atom_write_size (buffer, size, offset, original_offset);
1957   return original_offset - *offset;
1958 }
1959
1960 static gboolean
1961 atom_url_same_file_flag (AtomURL * url)
1962 {
1963   return (url->header.flags[2] & 0x1) == 1;
1964 }
1965
1966 static guint64
1967 atom_url_copy_data (AtomURL * url, guint8 ** buffer, guint64 * size,
1968     guint64 * offset)
1969 {
1970   guint64 original_offset = *offset;
1971
1972   if (!atom_full_copy_data (&url->header, buffer, size, offset)) {
1973     return 0;
1974   }
1975
1976   if (!atom_url_same_file_flag (url)) {
1977     prop_copy_null_terminated_string (url->location, buffer, size, offset);
1978   }
1979
1980   atom_write_size (buffer, size, offset, original_offset);
1981   return original_offset - *offset;
1982 }
1983
1984 guint64
1985 atom_stts_copy_data (AtomSTTS * stts, guint8 ** buffer, guint64 * size,
1986     guint64 * offset)
1987 {
1988   guint64 original_offset = *offset;
1989   guint i;
1990
1991   if (!atom_full_copy_data (&stts->header, buffer, size, offset)) {
1992     return 0;
1993   }
1994
1995   prop_copy_uint32 (atom_array_get_len (&stts->entries), buffer, size, offset);
1996   /* minimize realloc */
1997   prop_copy_ensure_buffer (buffer, size, offset,
1998       8 * atom_array_get_len (&stts->entries));
1999   for (i = 0; i < atom_array_get_len (&stts->entries); i++) {
2000     STTSEntry *entry = &atom_array_index (&stts->entries, i);
2001
2002     prop_copy_uint32 (entry->sample_count, buffer, size, offset);
2003     prop_copy_int32 (entry->sample_delta, buffer, size, offset);
2004   }
2005
2006   atom_write_size (buffer, size, offset, original_offset);
2007   return *offset - original_offset;
2008 }
2009
2010 static guint64
2011 atom_sample_entry_copy_data (SampleTableEntry * se, guint8 ** buffer,
2012     guint64 * size, guint64 * offset)
2013 {
2014   guint64 original_offset = *offset;
2015
2016   if (!atom_copy_data (&se->header, buffer, size, offset)) {
2017     return 0;
2018   }
2019
2020   prop_copy_uint8_array (se->reserved, 6, buffer, size, offset);
2021   prop_copy_uint16 (se->data_reference_index, buffer, size, offset);
2022
2023   return *offset - original_offset;
2024 }
2025
2026 static guint64
2027 atom_esds_copy_data (AtomESDS * esds, guint8 ** buffer, guint64 * size,
2028     guint64 * offset)
2029 {
2030   guint64 original_offset = *offset;
2031
2032   if (!atom_full_copy_data (&esds->header, buffer, size, offset)) {
2033     return 0;
2034   }
2035   if (!desc_es_descriptor_copy_data (&esds->es, buffer, size, offset)) {
2036     return 0;
2037   }
2038
2039   atom_write_size (buffer, size, offset, original_offset);
2040   return *offset - original_offset;
2041 }
2042
2043 static guint64
2044 atom_frma_copy_data (AtomFRMA * frma, guint8 ** buffer,
2045     guint64 * size, guint64 * offset)
2046 {
2047   guint64 original_offset = *offset;
2048
2049   if (!atom_copy_data (&(frma->header), buffer, size, offset))
2050     return 0;
2051
2052   prop_copy_fourcc (frma->media_type, buffer, size, offset);
2053
2054   atom_write_size (buffer, size, offset, original_offset);
2055   return *offset - original_offset;
2056 }
2057
2058 static guint64
2059 atom_hint_sample_entry_copy_data (AtomHintSampleEntry * hse, guint8 ** buffer,
2060     guint64 * size, guint64 * offset)
2061 {
2062   guint64 original_offset = *offset;
2063
2064   if (!atom_sample_entry_copy_data (&hse->se, buffer, size, offset)) {
2065     return 0;
2066   }
2067
2068   prop_copy_uint32 (hse->size, buffer, size, offset);
2069   prop_copy_uint8_array (hse->data, hse->size, buffer, size, offset);
2070
2071   atom_write_size (buffer, size, offset, original_offset);
2072   return *offset - original_offset;
2073 }
2074
2075 static guint64
2076 sample_entry_mp4a_copy_data (SampleTableEntryMP4A * mp4a, guint8 ** buffer,
2077     guint64 * size, guint64 * offset)
2078 {
2079   guint64 original_offset = *offset;
2080
2081   if (!atom_sample_entry_copy_data (&mp4a->se, buffer, size, offset)) {
2082     return 0;
2083   }
2084
2085   prop_copy_uint16 (mp4a->version, buffer, size, offset);
2086   prop_copy_uint16 (mp4a->revision_level, buffer, size, offset);
2087   prop_copy_uint32 (mp4a->vendor, buffer, size, offset);
2088   prop_copy_uint16 (mp4a->channels, buffer, size, offset);
2089   prop_copy_uint16 (mp4a->sample_size, buffer, size, offset);
2090   prop_copy_uint16 (mp4a->compression_id, buffer, size, offset);
2091   prop_copy_uint16 (mp4a->packet_size, buffer, size, offset);
2092   prop_copy_uint32 (mp4a->sample_rate, buffer, size, offset);
2093
2094   /* this should always be 0 for mp4 flavor */
2095   if (mp4a->version == 1) {
2096     prop_copy_uint32 (mp4a->samples_per_packet, buffer, size, offset);
2097     prop_copy_uint32 (mp4a->bytes_per_packet, buffer, size, offset);
2098     prop_copy_uint32 (mp4a->bytes_per_frame, buffer, size, offset);
2099     prop_copy_uint32 (mp4a->bytes_per_sample, buffer, size, offset);
2100   }
2101
2102   if (mp4a->extension_atoms) {
2103     if (!atom_info_list_copy_data (mp4a->extension_atoms, buffer, size, offset))
2104       return 0;
2105   }
2106
2107   atom_write_size (buffer, size, offset, original_offset);
2108   return *offset - original_offset;
2109 }
2110
2111 static guint64
2112 sample_entry_mp4v_copy_data (SampleTableEntryMP4V * mp4v, guint8 ** buffer,
2113     guint64 * size, guint64 * offset)
2114 {
2115   guint64 original_offset = *offset;
2116
2117   if (!atom_sample_entry_copy_data (&mp4v->se, buffer, size, offset)) {
2118     return 0;
2119   }
2120
2121   prop_copy_uint16 (mp4v->version, buffer, size, offset);
2122   prop_copy_uint16 (mp4v->revision_level, buffer, size, offset);
2123   prop_copy_fourcc (mp4v->vendor, buffer, size, offset);
2124   prop_copy_uint32 (mp4v->temporal_quality, buffer, size, offset);
2125   prop_copy_uint32 (mp4v->spatial_quality, buffer, size, offset);
2126
2127   prop_copy_uint16 (mp4v->width, buffer, size, offset);
2128   prop_copy_uint16 (mp4v->height, buffer, size, offset);
2129
2130   prop_copy_uint32 (mp4v->horizontal_resolution, buffer, size, offset);
2131   prop_copy_uint32 (mp4v->vertical_resolution, buffer, size, offset);
2132   prop_copy_uint32 (mp4v->datasize, buffer, size, offset);
2133
2134   prop_copy_uint16 (mp4v->frame_count, buffer, size, offset);
2135
2136   prop_copy_fixed_size_string ((guint8 *) mp4v->compressor, 32, buffer, size,
2137       offset);
2138
2139   prop_copy_uint16 (mp4v->depth, buffer, size, offset);
2140   prop_copy_uint16 (mp4v->color_table_id, buffer, size, offset);
2141
2142   /* extra atoms */
2143   if (mp4v->extension_atoms &&
2144       !atom_info_list_copy_data (mp4v->extension_atoms, buffer, size, offset))
2145     return 0;
2146
2147   atom_write_size (buffer, size, offset, original_offset);
2148   return *offset - original_offset;
2149 }
2150
2151 static guint64
2152 sample_entry_tx3g_copy_data (SampleTableEntryTX3G * tx3g, guint8 ** buffer,
2153     guint64 * size, guint64 * offset)
2154 {
2155   guint64 original_offset = *offset;
2156
2157   if (!atom_sample_entry_copy_data (&tx3g->se, buffer, size, offset)) {
2158     return 0;
2159   }
2160
2161   prop_copy_uint32 (tx3g->display_flags, buffer, size, offset);
2162
2163   /* reserved */
2164   prop_copy_uint8 (1, buffer, size, offset);
2165   prop_copy_uint8 (-1, buffer, size, offset);
2166   prop_copy_uint32 (0, buffer, size, offset);
2167
2168   prop_copy_uint64 (tx3g->default_text_box, buffer, size, offset);
2169
2170   /* reserved */
2171   prop_copy_uint32 (0, buffer, size, offset);
2172
2173   prop_copy_uint16 (tx3g->font_id, buffer, size, offset);
2174   prop_copy_uint8 (tx3g->font_face, buffer, size, offset);
2175   prop_copy_uint8 (tx3g->font_size, buffer, size, offset);
2176   prop_copy_uint32 (tx3g->foreground_color_rgba, buffer, size, offset);
2177
2178   /* it must have a fonttable atom */
2179   {
2180     Atom atom;
2181
2182     atom_header_set (&atom, FOURCC_ftab, 18, 0);
2183     if (!atom_copy_data (&atom, buffer, size, offset))
2184       return 0;
2185     prop_copy_uint16 (1, buffer, size, offset); /* Count must be 1 */
2186     prop_copy_uint16 (1, buffer, size, offset); /* Font id: 1 */
2187     prop_copy_size_string ((guint8 *) "Serif", 5, buffer, size, offset);
2188   }
2189
2190   atom_write_size (buffer, size, offset, original_offset);
2191   return *offset - original_offset;
2192 }
2193
2194 static guint64
2195 sample_entry_tmcd_copy_data (SampleTableEntryTMCD * tmcd, guint8 ** buffer,
2196     guint64 * size, guint64 * offset)
2197 {
2198   guint64 original_offset = *offset;
2199
2200   if (!atom_sample_entry_copy_data (&tmcd->se, buffer, size, offset)) {
2201     return 0;
2202   }
2203
2204   /* reserved */
2205   prop_copy_uint32 (0, buffer, size, offset);
2206
2207   prop_copy_uint32 (tmcd->tc_flags, buffer, size, offset);
2208   prop_copy_uint32 (tmcd->timescale, buffer, size, offset);
2209   prop_copy_uint32 (tmcd->frame_duration, buffer, size, offset);
2210   prop_copy_uint8 (tmcd->n_frames, buffer, size, offset);
2211
2212   /* reserved */
2213   prop_copy_uint8 (0, buffer, size, offset);
2214   {
2215     Atom atom;
2216     guint64 name_offset = *offset;
2217
2218     atom_header_set (&atom, FOURCC_name, 0, 0);
2219     if (!atom_copy_data (&atom, buffer, size, offset))
2220       return 0;
2221     prop_copy_uint16 (strlen (tmcd->name.name), buffer, size, offset);
2222     prop_copy_uint16 (tmcd->name.language_code, buffer, size, offset);
2223     prop_copy_fixed_size_string ((guint8 *) tmcd->name.name,
2224         strlen (tmcd->name.name), buffer, size, offset);
2225
2226     atom_write_size (buffer, size, offset, name_offset);
2227   }
2228
2229   atom_write_size (buffer, size, offset, original_offset);
2230   return *offset - original_offset;
2231 }
2232
2233 static guint64
2234 sample_entry_generic_copy_data (SampleTableEntry * entry, guint8 ** buffer,
2235     guint64 * size, guint64 * offset)
2236 {
2237   guint64 original_offset = *offset;
2238
2239   if (!atom_sample_entry_copy_data (entry, buffer, size, offset)) {
2240     return 0;
2241   }
2242
2243   atom_write_size (buffer, size, offset, original_offset);
2244   return *offset - original_offset;
2245 }
2246
2247 guint64
2248 atom_stsz_copy_data (AtomSTSZ * stsz, guint8 ** buffer, guint64 * size,
2249     guint64 * offset)
2250 {
2251   guint64 original_offset = *offset;
2252   guint i;
2253
2254   if (!atom_full_copy_data (&stsz->header, buffer, size, offset)) {
2255     return 0;
2256   }
2257
2258   prop_copy_uint32 (stsz->sample_size, buffer, size, offset);
2259   prop_copy_uint32 (stsz->table_size, buffer, size, offset);
2260   if (stsz->sample_size == 0) {
2261     /* minimize realloc */
2262     prop_copy_ensure_buffer (buffer, size, offset, 4 * stsz->table_size);
2263     /* entry count must match sample count */
2264     g_assert (atom_array_get_len (&stsz->entries) == stsz->table_size);
2265     for (i = 0; i < atom_array_get_len (&stsz->entries); i++) {
2266       prop_copy_uint32 (atom_array_index (&stsz->entries, i), buffer, size,
2267           offset);
2268     }
2269   }
2270
2271   atom_write_size (buffer, size, offset, original_offset);
2272   return *offset - original_offset;
2273 }
2274
2275 guint64
2276 atom_stsc_copy_data (AtomSTSC * stsc, guint8 ** buffer, guint64 * size,
2277     guint64 * offset)
2278 {
2279   guint64 original_offset = *offset;
2280   guint i, len;
2281   gboolean last_entries_merged = FALSE;
2282
2283   if (!atom_full_copy_data (&stsc->header, buffer, size, offset)) {
2284     return 0;
2285   }
2286
2287   /* Last two entries might be the same size here as we only merge once the
2288    * next chunk is started */
2289   if ((len = atom_array_get_len (&stsc->entries)) > 1 &&
2290       ((atom_array_index (&stsc->entries, len - 1)).samples_per_chunk ==
2291           (atom_array_index (&stsc->entries, len - 2)).samples_per_chunk)) {
2292     stsc->entries.len--;
2293     last_entries_merged = TRUE;
2294   }
2295
2296   prop_copy_uint32 (atom_array_get_len (&stsc->entries), buffer, size, offset);
2297   /* minimize realloc */
2298   prop_copy_ensure_buffer (buffer, size, offset,
2299       12 * atom_array_get_len (&stsc->entries));
2300
2301   for (i = 0; i < atom_array_get_len (&stsc->entries); i++) {
2302     STSCEntry *entry = &atom_array_index (&stsc->entries, i);
2303
2304     prop_copy_uint32 (entry->first_chunk, buffer, size, offset);
2305     prop_copy_uint32 (entry->samples_per_chunk, buffer, size, offset);
2306     prop_copy_uint32 (entry->sample_description_index, buffer, size, offset);
2307   }
2308
2309   atom_write_size (buffer, size, offset, original_offset);
2310
2311   /* Need to add the last entry again as in "robust" muxing mode we will most
2312    * likely add new samples to the last chunk, thus making the
2313    * samples_per_chunk in the last one different to the second to last one,
2314    * and thus making it wrong to keep them merged
2315    */
2316   if (last_entries_merged)
2317     stsc->entries.len++;
2318
2319   return *offset - original_offset;
2320 }
2321
2322 guint64
2323 atom_ctts_copy_data (AtomCTTS * ctts, guint8 ** buffer, guint64 * size,
2324     guint64 * offset)
2325 {
2326   guint64 original_offset = *offset;
2327   guint i;
2328
2329   if (!atom_full_copy_data (&ctts->header, buffer, size, offset)) {
2330     return 0;
2331   }
2332
2333   prop_copy_uint32 (atom_array_get_len (&ctts->entries), buffer, size, offset);
2334   /* minimize realloc */
2335   prop_copy_ensure_buffer (buffer, size, offset,
2336       8 * atom_array_get_len (&ctts->entries));
2337   for (i = 0; i < atom_array_get_len (&ctts->entries); i++) {
2338     CTTSEntry *entry = &atom_array_index (&ctts->entries, i);
2339
2340     prop_copy_uint32 (entry->samplecount, buffer, size, offset);
2341     prop_copy_uint32 (entry->sampleoffset, buffer, size, offset);
2342   }
2343
2344   atom_write_size (buffer, size, offset, original_offset);
2345   return *offset - original_offset;
2346 }
2347
2348 guint64
2349 atom_svmi_copy_data (AtomSVMI * svmi, guint8 ** buffer, guint64 * size,
2350     guint64 * offset)
2351 {
2352   guint64 original_offset = *offset;
2353
2354   if (!atom_full_copy_data (&svmi->header, buffer, size, offset)) {
2355     return 0;
2356   }
2357
2358   prop_copy_uint8 (svmi->stereoscopic_composition_type, buffer, size, offset);
2359   prop_copy_uint8 (svmi->is_left_first ? 1 : 0, buffer, size, offset);
2360   /* stereo-mono change count */
2361   prop_copy_uint32 (0, buffer, size, offset);
2362
2363   atom_write_size (buffer, size, offset, original_offset);
2364   return *offset - original_offset;
2365 }
2366
2367 guint64
2368 atom_stco64_copy_data (AtomSTCO64 * stco64, guint8 ** buffer, guint64 * size,
2369     guint64 * offset)
2370 {
2371   guint64 original_offset = *offset;
2372   guint i;
2373   gboolean trunc_to_32 = stco64->header.header.type == FOURCC_stco;
2374
2375   if (!atom_full_copy_data (&stco64->header, buffer, size, offset)) {
2376     return 0;
2377   }
2378
2379   prop_copy_uint32 (atom_array_get_len (&stco64->entries), buffer, size,
2380       offset);
2381
2382   /* minimize realloc */
2383   prop_copy_ensure_buffer (buffer, size, offset,
2384       8 * atom_array_get_len (&stco64->entries));
2385   for (i = 0; i < atom_array_get_len (&stco64->entries); i++) {
2386     guint64 value =
2387         atom_array_index (&stco64->entries, i) + stco64->chunk_offset;
2388
2389     if (trunc_to_32) {
2390       prop_copy_uint32 ((guint32) value, buffer, size, offset);
2391     } else {
2392       prop_copy_uint64 (value, buffer, size, offset);
2393     }
2394   }
2395
2396   atom_write_size (buffer, size, offset, original_offset);
2397   return *offset - original_offset;
2398 }
2399
2400 guint64
2401 atom_stss_copy_data (AtomSTSS * stss, guint8 ** buffer, guint64 * size,
2402     guint64 * offset)
2403 {
2404   guint64 original_offset = *offset;
2405   guint i;
2406
2407   if (atom_array_get_len (&stss->entries) == 0) {
2408     /* FIXME not needing this atom might be confused with error while copying */
2409     return 0;
2410   }
2411
2412   if (!atom_full_copy_data (&stss->header, buffer, size, offset)) {
2413     return 0;
2414   }
2415
2416   prop_copy_uint32 (atom_array_get_len (&stss->entries), buffer, size, offset);
2417   /* minimize realloc */
2418   prop_copy_ensure_buffer (buffer, size, offset,
2419       4 * atom_array_get_len (&stss->entries));
2420   for (i = 0; i < atom_array_get_len (&stss->entries); i++) {
2421     prop_copy_uint32 (atom_array_index (&stss->entries, i), buffer, size,
2422         offset);
2423   }
2424
2425   atom_write_size (buffer, size, offset, original_offset);
2426   return *offset - original_offset;
2427 }
2428
2429 static guint64
2430 atom_stsd_copy_data (AtomSTSD * stsd, guint8 ** buffer, guint64 * size,
2431     guint64 * offset)
2432 {
2433   guint64 original_offset = *offset;
2434   GList *walker;
2435
2436   if (!atom_full_copy_data (&stsd->header, buffer, size, offset)) {
2437     return 0;
2438   }
2439
2440   prop_copy_uint32 (stsd->n_entries, buffer, size, offset);
2441
2442   for (walker = g_list_last (stsd->entries); walker != NULL;
2443       walker = g_list_previous (walker)) {
2444     SampleTableEntry *se = (SampleTableEntry *) walker->data;
2445
2446     switch (((Atom *) walker->data)->type) {
2447       case FOURCC_mp4a:
2448         if (!sample_entry_mp4a_copy_data ((SampleTableEntryMP4A *) walker->data,
2449                 buffer, size, offset)) {
2450           return 0;
2451         }
2452         break;
2453       case FOURCC_mp4v:
2454         if (!sample_entry_mp4v_copy_data ((SampleTableEntryMP4V *) walker->data,
2455                 buffer, size, offset)) {
2456           return 0;
2457         }
2458         break;
2459       default:
2460         if (se->kind == VIDEO) {
2461           if (!sample_entry_mp4v_copy_data ((SampleTableEntryMP4V *)
2462                   walker->data, buffer, size, offset)) {
2463             return 0;
2464           }
2465         } else if (se->kind == AUDIO) {
2466           if (!sample_entry_mp4a_copy_data ((SampleTableEntryMP4A *)
2467                   walker->data, buffer, size, offset)) {
2468             return 0;
2469           }
2470         } else if (se->kind == SUBTITLE) {
2471           if (!sample_entry_tx3g_copy_data ((SampleTableEntryTX3G *)
2472                   walker->data, buffer, size, offset)) {
2473             return 0;
2474           }
2475         } else if (se->kind == TIMECODE) {
2476           if (!sample_entry_tmcd_copy_data ((SampleTableEntryTMCD *)
2477                   walker->data, buffer, size, offset)) {
2478             return 0;
2479           }
2480         } else if (se->kind == CLOSEDCAPTION) {
2481           if (!sample_entry_generic_copy_data ((SampleTableEntry *)
2482                   walker->data, buffer, size, offset)) {
2483             return 0;
2484           }
2485         } else {
2486           if (!atom_hint_sample_entry_copy_data (
2487                   (AtomHintSampleEntry *) walker->data, buffer, size, offset)) {
2488             return 0;
2489           }
2490         }
2491         break;
2492     }
2493   }
2494
2495   atom_write_size (buffer, size, offset, original_offset);
2496   return *offset - original_offset;
2497 }
2498
2499 static guint64
2500 atom_stbl_copy_data (AtomSTBL * stbl, guint8 ** buffer, guint64 * size,
2501     guint64 * offset)
2502 {
2503   guint64 original_offset = *offset;
2504
2505   if (!atom_copy_data (&stbl->header, buffer, size, offset)) {
2506     return 0;
2507   }
2508
2509   if (!atom_stsd_copy_data (&stbl->stsd, buffer, size, offset)) {
2510     return 0;
2511   }
2512   if (!atom_stts_copy_data (&stbl->stts, buffer, size, offset)) {
2513     return 0;
2514   }
2515   /* this atom is optional, so let's check if we need it
2516    * (to avoid false error) */
2517   if (atom_array_get_len (&stbl->stss.entries)) {
2518     if (!atom_stss_copy_data (&stbl->stss, buffer, size, offset)) {
2519       return 0;
2520     }
2521   }
2522
2523   if (!atom_stsc_copy_data (&stbl->stsc, buffer, size, offset)) {
2524     return 0;
2525   }
2526   if (!atom_stsz_copy_data (&stbl->stsz, buffer, size, offset)) {
2527     return 0;
2528   }
2529   if (stbl->ctts && stbl->ctts->do_pts) {
2530     if (!atom_ctts_copy_data (stbl->ctts, buffer, size, offset)) {
2531       return 0;
2532     }
2533   }
2534   if (stbl->svmi) {
2535     if (!atom_svmi_copy_data (stbl->svmi, buffer, size, offset)) {
2536       return 0;
2537     }
2538   }
2539   if (!atom_stco64_copy_data (&stbl->stco64, buffer, size, offset)) {
2540     return 0;
2541   }
2542
2543   atom_write_size (buffer, size, offset, original_offset);
2544   return original_offset - *offset;
2545 }
2546
2547
2548 static guint64
2549 atom_dref_copy_data (AtomDREF * dref, guint8 ** buffer, guint64 * size,
2550     guint64 * offset)
2551 {
2552   guint64 original_offset = *offset;
2553   GList *walker;
2554
2555   if (!atom_full_copy_data (&dref->header, buffer, size, offset)) {
2556     return 0;
2557   }
2558
2559   prop_copy_uint32 (g_list_length (dref->entries), buffer, size, offset);
2560
2561   walker = dref->entries;
2562   while (walker != NULL) {
2563     Atom *atom = (Atom *) walker->data;
2564
2565     if (atom->type == FOURCC_url_) {
2566       if (!atom_url_copy_data ((AtomURL *) atom, buffer, size, offset))
2567         return 0;
2568     } else if (atom->type == FOURCC_alis) {
2569       if (!atom_full_copy_data ((AtomFull *) atom, buffer, size, offset))
2570         return 0;
2571     } else {
2572       g_error ("Unsupported atom used inside dref atom");
2573     }
2574     walker = g_list_next (walker);
2575   }
2576
2577   atom_write_size (buffer, size, offset, original_offset);
2578   return *offset - original_offset;
2579 }
2580
2581 static guint64
2582 atom_dinf_copy_data (AtomDINF * dinf, guint8 ** buffer, guint64 * size,
2583     guint64 * offset)
2584 {
2585   guint64 original_offset = *offset;
2586
2587   if (!atom_copy_data (&dinf->header, buffer, size, offset)) {
2588     return 0;
2589   }
2590
2591   if (!atom_dref_copy_data (&dinf->dref, buffer, size, offset)) {
2592     return 0;
2593   }
2594
2595   atom_write_size (buffer, size, offset, original_offset);
2596   return original_offset - *offset;
2597 }
2598
2599 static guint64
2600 atom_minf_copy_data (AtomMINF * minf, guint8 ** buffer, guint64 * size,
2601     guint64 * offset)
2602 {
2603   guint64 original_offset = *offset;
2604
2605   if (!atom_copy_data (&minf->header, buffer, size, offset)) {
2606     return 0;
2607   }
2608
2609   if (minf->vmhd) {
2610     if (!atom_vmhd_copy_data (minf->vmhd, buffer, size, offset)) {
2611       return 0;
2612     }
2613   } else if (minf->smhd) {
2614     if (!atom_smhd_copy_data (minf->smhd, buffer, size, offset)) {
2615       return 0;
2616     }
2617   } else if (minf->hmhd) {
2618     if (!atom_hmhd_copy_data (minf->hmhd, buffer, size, offset)) {
2619       return 0;
2620     }
2621   } else if (minf->gmhd) {
2622     if (!atom_gmhd_copy_data (minf->gmhd, buffer, size, offset)) {
2623       return 0;
2624     }
2625   }
2626
2627   if (minf->hdlr) {
2628     if (!atom_hdlr_copy_data (minf->hdlr, buffer, size, offset)) {
2629       return 0;
2630     }
2631   }
2632
2633   if (!atom_dinf_copy_data (&minf->dinf, buffer, size, offset)) {
2634     return 0;
2635   }
2636   if (!atom_stbl_copy_data (&minf->stbl, buffer, size, offset)) {
2637     return 0;
2638   }
2639
2640   atom_write_size (buffer, size, offset, original_offset);
2641   return *offset - original_offset;
2642 }
2643
2644 static guint64
2645 atom_mdhd_copy_data (AtomMDHD * mdhd, guint8 ** buffer, guint64 * size,
2646     guint64 * offset)
2647 {
2648   guint64 original_offset = *offset;
2649
2650   if (!atom_full_copy_data (&mdhd->header, buffer, size, offset)) {
2651     return 0;
2652   }
2653
2654   if (!common_time_info_copy_data (&mdhd->time_info,
2655           atom_full_get_version (&mdhd->header) == 0, buffer, size, offset)) {
2656     return 0;
2657   }
2658
2659   prop_copy_uint16 (mdhd->language_code, buffer, size, offset);
2660   prop_copy_uint16 (mdhd->quality, buffer, size, offset);
2661
2662   atom_write_size (buffer, size, offset, original_offset);
2663   return *offset - original_offset;
2664 }
2665
2666 static guint64
2667 atom_mdia_copy_data (AtomMDIA * mdia, guint8 ** buffer, guint64 * size,
2668     guint64 * offset)
2669 {
2670   guint64 original_offset = *offset;
2671
2672   if (!atom_copy_data (&mdia->header, buffer, size, offset)) {
2673     return 0;
2674   }
2675   if (!atom_mdhd_copy_data (&mdia->mdhd, buffer, size, offset)) {
2676     return 0;
2677   }
2678   if (!atom_hdlr_copy_data (&mdia->hdlr, buffer, size, offset)) {
2679     return 0;
2680   }
2681
2682   if (!atom_minf_copy_data (&mdia->minf, buffer, size, offset)) {
2683     return 0;
2684   }
2685
2686   atom_write_size (buffer, size, offset, original_offset);
2687   return *offset - original_offset;
2688 }
2689
2690 static guint64
2691 atom_elst_copy_data (AtomELST * elst, guint8 ** buffer, guint64 * size,
2692     guint64 * offset)
2693 {
2694   guint64 original_offset = *offset;
2695   GSList *walker;
2696
2697   if (!atom_full_copy_data (&elst->header, buffer, size, offset)) {
2698     return 0;
2699   }
2700
2701   prop_copy_uint32 (g_slist_length (elst->entries), buffer, size, offset);
2702
2703   for (walker = elst->entries; walker != NULL; walker = g_slist_next (walker)) {
2704     EditListEntry *entry = (EditListEntry *) walker->data;
2705     prop_copy_uint32 (entry->duration, buffer, size, offset);
2706     prop_copy_uint32 (entry->media_time, buffer, size, offset);
2707     prop_copy_uint32 (entry->media_rate, buffer, size, offset);
2708   }
2709   atom_write_size (buffer, size, offset, original_offset);
2710   return *offset - original_offset;
2711 }
2712
2713 static guint64
2714 atom_tref_copy_data (AtomTREF * tref, guint8 ** buffer, guint64 * size,
2715     guint64 * offset)
2716 {
2717   guint64 original_offset = *offset;
2718   guint i;
2719
2720   g_assert (atom_array_get_len (&tref->entries) > 0);
2721
2722   if (!atom_copy_data (&tref->header, buffer, size, offset)) {
2723     return 0;
2724   }
2725
2726   prop_copy_uint32 (8 + 4 * atom_array_get_len (&tref->entries), buffer, size,
2727       offset);
2728   prop_copy_fourcc (tref->reftype, buffer, size, offset);
2729   /* minimize realloc */
2730   prop_copy_ensure_buffer (buffer, size, offset,
2731       4 * atom_array_get_len (&tref->entries));
2732   for (i = 0; i < atom_array_get_len (&tref->entries); i++) {
2733     prop_copy_uint32 (atom_array_index (&tref->entries, i), buffer, size,
2734         offset);
2735   }
2736
2737   atom_write_size (buffer, size, offset, original_offset);
2738   return *offset - original_offset;
2739 }
2740
2741 static guint64
2742 atom_edts_copy_data (AtomEDTS * edts, guint8 ** buffer, guint64 * size,
2743     guint64 * offset)
2744 {
2745   guint64 original_offset = *offset;
2746
2747   if (!atom_copy_data (&(edts->header), buffer, size, offset))
2748     return 0;
2749
2750   if (!atom_elst_copy_data (&(edts->elst), buffer, size, offset))
2751     return 0;
2752
2753   atom_write_size (buffer, size, offset, original_offset);
2754   return *offset - original_offset;
2755 }
2756
2757 static guint64
2758 atom_tag_data_copy_data (AtomTagData * data, guint8 ** buffer, guint64 * size,
2759     guint64 * offset)
2760 {
2761   guint64 original_offset = *offset;
2762
2763   if (!atom_full_copy_data (&data->header, buffer, size, offset)) {
2764     return 0;
2765   }
2766
2767   prop_copy_uint32 (data->reserved, buffer, size, offset);
2768   prop_copy_uint8_array (data->data, data->datalen, buffer, size, offset);
2769
2770   atom_write_size (buffer, size, offset, original_offset);
2771   return *offset - original_offset;
2772 }
2773
2774 static guint64
2775 atom_tag_copy_data (AtomTag * tag, guint8 ** buffer, guint64 * size,
2776     guint64 * offset)
2777 {
2778   guint64 original_offset = *offset;
2779
2780   if (!atom_copy_data (&tag->header, buffer, size, offset)) {
2781     return 0;
2782   }
2783
2784   if (!atom_tag_data_copy_data (&tag->data, buffer, size, offset)) {
2785     return 0;
2786   }
2787
2788   atom_write_size (buffer, size, offset, original_offset);
2789   return *offset - original_offset;
2790 }
2791
2792 static guint64
2793 atom_ilst_copy_data (AtomILST * ilst, guint8 ** buffer, guint64 * size,
2794     guint64 * offset)
2795 {
2796   guint64 original_offset = *offset;
2797
2798   if (!atom_copy_data (&ilst->header, buffer, size, offset)) {
2799     return 0;
2800   }
2801   /* extra atoms */
2802   if (ilst->entries &&
2803       !atom_info_list_copy_data (ilst->entries, buffer, size, offset))
2804     return 0;
2805
2806   atom_write_size (buffer, size, offset, original_offset);
2807   return *offset - original_offset;
2808 }
2809
2810 static guint64
2811 atom_meta_copy_data (AtomMETA * meta, guint8 ** buffer, guint64 * size,
2812     guint64 * offset)
2813 {
2814   guint64 original_offset = *offset;
2815
2816   if (!atom_full_copy_data (&meta->header, buffer, size, offset)) {
2817     return 0;
2818   }
2819   if (!atom_hdlr_copy_data (&meta->hdlr, buffer, size, offset)) {
2820     return 0;
2821   }
2822   if (meta->ilst) {
2823     if (!atom_ilst_copy_data (meta->ilst, buffer, size, offset)) {
2824       return 0;
2825     }
2826   }
2827
2828   atom_write_size (buffer, size, offset, original_offset);
2829   return *offset - original_offset;
2830 }
2831
2832 static guint64
2833 atom_udta_copy_data (AtomUDTA * udta, guint8 ** buffer, guint64 * size,
2834     guint64 * offset)
2835 {
2836   guint64 original_offset = *offset;
2837
2838   if (!atom_copy_data (&udta->header, buffer, size, offset)) {
2839     return 0;
2840   }
2841   if (udta->meta) {
2842     if (!atom_meta_copy_data (udta->meta, buffer, size, offset)) {
2843       return 0;
2844     }
2845   }
2846   if (udta->entries) {
2847     /* extra atoms */
2848     if (!atom_info_list_copy_data (udta->entries, buffer, size, offset))
2849       return 0;
2850   }
2851
2852   atom_write_size (buffer, size, offset, original_offset);
2853   return *offset - original_offset;
2854 }
2855
2856 static guint64
2857 atom_mehd_copy_data (AtomMEHD * mehd, guint8 ** buffer, guint64 * size,
2858     guint64 * offset)
2859 {
2860   guint64 original_offset = *offset;
2861
2862   if (!atom_full_copy_data (&mehd->header, buffer, size, offset)) {
2863     return 0;
2864   }
2865
2866   prop_copy_uint64 (mehd->fragment_duration, buffer, size, offset);
2867
2868   atom_write_size (buffer, size, offset, original_offset);
2869   return *offset - original_offset;
2870 }
2871
2872 static guint64
2873 atom_trex_copy_data (AtomTREX * trex, guint8 ** buffer, guint64 * size,
2874     guint64 * offset)
2875 {
2876   guint64 original_offset = *offset;
2877
2878   if (!atom_full_copy_data (&trex->header, buffer, size, offset)) {
2879     return 0;
2880   }
2881
2882   prop_copy_uint32 (trex->track_ID, buffer, size, offset);
2883   prop_copy_uint32 (trex->default_sample_description_index, buffer, size,
2884       offset);
2885   prop_copy_uint32 (trex->default_sample_duration, buffer, size, offset);
2886   prop_copy_uint32 (trex->default_sample_size, buffer, size, offset);
2887   prop_copy_uint32 (trex->default_sample_flags, buffer, size, offset);
2888
2889   atom_write_size (buffer, size, offset, original_offset);
2890   return *offset - original_offset;
2891 }
2892
2893 static guint64
2894 atom_mvex_copy_data (AtomMVEX * mvex, guint8 ** buffer, guint64 * size,
2895     guint64 * offset)
2896 {
2897   guint64 original_offset = *offset;
2898   GList *walker;
2899
2900   if (!atom_copy_data (&mvex->header, buffer, size, offset)) {
2901     return 0;
2902   }
2903
2904   if (!atom_mehd_copy_data (&mvex->mehd, buffer, size, offset)) {
2905     return 0;
2906   }
2907
2908   walker = g_list_first (mvex->trexs);
2909   while (walker != NULL) {
2910     if (!atom_trex_copy_data ((AtomTREX *) walker->data, buffer, size, offset)) {
2911       return 0;
2912     }
2913     walker = g_list_next (walker);
2914   }
2915
2916   atom_write_size (buffer, size, offset, original_offset);
2917   return *offset - original_offset;
2918 }
2919
2920 guint64
2921 atom_trak_copy_data (AtomTRAK * trak, guint8 ** buffer, guint64 * size,
2922     guint64 * offset)
2923 {
2924   guint64 original_offset = *offset;
2925
2926   if (!atom_copy_data (&trak->header, buffer, size, offset)) {
2927     return 0;
2928   }
2929   if (!atom_tkhd_copy_data (&trak->tkhd, buffer, size, offset)) {
2930     return 0;
2931   }
2932   if (trak->tapt) {
2933     if (!trak->tapt->copy_data_func (trak->tapt->atom, buffer, size, offset)) {
2934       return 0;
2935     }
2936   }
2937   if (trak->edts) {
2938     if (!atom_edts_copy_data (trak->edts, buffer, size, offset)) {
2939       return 0;
2940     }
2941   }
2942   if (trak->tref) {
2943     /* Make sure we need this atom (there is a referenced track */
2944     if (atom_array_get_len (&trak->tref->entries) > 0) {
2945       if (!atom_tref_copy_data (trak->tref, buffer, size, offset)) {
2946         return 0;
2947       }
2948     }
2949   }
2950
2951   if (!atom_mdia_copy_data (&trak->mdia, buffer, size, offset)) {
2952     return 0;
2953   }
2954
2955   if (!atom_udta_copy_data (&trak->udta, buffer, size, offset)) {
2956     return 0;
2957   }
2958
2959   atom_write_size (buffer, size, offset, original_offset);
2960   return *offset - original_offset;
2961 }
2962
2963
2964 guint64
2965 atom_moov_copy_data (AtomMOOV * atom, guint8 ** buffer, guint64 * size,
2966     guint64 * offset)
2967 {
2968   guint64 original_offset = *offset;
2969   GList *walker;
2970
2971   if (!atom_copy_data (&(atom->header), buffer, size, offset))
2972     return 0;
2973
2974   if (!atom_mvhd_copy_data (&(atom->mvhd), buffer, size, offset))
2975     return 0;
2976
2977   walker = g_list_first (atom->traks);
2978   while (walker != NULL) {
2979     if (!atom_trak_copy_data ((AtomTRAK *) walker->data, buffer, size, offset)) {
2980       return 0;
2981     }
2982     walker = g_list_next (walker);
2983   }
2984
2985   if (!atom_udta_copy_data (&atom->udta, buffer, size, offset)) {
2986     return 0;
2987   }
2988
2989   if (atom->fragmented) {
2990     if (!atom_mvex_copy_data (&atom->mvex, buffer, size, offset)) {
2991       return 0;
2992     }
2993   }
2994
2995   atom_write_size (buffer, size, offset, original_offset);
2996   return *offset - original_offset;
2997 }
2998
2999 static guint64
3000 atom_wave_copy_data (AtomWAVE * wave, guint8 ** buffer,
3001     guint64 * size, guint64 * offset)
3002 {
3003   guint64 original_offset = *offset;
3004
3005   if (!atom_copy_data (&(wave->header), buffer, size, offset))
3006     return 0;
3007
3008   if (wave->extension_atoms) {
3009     if (!atom_info_list_copy_data (wave->extension_atoms, buffer, size, offset))
3010       return 0;
3011   }
3012
3013   atom_write_size (buffer, size, offset, original_offset);
3014   return *offset - original_offset;
3015 }
3016
3017 /* -- end of copy data functions -- */
3018
3019 /* -- general functions, API and support functions */
3020
3021 /* add samples to tables */
3022
3023 void
3024 atom_stsc_add_new_entry (AtomSTSC * stsc, guint32 first_chunk, guint32 nsamples)
3025 {
3026   gint len;
3027
3028   if ((len = atom_array_get_len (&stsc->entries)) > 1 &&
3029       ((atom_array_index (&stsc->entries, len - 1)).samples_per_chunk ==
3030           (atom_array_index (&stsc->entries, len - 2)).samples_per_chunk)) {
3031     STSCEntry *nentry;
3032
3033     /* Merge last two entries as they have the same number of samples per chunk */
3034     nentry = &atom_array_index (&stsc->entries, len - 1);
3035     nentry->first_chunk = first_chunk;
3036     nentry->samples_per_chunk = nsamples;
3037     nentry->sample_description_index = 1;
3038   } else {
3039     STSCEntry nentry;
3040
3041     nentry.first_chunk = first_chunk;
3042     nentry.samples_per_chunk = nsamples;
3043     nentry.sample_description_index = 1;
3044     atom_array_append (&stsc->entries, nentry, 128);
3045   }
3046 }
3047
3048 static void
3049 atom_stsc_update_entry (AtomSTSC * stsc, guint32 first_chunk, guint32 nsamples)
3050 {
3051   gint len;
3052
3053   len = atom_array_get_len (&stsc->entries);
3054   g_assert (len != 0);
3055   g_assert (atom_array_index (&stsc->entries,
3056           len - 1).first_chunk == first_chunk);
3057
3058   atom_array_index (&stsc->entries, len - 1).samples_per_chunk += nsamples;
3059 }
3060
3061 static void
3062 atom_stts_add_entry (AtomSTTS * stts, guint32 sample_count, gint32 sample_delta)
3063 {
3064   STTSEntry *entry = NULL;
3065
3066   if (G_LIKELY (atom_array_get_len (&stts->entries) != 0))
3067     entry = &atom_array_index (&stts->entries,
3068         atom_array_get_len (&stts->entries) - 1);
3069
3070   if (entry && entry->sample_delta == sample_delta) {
3071     entry->sample_count += sample_count;
3072   } else {
3073     STTSEntry nentry;
3074
3075     nentry.sample_count = sample_count;
3076     nentry.sample_delta = sample_delta;
3077     atom_array_append (&stts->entries, nentry, 256);
3078   }
3079 }
3080
3081 static void
3082 atom_stsz_add_entry (AtomSTSZ * stsz, guint32 nsamples, guint32 size)
3083 {
3084   guint32 i;
3085
3086   stsz->table_size += nsamples;
3087   if (stsz->sample_size != 0) {
3088     /* it is constant size, we don't need entries */
3089     return;
3090   }
3091   for (i = 0; i < nsamples; i++) {
3092     atom_array_append (&stsz->entries, size, 1024);
3093   }
3094 }
3095
3096 static guint32
3097 atom_stco64_get_entry_count (AtomSTCO64 * stco64)
3098 {
3099   return atom_array_get_len (&stco64->entries);
3100 }
3101
3102 /* returns TRUE if a new entry was added */
3103 static gboolean
3104 atom_stco64_add_entry (AtomSTCO64 * stco64, guint64 entry)
3105 {
3106   guint32 len;
3107
3108   /* Only add a new entry if the chunk offset changed */
3109   if ((len = atom_array_get_len (&stco64->entries)) &&
3110       ((atom_array_index (&stco64->entries, len - 1)) == entry))
3111     return FALSE;
3112
3113   atom_array_append (&stco64->entries, entry, 256);
3114   if (entry > G_MAXUINT32)
3115     stco64->header.header.type = FOURCC_co64;
3116
3117   return TRUE;
3118 }
3119
3120 void
3121 atom_tref_add_entry (AtomTREF * tref, guint32 sample)
3122 {
3123   atom_array_append (&tref->entries, sample, 512);
3124 }
3125
3126 static void
3127 atom_stss_add_entry (AtomSTSS * stss, guint32 sample)
3128 {
3129   atom_array_append (&stss->entries, sample, 512);
3130 }
3131
3132 static void
3133 atom_stbl_add_stss_entry (AtomSTBL * stbl)
3134 {
3135   guint32 sample_index = stbl->stsz.table_size;
3136
3137   atom_stss_add_entry (&stbl->stss, sample_index);
3138 }
3139
3140 static void
3141 atom_ctts_add_entry (AtomCTTS * ctts, guint32 nsamples, guint32 offset)
3142 {
3143   CTTSEntry *entry = NULL;
3144
3145   if (G_LIKELY (atom_array_get_len (&ctts->entries) != 0))
3146     entry = &atom_array_index (&ctts->entries,
3147         atom_array_get_len (&ctts->entries) - 1);
3148
3149   if (entry == NULL || entry->sampleoffset != offset) {
3150     CTTSEntry nentry;
3151
3152     nentry.samplecount = nsamples;
3153     nentry.sampleoffset = offset;
3154     atom_array_append (&ctts->entries, nentry, 256);
3155     if (offset != 0)
3156       ctts->do_pts = TRUE;
3157   } else {
3158     entry->samplecount += nsamples;
3159   }
3160 }
3161
3162 static void
3163 atom_stbl_add_ctts_entry (AtomSTBL * stbl, guint32 nsamples, guint32 offset)
3164 {
3165   if (stbl->ctts == NULL) {
3166     stbl->ctts = atom_ctts_new ();
3167   }
3168   atom_ctts_add_entry (stbl->ctts, nsamples, offset);
3169 }
3170
3171 void
3172 atom_stbl_add_samples (AtomSTBL * stbl, guint32 nsamples, guint32 delta,
3173     guint32 size, guint64 chunk_offset, gboolean sync, gint64 pts_offset)
3174 {
3175   atom_stts_add_entry (&stbl->stts, nsamples, delta);
3176   atom_stsz_add_entry (&stbl->stsz, nsamples, size);
3177   if (atom_stco64_add_entry (&stbl->stco64, chunk_offset)) {
3178     atom_stsc_add_new_entry (&stbl->stsc,
3179         atom_stco64_get_entry_count (&stbl->stco64), nsamples);
3180   } else {
3181     atom_stsc_update_entry (&stbl->stsc,
3182         atom_stco64_get_entry_count (&stbl->stco64), nsamples);
3183   }
3184
3185   if (sync)
3186     atom_stbl_add_stss_entry (stbl);
3187   /* always store to arrange for consistent content */
3188   atom_stbl_add_ctts_entry (stbl, nsamples, pts_offset);
3189 }
3190
3191 void
3192 atom_trak_add_samples (AtomTRAK * trak, guint32 nsamples, guint32 delta,
3193     guint32 size, guint64 chunk_offset, gboolean sync, gint64 pts_offset)
3194 {
3195   AtomSTBL *stbl = &trak->mdia.minf.stbl;
3196   atom_stbl_add_samples (stbl, nsamples, delta, size, chunk_offset, sync,
3197       pts_offset);
3198 }
3199
3200 /* trak and moov molding */
3201
3202 guint32
3203 atom_trak_get_timescale (AtomTRAK * trak)
3204 {
3205   return trak->mdia.mdhd.time_info.timescale;
3206 }
3207
3208 guint32
3209 atom_trak_get_id (AtomTRAK * trak)
3210 {
3211   return trak->tkhd.track_ID;
3212 }
3213
3214 static void
3215 atom_trak_set_id (AtomTRAK * trak, guint32 id)
3216 {
3217   trak->tkhd.track_ID = id;
3218 }
3219
3220 static void
3221 atom_moov_add_trex (AtomMOOV * moov, AtomTREX * trex)
3222 {
3223   moov->mvex.trexs = g_list_append (moov->mvex.trexs, trex);
3224 }
3225
3226 static AtomTREX *
3227 atom_trex_new (AtomTRAK * trak)
3228 {
3229   guint8 flags[3] = { 0, 0, 0 };
3230   AtomTREX *trex = g_new0 (AtomTREX, 1);
3231
3232   atom_full_init (&trex->header, FOURCC_trex, 0, 0, 0, flags);
3233
3234   trex->track_ID = trak->tkhd.track_ID;
3235   trex->default_sample_description_index = 1;
3236   trex->default_sample_duration = 0;
3237   trex->default_sample_size = 0;
3238   trex->default_sample_flags = 0;
3239
3240   return trex;
3241 }
3242
3243 void
3244 atom_moov_add_trak (AtomMOOV * moov, AtomTRAK * trak)
3245 {
3246   atom_trak_set_id (trak, moov->mvhd.next_track_id++);
3247   moov->traks = g_list_append (moov->traks, trak);
3248   /* additional trak means also new trex */
3249   atom_moov_add_trex (moov, atom_trex_new (trak));
3250 }
3251
3252 guint
3253 atom_moov_get_trak_count (AtomMOOV * moov)
3254 {
3255   return g_list_length (moov->traks);
3256 }
3257
3258 static guint64
3259 atom_trak_get_duration (AtomTRAK * trak)
3260 {
3261   return trak->tkhd.duration;
3262 }
3263
3264 static guint64
3265 atom_stts_get_total_duration (AtomSTTS * stts)
3266 {
3267   guint i;
3268   guint64 sum = 0;
3269
3270   for (i = 0; i < atom_array_get_len (&stts->entries); i++) {
3271     STTSEntry *entry = &atom_array_index (&stts->entries, i);
3272
3273     sum += (guint64) (entry->sample_count) * entry->sample_delta;
3274   }
3275   return sum;
3276 }
3277
3278 static void
3279 atom_trak_update_duration (AtomTRAK * trak, guint64 moov_timescale)
3280 {
3281   trak->mdia.mdhd.time_info.duration =
3282       atom_stts_get_total_duration (&trak->mdia.minf.stbl.stts);
3283   if (trak->mdia.mdhd.time_info.timescale != 0) {
3284     trak->tkhd.duration =
3285         gst_util_uint64_scale (trak->mdia.mdhd.time_info.duration,
3286         moov_timescale, trak->mdia.mdhd.time_info.timescale);
3287   } else {
3288     trak->tkhd.duration = 0;
3289   }
3290 }
3291
3292 static void
3293 timecode_atom_trak_set_duration (AtomTRAK * trak, guint64 duration,
3294     guint64 timescale)
3295 {
3296   STTSEntry *entry;
3297   GList *iter;
3298
3299   /* Sanity checks to ensure we have a timecode */
3300   g_assert (trak->mdia.minf.gmhd != NULL);
3301   g_assert (atom_array_get_len (&trak->mdia.minf.stbl.stts.entries) == 1);
3302
3303   for (iter = trak->mdia.minf.stbl.stsd.entries; iter;
3304       iter = g_list_next (iter)) {
3305     SampleTableEntry *entry = iter->data;
3306     if (entry->kind == TIMECODE) {
3307       SampleTableEntryTMCD *tmcd = (SampleTableEntryTMCD *) entry;
3308
3309       duration = duration * tmcd->timescale / timescale;
3310       timescale = tmcd->timescale;
3311       break;
3312     }
3313   }
3314
3315   trak->tkhd.duration = duration;
3316   trak->mdia.mdhd.time_info.duration = duration;
3317   trak->mdia.mdhd.time_info.timescale = timescale;
3318
3319   entry = &atom_array_index (&trak->mdia.minf.stbl.stts.entries, 0);
3320   entry->sample_delta = duration;
3321 }
3322
3323 static guint32
3324 atom_moov_get_timescale (AtomMOOV * moov)
3325 {
3326   return moov->mvhd.time_info.timescale;
3327 }
3328
3329 void
3330 atom_moov_update_timescale (AtomMOOV * moov, guint32 timescale)
3331 {
3332   moov->mvhd.time_info.timescale = timescale;
3333 }
3334
3335 void
3336 atom_moov_update_duration (AtomMOOV * moov)
3337 {
3338   GList *traks = moov->traks;
3339   guint64 dur, duration = 0;
3340
3341   while (traks) {
3342     AtomTRAK *trak = (AtomTRAK *) traks->data;
3343
3344     /* Skip timecodes for now: they have a placeholder duration */
3345     if (trak->mdia.minf.gmhd == NULL || trak->mdia.minf.gmhd->tmcd == NULL) {
3346       atom_trak_update_duration (trak, atom_moov_get_timescale (moov));
3347       dur = atom_trak_get_duration (trak);
3348       if (dur > duration)
3349         duration = dur;
3350     }
3351     traks = g_list_next (traks);
3352   }
3353   /* Now update the duration of the timecodes */
3354   traks = moov->traks;
3355   while (traks) {
3356     AtomTRAK *trak = (AtomTRAK *) traks->data;
3357
3358     if (trak->mdia.minf.gmhd != NULL && trak->mdia.minf.gmhd->tmcd != NULL)
3359       timecode_atom_trak_set_duration (trak, duration,
3360           atom_moov_get_timescale (moov));
3361     traks = g_list_next (traks);
3362   }
3363   moov->mvhd.time_info.duration = duration;
3364   moov->mvex.mehd.fragment_duration = duration;
3365 }
3366
3367 void
3368 atom_moov_set_fragmented (AtomMOOV * moov, gboolean fragmented)
3369 {
3370   moov->fragmented = fragmented;
3371 }
3372
3373 void
3374 atom_stco64_chunks_set_offset (AtomSTCO64 * stco64, guint32 offset)
3375 {
3376   stco64->chunk_offset = offset;
3377 }
3378
3379 void
3380 atom_moov_chunks_set_offset (AtomMOOV * moov, guint32 offset)
3381 {
3382   GList *traks = moov->traks;
3383
3384   if (offset == moov->chunks_offset)
3385     return;                     /* Nothing to do */
3386
3387   while (traks) {
3388     AtomTRAK *trak = (AtomTRAK *) traks->data;
3389
3390     atom_stco64_chunks_set_offset (&trak->mdia.minf.stbl.stco64, offset);
3391     traks = g_list_next (traks);
3392   }
3393
3394   moov->chunks_offset = offset;
3395 }
3396
3397 void
3398 atom_trak_update_bitrates (AtomTRAK * trak, guint32 avg_bitrate,
3399     guint32 max_bitrate)
3400 {
3401   AtomESDS *esds = NULL;
3402   AtomData *btrt = NULL;
3403   AtomWAVE *wave = NULL;
3404   AtomSTSD *stsd;
3405   GList *iter;
3406   GList *extensioniter = NULL;
3407
3408   g_return_if_fail (trak != NULL);
3409
3410   if (avg_bitrate == 0 && max_bitrate == 0)
3411     return;
3412
3413   stsd = &trak->mdia.minf.stbl.stsd;
3414   for (iter = stsd->entries; iter; iter = g_list_next (iter)) {
3415     SampleTableEntry *entry = iter->data;
3416
3417     switch (entry->kind) {
3418       case AUDIO:{
3419         SampleTableEntryMP4A *audioentry = (SampleTableEntryMP4A *) entry;
3420         extensioniter = audioentry->extension_atoms;
3421         break;
3422       }
3423       case VIDEO:{
3424         SampleTableEntryMP4V *videoentry = (SampleTableEntryMP4V *) entry;
3425         extensioniter = videoentry->extension_atoms;
3426         break;
3427       }
3428       default:
3429         break;
3430     }
3431   }
3432
3433   for (; extensioniter; extensioniter = g_list_next (extensioniter)) {
3434     AtomInfo *atominfo = extensioniter->data;
3435     if (atominfo->atom->type == FOURCC_esds) {
3436       esds = (AtomESDS *) atominfo->atom;
3437     } else if (atominfo->atom->type == FOURCC_btrt) {
3438       btrt = (AtomData *) atominfo->atom;
3439     } else if (atominfo->atom->type == FOURCC_wave) {
3440       wave = (AtomWAVE *) atominfo->atom;
3441     }
3442   }
3443
3444   /* wave might have an esds internally */
3445   if (wave) {
3446     for (extensioniter = wave->extension_atoms; extensioniter;
3447         extensioniter = g_list_next (extensioniter)) {
3448       AtomInfo *atominfo = extensioniter->data;
3449       if (atominfo->atom->type == FOURCC_esds) {
3450         esds = (AtomESDS *) atominfo->atom;
3451         break;
3452       }
3453     }
3454   }
3455
3456   if (esds) {
3457     if (avg_bitrate && esds->es.dec_conf_desc.avg_bitrate == 0)
3458       esds->es.dec_conf_desc.avg_bitrate = avg_bitrate;
3459     if (max_bitrate && esds->es.dec_conf_desc.max_bitrate == 0)
3460       esds->es.dec_conf_desc.max_bitrate = max_bitrate;
3461   }
3462   if (btrt) {
3463     /* type(4bytes) + size(4bytes) + buffersize(4bytes) +
3464      * maxbitrate(bytes) + avgbitrate(bytes) */
3465     if (max_bitrate && GST_READ_UINT32_BE (btrt->data + 4) == 0)
3466       GST_WRITE_UINT32_BE (btrt->data + 4, max_bitrate);
3467     if (avg_bitrate && GST_READ_UINT32_BE (btrt->data + 8) == 0)
3468       GST_WRITE_UINT32_BE (btrt->data + 8, avg_bitrate);
3469   }
3470 }
3471
3472 void
3473 atom_trak_tx3g_update_dimension (AtomTRAK * trak, guint32 width, guint32 height)
3474 {
3475   AtomSTSD *stsd;
3476   GList *iter;
3477   SampleTableEntryTX3G *tx3g = NULL;
3478
3479   stsd = &trak->mdia.minf.stbl.stsd;
3480   for (iter = stsd->entries; iter && tx3g == NULL; iter = g_list_next (iter)) {
3481     SampleTableEntry *entry = iter->data;
3482
3483     switch (entry->kind) {
3484       case SUBTITLE:{
3485         tx3g = (SampleTableEntryTX3G *) entry;
3486         break;
3487       }
3488       default:
3489         break;
3490     }
3491   }
3492
3493   /* Currently we never set the vertical placement flag, so we don't
3494    * check for it to set the dimensions differently as the spec says.
3495    * Always do it for the not set case */
3496   if (tx3g) {
3497     tx3g->font_size = 0.05 * height;
3498
3499     height = 0.15 * height;
3500     trak->tkhd.width = width << 16;
3501     trak->tkhd.height = height << 16;
3502     tx3g->default_text_box = width | (height << 16);
3503   }
3504 }
3505
3506 /*
3507  * Meta tags functions
3508  */
3509 static void
3510 atom_tag_data_alloc_data (AtomTagData * data, guint size)
3511 {
3512   g_free (data->data);
3513   data->data = g_new0 (guint8, size);
3514   data->datalen = size;
3515 }
3516
3517 static void
3518 atom_udta_append_tag (AtomUDTA * udta, AtomInfo * tag)
3519 {
3520   GList **entries;
3521
3522   if (udta->meta)
3523     entries = &udta->meta->ilst->entries;
3524   else
3525     entries = &udta->entries;
3526   *entries = g_list_append (*entries, tag);
3527 }
3528
3529 void
3530 atom_udta_add_tag (AtomUDTA * udta, guint32 fourcc, guint32 flags,
3531     const guint8 * data, guint size)
3532 {
3533   AtomTag *tag;
3534   AtomTagData *tdata;
3535
3536   tag = atom_tag_new (fourcc, flags);
3537   tdata = &tag->data;
3538   atom_tag_data_alloc_data (tdata, size);
3539   memmove (tdata->data, data, size);
3540
3541   atom_udta_append_tag (udta,
3542       build_atom_info_wrapper ((Atom *) tag, atom_tag_copy_data,
3543           atom_tag_free));
3544 }
3545
3546 void
3547 atom_udta_add_str_tag (AtomUDTA * udta, guint32 fourcc, const gchar * value)
3548 {
3549   gint len = strlen (value);
3550
3551   if (len > 0)
3552     atom_udta_add_tag (udta, fourcc, METADATA_TEXT_FLAG, (guint8 *) value, len);
3553 }
3554
3555 void
3556 atom_udta_add_uint_tag (AtomUDTA * udta, guint32 fourcc, guint32 flags,
3557     guint32 value)
3558 {
3559   guint8 data[8] = { 0, };
3560
3561   if (flags) {
3562     GST_WRITE_UINT16_BE (data, value);
3563     atom_udta_add_tag (udta, fourcc, flags, data, 2);
3564   } else {
3565     GST_WRITE_UINT32_BE (data + 2, value);
3566     atom_udta_add_tag (udta, fourcc, flags, data, 8);
3567   }
3568 }
3569
3570 #define GST_BUFFER_NEW_READONLY(mem, size) \
3571     gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, mem, size, \
3572     0, size, mem, NULL)
3573
3574 void
3575 atom_udta_add_blob_tag (AtomUDTA * udta, guint8 * data, guint size)
3576 {
3577   AtomData *data_atom;
3578   guint len;
3579   guint32 fourcc;
3580
3581   if (size < 8)
3582     return;
3583
3584   /* blob is unparsed atom;
3585    * extract size and fourcc, and wrap remainder in data atom */
3586   len = GST_READ_UINT32_BE (data);
3587   fourcc = GST_READ_UINT32_LE (data + 4);
3588   if (len > size)
3589     return;
3590
3591   data_atom = atom_data_new_from_data (fourcc, data + 8, len - 8);
3592
3593   atom_udta_append_tag (udta,
3594       build_atom_info_wrapper ((Atom *) data_atom, atom_data_copy_data,
3595           atom_data_free));
3596 }
3597
3598 void
3599 atom_udta_add_3gp_tag (AtomUDTA * udta, guint32 fourcc, guint8 * data,
3600     guint size)
3601 {
3602   AtomData *data_atom;
3603
3604   data_atom = atom_data_new (fourcc);
3605
3606   /* need full atom */
3607   atom_data_alloc_mem (data_atom, size + 4);
3608
3609   /* full atom: version and flags */
3610   GST_WRITE_UINT32_BE (data_atom->data, 0);
3611   memcpy (data_atom->data + 4, data, size);
3612
3613   atom_udta_append_tag (udta,
3614       build_atom_info_wrapper ((Atom *) data_atom, atom_data_copy_data,
3615           atom_data_free));
3616 }
3617
3618 guint16
3619 language_code (const char *lang)
3620 {
3621   g_return_val_if_fail (lang != NULL, 0);
3622   g_return_val_if_fail (strlen (lang) == 3, 0);
3623
3624   return (((lang[0] - 0x60) & 0x1F) << 10) + (((lang[1] - 0x60) & 0x1F) << 5) +
3625       ((lang[2] - 0x60) & 0x1F);
3626 }
3627
3628 void
3629 atom_udta_add_3gp_str_int_tag (AtomUDTA * udta, guint32 fourcc,
3630     const gchar * value, gint16 ivalue)
3631 {
3632   gint len = 0, size = 0;
3633   guint8 *data;
3634
3635   if (value) {
3636     len = strlen (value);
3637     size = len + 3;
3638   }
3639
3640   if (ivalue >= 0)
3641     size += 2;
3642
3643   data = g_malloc (size + 3);
3644   /* language tag and null-terminated UTF-8 string */
3645   if (value) {
3646     GST_WRITE_UINT16_BE (data, language_code (GST_QT_MUX_DEFAULT_TAG_LANGUAGE));
3647     /* include 0 terminator */
3648     memcpy (data + 2, value, len + 1);
3649   }
3650   /* 16-bit unsigned int if standalone, otherwise 8-bit */
3651   if (ivalue >= 0) {
3652     if (size == 2)
3653       GST_WRITE_UINT16_BE (data + size - 2, ivalue);
3654     else {
3655       GST_WRITE_UINT8 (data + size - 2, ivalue & 0xFF);
3656       size--;
3657     }
3658   }
3659
3660   atom_udta_add_3gp_tag (udta, fourcc, data, size);
3661   g_free (data);
3662 }
3663
3664 void
3665 atom_udta_add_3gp_str_tag (AtomUDTA * udta, guint32 fourcc, const gchar * value)
3666 {
3667   atom_udta_add_3gp_str_int_tag (udta, fourcc, value, -1);
3668 }
3669
3670 void
3671 atom_udta_add_3gp_uint_tag (AtomUDTA * udta, guint32 fourcc, guint16 value)
3672 {
3673   atom_udta_add_3gp_str_int_tag (udta, fourcc, NULL, value);
3674 }
3675
3676 void
3677 atom_udta_add_xmp_tags (AtomUDTA * udta, GstBuffer * xmpbuffer)
3678 {
3679   AtomData *data_atom = NULL;
3680
3681   if (udta->context->flavor == ATOMS_TREE_FLAVOR_MOV) {
3682     if (xmpbuffer) {
3683       data_atom = atom_data_new_from_gst_buffer (FOURCC_XMP_, xmpbuffer);
3684       udta->entries = g_list_append (udta->entries,
3685           build_atom_info_wrapper ((Atom *) data_atom, atom_data_copy_data,
3686               atom_data_free));
3687     }
3688   } else {
3689     GST_DEBUG ("Not adding xmp to moov atom, it is only used in 'mov' format");
3690   }
3691 }
3692
3693 /*
3694  * Functions for specifying media types
3695  */
3696
3697 static void
3698 atom_minf_set_audio (AtomMINF * minf)
3699 {
3700   atom_minf_clear_handlers (minf);
3701   minf->smhd = atom_smhd_new ();
3702 }
3703
3704 static void
3705 atom_minf_set_video (AtomMINF * minf, AtomsContext * context)
3706 {
3707   atom_minf_clear_handlers (minf);
3708   minf->vmhd = atom_vmhd_new (context);
3709 }
3710
3711 static void
3712 atom_minf_set_subtitle (AtomMINF * minf)
3713 {
3714   atom_minf_clear_handlers (minf);
3715 }
3716
3717 static void
3718 atom_hdlr_set_type (AtomHDLR * hdlr, AtomsContext * context, guint32 comp_type,
3719     guint32 hdlr_type)
3720 {
3721   if (context->flavor == ATOMS_TREE_FLAVOR_MOV) {
3722     hdlr->component_type = comp_type;
3723   }
3724   hdlr->handler_type = hdlr_type;
3725 }
3726
3727 static void
3728 atom_hdlr_set_name (AtomHDLR * hdlr, const char *name)
3729 {
3730   g_free (hdlr->name);
3731   hdlr->name = g_strdup (name);
3732 }
3733
3734 static void
3735 atom_mdia_set_hdlr_type_audio (AtomMDIA * mdia, AtomsContext * context)
3736 {
3737   atom_hdlr_set_type (&mdia->hdlr, context, FOURCC_mhlr, FOURCC_soun);
3738   /* Some players (low-end hardware) check for this name, which is what
3739    * QuickTime itself sets */
3740   atom_hdlr_set_name (&mdia->hdlr, "SoundHandler");
3741 }
3742
3743 static void
3744 atom_mdia_set_hdlr_type_video (AtomMDIA * mdia, AtomsContext * context)
3745 {
3746   atom_hdlr_set_type (&mdia->hdlr, context, FOURCC_mhlr, FOURCC_vide);
3747   /* Some players (low-end hardware) check for this name, which is what
3748    * QuickTime itself sets */
3749   atom_hdlr_set_name (&mdia->hdlr, "VideoHandler");
3750 }
3751
3752 static void
3753 atom_mdia_set_hdlr_type_subtitle (AtomMDIA * mdia, AtomsContext * context)
3754 {
3755   atom_hdlr_set_type (&mdia->hdlr, context, FOURCC_mhlr, FOURCC_sbtl);
3756
3757   /* Just follows the pattern from video and audio above */
3758   atom_hdlr_set_name (&mdia->hdlr, "SubtitleHandler");
3759 }
3760
3761 static void
3762 atom_mdia_set_audio (AtomMDIA * mdia, AtomsContext * context)
3763 {
3764   atom_mdia_set_hdlr_type_audio (mdia, context);
3765   atom_minf_set_audio (&mdia->minf);
3766 }
3767
3768 static void
3769 atom_mdia_set_video (AtomMDIA * mdia, AtomsContext * context)
3770 {
3771   atom_mdia_set_hdlr_type_video (mdia, context);
3772   atom_minf_set_video (&mdia->minf, context);
3773 }
3774
3775 static void
3776 atom_mdia_set_subtitle (AtomMDIA * mdia, AtomsContext * context)
3777 {
3778   atom_mdia_set_hdlr_type_subtitle (mdia, context);
3779   atom_minf_set_subtitle (&mdia->minf);
3780 }
3781
3782 static void
3783 atom_tkhd_set_audio (AtomTKHD * tkhd)
3784 {
3785   tkhd->volume = 0x0100;
3786   tkhd->width = tkhd->height = 0;
3787 }
3788
3789 static void
3790 atom_tkhd_set_video (AtomTKHD * tkhd, AtomsContext * context, guint32 width,
3791     guint32 height)
3792 {
3793   tkhd->volume = 0;
3794
3795   /* qt and ISO base media do not contradict, and examples agree */
3796   tkhd->width = width;
3797   tkhd->height = height;
3798 }
3799
3800 static void
3801 atom_tkhd_set_subtitle (AtomTKHD * tkhd, AtomsContext * context, guint32 width,
3802     guint32 height)
3803 {
3804   tkhd->volume = 0;
3805
3806   /* qt and ISO base media do not contradict, and examples agree */
3807   tkhd->width = width;
3808   tkhd->height = height;
3809 }
3810
3811
3812 static void
3813 atom_edts_add_entry (AtomEDTS * edts, gint index, EditListEntry * entry)
3814 {
3815   EditListEntry *e =
3816       (EditListEntry *) g_slist_nth_data (edts->elst.entries, index);
3817   /* Create a new entry if missing (appends to the list if index is larger) */
3818   if (e == NULL) {
3819     e = g_new (EditListEntry, 1);
3820     edts->elst.entries = g_slist_insert (edts->elst.entries, e, index);
3821   }
3822
3823   /* Update the entry */
3824   *e = *entry;
3825 }
3826
3827 void
3828 atom_trak_edts_clear (AtomTRAK * trak)
3829 {
3830   if (trak->edts) {
3831     atom_edts_free (trak->edts);
3832     trak->edts = NULL;
3833   }
3834 }
3835
3836 /*
3837  * Update an entry in this trak edits list, creating it if needed.
3838  * index is the index of the entry to update, or create if it's past the end.
3839  * duration is in the moov's timescale
3840  * media_time is the offset in the media time to start from (media's timescale)
3841  * rate is a 32 bits fixed-point
3842  */
3843 void
3844 atom_trak_set_elst_entry (AtomTRAK * trak, gint index,
3845     guint32 duration, guint32 media_time, guint32 rate)
3846 {
3847   EditListEntry entry;
3848
3849   entry.duration = duration;
3850   entry.media_time = media_time;
3851   entry.media_rate = rate;
3852
3853   if (trak->edts == NULL)
3854     trak->edts = atom_edts_new ();
3855
3856   atom_edts_add_entry (trak->edts, index, &entry);
3857 }
3858
3859 /* re-negotiation is prevented at top-level, so only 1 entry expected.
3860  * Quite some more care here and elsewhere may be needed to
3861  * support several entries */
3862 static SampleTableEntryMP4A *
3863 atom_trak_add_audio_entry (AtomTRAK * trak, AtomsContext * context,
3864     guint32 type)
3865 {
3866   AtomSTSD *stsd = &trak->mdia.minf.stbl.stsd;
3867   SampleTableEntryMP4A *mp4a = sample_entry_mp4a_new ();
3868
3869   mp4a->se.header.type = type;
3870   mp4a->se.kind = AUDIO;
3871   mp4a->compression_id = -1;
3872   mp4a->se.data_reference_index = 1;
3873
3874   stsd->entries = g_list_prepend (stsd->entries, mp4a);
3875   stsd->n_entries++;
3876   return mp4a;
3877 }
3878
3879 /* return number of centiframes per second */
3880 guint
3881 atom_framerate_to_timescale (gint n, gint d)
3882 {
3883   if (n == 0)
3884     return 10000;
3885
3886   if (d != 1 && d != 1001) {
3887     /* otherwise there are probably rounding errors and we should rather guess
3888      * if it's close enough to a well known framerate */
3889     gst_video_guess_framerate (gst_util_uint64_scale (d, GST_SECOND, n), &n,
3890         &d);
3891   }
3892
3893   return gst_util_uint64_scale (n, 100, d);
3894 }
3895
3896 static SampleTableEntryTMCD *
3897 atom_trak_add_timecode_entry (AtomTRAK * trak, AtomsContext * context,
3898     guint32 trak_timescale, GstVideoTimeCode * tc)
3899 {
3900   AtomSTSD *stsd = &trak->mdia.minf.stbl.stsd;
3901   SampleTableEntryTMCD *tmcd = sample_entry_tmcd_new ();
3902
3903   g_assert (trak_timescale != 0);
3904
3905   trak->mdia.hdlr.component_type = FOURCC_mhlr;
3906   trak->mdia.hdlr.handler_type = FOURCC_tmcd;
3907   g_free (trak->mdia.hdlr.name);
3908   trak->mdia.hdlr.name = g_strdup ("Time Code Media Handler");
3909   trak->mdia.mdhd.time_info.timescale = trak_timescale;
3910
3911   tmcd->se.kind = TIMECODE;
3912   tmcd->se.data_reference_index = 1;
3913   tmcd->tc_flags = TC_24H_MAX;
3914   if (tc->config.flags &= GST_VIDEO_TIME_CODE_FLAGS_DROP_FRAME)
3915     tmcd->tc_flags |= TC_DROP_FRAME;
3916   tmcd->name.language_code = 0;
3917   tmcd->name.name = g_strdup ("Tape");
3918   tmcd->timescale = trak_timescale;
3919   tmcd->frame_duration =
3920       gst_util_uint64_scale (tmcd->timescale, tc->config.fps_d,
3921       tc->config.fps_n);
3922   if (tc->config.fps_d == 1001)
3923     tmcd->n_frames = tc->config.fps_n / 1000;
3924   else
3925     tmcd->n_frames = tc->config.fps_n / tc->config.fps_d;
3926
3927   stsd->entries = g_list_prepend (stsd->entries, tmcd);
3928   stsd->n_entries++;
3929   return tmcd;
3930 }
3931
3932 static SampleTableEntryMP4V *
3933 atom_trak_add_video_entry (AtomTRAK * trak, AtomsContext * context,
3934     guint32 type)
3935 {
3936   SampleTableEntryMP4V *mp4v = sample_entry_mp4v_new (context);
3937   AtomSTSD *stsd = &trak->mdia.minf.stbl.stsd;
3938
3939   mp4v->se.header.type = type;
3940   mp4v->se.kind = VIDEO;
3941   mp4v->se.data_reference_index = 1;
3942   mp4v->horizontal_resolution = 72 << 16;
3943   mp4v->vertical_resolution = 72 << 16;
3944   if (context->flavor == ATOMS_TREE_FLAVOR_MOV) {
3945     mp4v->spatial_quality = 512;
3946     mp4v->temporal_quality = 512;
3947   }
3948
3949   stsd->entries = g_list_prepend (stsd->entries, mp4v);
3950   stsd->n_entries++;
3951   return mp4v;
3952 }
3953
3954 static SampleTableEntryTX3G *
3955 atom_trak_add_subtitle_entry (AtomTRAK * trak, AtomsContext * context,
3956     guint32 type)
3957 {
3958   SampleTableEntryTX3G *tx3g = sample_entry_tx3g_new ();
3959   AtomSTSD *stsd = &trak->mdia.minf.stbl.stsd;
3960
3961   tx3g->se.header.type = type;
3962   tx3g->se.kind = SUBTITLE;
3963   tx3g->se.data_reference_index = 1;
3964
3965   stsd->entries = g_list_prepend (stsd->entries, tx3g);
3966   stsd->n_entries++;
3967   return tx3g;
3968 }
3969
3970
3971 void
3972 atom_trak_set_constant_size_samples (AtomTRAK * trak, guint32 sample_size)
3973 {
3974   trak->mdia.minf.stbl.stsz.sample_size = sample_size;
3975 }
3976
3977 static void
3978 atom_trak_set_audio (AtomTRAK * trak, AtomsContext * context)
3979 {
3980   atom_tkhd_set_audio (&trak->tkhd);
3981   atom_mdia_set_audio (&trak->mdia, context);
3982 }
3983
3984 static void
3985 atom_trak_set_video (AtomTRAK * trak, AtomsContext * context, guint32 width,
3986     guint32 height)
3987 {
3988   atom_tkhd_set_video (&trak->tkhd, context, width, height);
3989   atom_mdia_set_video (&trak->mdia, context);
3990 }
3991
3992 static void
3993 atom_trak_set_subtitle (AtomTRAK * trak, AtomsContext * context)
3994 {
3995   atom_tkhd_set_subtitle (&trak->tkhd, context, 0, 0);
3996   atom_mdia_set_subtitle (&trak->mdia, context);
3997 }
3998
3999 static void
4000 atom_trak_set_audio_commons (AtomTRAK * trak, AtomsContext * context,
4001     guint32 rate)
4002 {
4003   atom_trak_set_audio (trak, context);
4004   trak->mdia.mdhd.time_info.timescale = rate;
4005 }
4006
4007 static void
4008 atom_trak_set_video_commons (AtomTRAK * trak, AtomsContext * context,
4009     guint32 rate, guint32 width, guint32 height)
4010 {
4011   atom_trak_set_video (trak, context, width, height);
4012   trak->mdia.mdhd.time_info.timescale = rate;
4013   trak->tkhd.width = width << 16;
4014   trak->tkhd.height = height << 16;
4015 }
4016
4017 static void
4018 atom_trak_set_subtitle_commons (AtomTRAK * trak, AtomsContext * context)
4019 {
4020   atom_trak_set_subtitle (trak, context);
4021   trak->mdia.mdhd.time_info.timescale = 1000;
4022
4023   trak->tkhd.alternate_group = 2;       /* same for all subtitles */
4024   trak->tkhd.layer = -1;        /* above video (layer 0) */
4025 }
4026
4027 void
4028 sample_table_entry_add_ext_atom (SampleTableEntry * ste, AtomInfo * ext)
4029 {
4030   GList **list = NULL;
4031   if (ste->kind == AUDIO) {
4032     list = &(((SampleTableEntryMP4A *) ste)->extension_atoms);
4033   } else if (ste->kind == VIDEO) {
4034     list = &(((SampleTableEntryMP4V *) ste)->extension_atoms);
4035   } else {
4036     g_assert_not_reached ();
4037     return;
4038   }
4039
4040   *list = g_list_prepend (*list, ext);
4041 }
4042
4043 SampleTableEntryMP4A *
4044 atom_trak_set_audio_type (AtomTRAK * trak, AtomsContext * context,
4045     AudioSampleEntry * entry, guint32 scale, AtomInfo * ext, gint sample_size)
4046 {
4047   SampleTableEntryMP4A *ste;
4048
4049   atom_trak_set_audio_commons (trak, context, scale);
4050   atom_stsd_remove_entries (&trak->mdia.minf.stbl.stsd);
4051   ste = atom_trak_add_audio_entry (trak, context, entry->fourcc);
4052
4053   trak->is_video = FALSE;
4054   trak->is_h264 = FALSE;
4055
4056   ste->version = entry->version;
4057   ste->compression_id = entry->compression_id;
4058   ste->sample_size = entry->sample_size;
4059   ste->sample_rate = entry->sample_rate << 16;
4060   ste->channels = entry->channels;
4061
4062   ste->samples_per_packet = entry->samples_per_packet;
4063   ste->bytes_per_sample = entry->bytes_per_sample;
4064   ste->bytes_per_packet = entry->bytes_per_packet;
4065   ste->bytes_per_frame = entry->bytes_per_frame;
4066
4067   if (ext)
4068     ste->extension_atoms = g_list_prepend (ste->extension_atoms, ext);
4069
4070   /* 0 size means variable size */
4071   atom_trak_set_constant_size_samples (trak, sample_size);
4072
4073   return ste;
4074 }
4075
4076 SampleTableEntryTMCD *
4077 atom_trak_set_timecode_type (AtomTRAK * trak, AtomsContext * context,
4078     guint32 trak_timescale, GstVideoTimeCode * tc)
4079 {
4080   SampleTableEntryTMCD *ste;
4081   AtomGMHD *gmhd = trak->mdia.minf.gmhd;
4082
4083   if (context->flavor != ATOMS_TREE_FLAVOR_MOV) {
4084     return NULL;
4085   }
4086
4087   ste = atom_trak_add_timecode_entry (trak, context, trak_timescale, tc);
4088
4089   gmhd = atom_gmhd_new ();
4090   gmhd->gmin.graphics_mode = 0x0040;
4091   gmhd->gmin.opcolor[0] = 0x8000;
4092   gmhd->gmin.opcolor[1] = 0x8000;
4093   gmhd->gmin.opcolor[2] = 0x8000;
4094   gmhd->tmcd = atom_tmcd_new ();
4095   gmhd->tmcd->tcmi.text_size = 12;
4096   gmhd->tmcd->tcmi.font_name = g_strdup ("Chicago");    /* Pascal string */
4097
4098   trak->mdia.minf.gmhd = gmhd;
4099   trak->is_video = FALSE;
4100   trak->is_h264 = FALSE;
4101
4102   return ste;
4103 }
4104
4105 SampleTableEntry *
4106 atom_trak_set_caption_type (AtomTRAK * trak, AtomsContext * context,
4107     guint32 trak_timescale, guint32 caption_type)
4108 {
4109   SampleTableEntry *ste;
4110   AtomGMHD *gmhd = trak->mdia.minf.gmhd;
4111   AtomSTSD *stsd = &trak->mdia.minf.stbl.stsd;
4112
4113   if (context->flavor != ATOMS_TREE_FLAVOR_MOV) {
4114     return NULL;
4115   }
4116
4117   trak->mdia.mdhd.time_info.timescale = trak_timescale;
4118   trak->mdia.hdlr.component_type = FOURCC_mhlr;
4119   trak->mdia.hdlr.handler_type = FOURCC_clcp;
4120   g_free (trak->mdia.hdlr.name);
4121   trak->mdia.hdlr.name = g_strdup ("Closed Caption Media Handler");
4122
4123   ste = g_new0 (SampleTableEntry, 1);
4124   atom_sample_entry_init (ste, caption_type);
4125   ste->kind = CLOSEDCAPTION;
4126   ste->data_reference_index = 1;
4127   stsd->entries = g_list_prepend (stsd->entries, ste);
4128   stsd->n_entries++;
4129
4130   gmhd = atom_gmhd_new ();
4131   gmhd->gmin.graphics_mode = 0x0040;
4132   gmhd->gmin.opcolor[0] = 0x8000;
4133   gmhd->gmin.opcolor[1] = 0x8000;
4134   gmhd->gmin.opcolor[2] = 0x8000;
4135
4136   trak->mdia.minf.gmhd = gmhd;
4137   trak->is_video = FALSE;
4138   trak->is_h264 = FALSE;
4139
4140   return ste;
4141 }
4142
4143 static AtomInfo *
4144 build_pasp_extension (gint par_width, gint par_height)
4145 {
4146   AtomData *atom_data = atom_data_new (FOURCC_pasp);
4147   guint8 *data;
4148
4149   atom_data_alloc_mem (atom_data, 8);
4150   data = atom_data->data;
4151
4152   /* ihdr = image header box */
4153   GST_WRITE_UINT32_BE (data, par_width);
4154   GST_WRITE_UINT32_BE (data + 4, par_height);
4155
4156   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
4157       atom_data_free);
4158 }
4159
4160 AtomInfo *
4161 build_fiel_extension (GstVideoInterlaceMode mode, GstVideoFieldOrder order)
4162 {
4163   AtomData *atom_data = atom_data_new (FOURCC_fiel);
4164   guint8 *data;
4165   gint field_order;
4166   gint interlace;
4167
4168   atom_data_alloc_mem (atom_data, 2);
4169   data = atom_data->data;
4170
4171   if (mode == GST_VIDEO_INTERLACE_MODE_PROGRESSIVE) {
4172     interlace = 1;
4173     field_order = 0;
4174   } else if (mode == GST_VIDEO_INTERLACE_MODE_INTERLEAVED) {
4175     interlace = 2;
4176     field_order = order == GST_VIDEO_FIELD_ORDER_TOP_FIELD_FIRST ? 9 : 14;
4177   } else {
4178     interlace = 0;
4179     field_order = 0;
4180   }
4181
4182   GST_WRITE_UINT8 (data, interlace);
4183   GST_WRITE_UINT8 (data + 1, field_order);
4184
4185   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
4186       atom_data_free);
4187 }
4188
4189 AtomInfo *
4190 build_colr_extension (const GstVideoColorimetry * colorimetry, gboolean is_mp4)
4191 {
4192   AtomData *atom_data = atom_data_new (FOURCC_colr);
4193   guint8 *data;
4194   guint16 primaries;
4195   guint16 transfer_function;
4196   guint16 matrix;
4197
4198   switch (colorimetry->primaries) {
4199     case GST_VIDEO_COLOR_PRIMARIES_BT709:
4200       primaries = 1;
4201       break;
4202     case GST_VIDEO_COLOR_PRIMARIES_BT470BG:
4203       primaries = 5;
4204       break;
4205     case GST_VIDEO_COLOR_PRIMARIES_SMPTE170M:
4206     case GST_VIDEO_COLOR_PRIMARIES_SMPTE240M:
4207       primaries = 6;
4208       break;
4209     case GST_VIDEO_COLOR_PRIMARIES_BT2020:
4210       primaries = 9;
4211       break;
4212     case GST_VIDEO_COLOR_PRIMARIES_UNKNOWN:
4213     default:
4214       primaries = 2;
4215       break;
4216   }
4217
4218   switch (colorimetry->transfer) {
4219     case GST_VIDEO_TRANSFER_BT709:
4220       transfer_function = 1;
4221       break;
4222     case GST_VIDEO_TRANSFER_SMPTE240M:
4223       transfer_function = 7;
4224       break;
4225     case GST_VIDEO_TRANSFER_UNKNOWN:
4226     default:
4227       transfer_function = 2;
4228       break;
4229   }
4230
4231   switch (colorimetry->matrix) {
4232     case GST_VIDEO_COLOR_MATRIX_BT709:
4233       matrix = 1;
4234       break;
4235     case GST_VIDEO_COLOR_MATRIX_BT601:
4236       matrix = 6;
4237       break;
4238     case GST_VIDEO_COLOR_MATRIX_SMPTE240M:
4239       matrix = 7;
4240       break;
4241     case GST_VIDEO_COLOR_MATRIX_BT2020:
4242       matrix = 9;
4243       break;
4244     case GST_VIDEO_COLOR_MATRIX_UNKNOWN:
4245     default:
4246       matrix = 2;
4247       break;
4248   }
4249
4250   atom_data_alloc_mem (atom_data, 10 + (is_mp4 ? 1 : 0));
4251   data = atom_data->data;
4252
4253   /* colour specification box */
4254   if (is_mp4)
4255     GST_WRITE_UINT32_LE (data, FOURCC_nclx);
4256   else
4257     GST_WRITE_UINT32_LE (data, FOURCC_nclc);
4258
4259   GST_WRITE_UINT16_BE (data + 4, primaries);
4260   GST_WRITE_UINT16_BE (data + 6, transfer_function);
4261   GST_WRITE_UINT16_BE (data + 8, matrix);
4262
4263   if (is_mp4) {
4264     GST_WRITE_UINT8 (data + 10,
4265         colorimetry->range == GST_VIDEO_COLOR_RANGE_0_255 ? 0x80 : 0x00);
4266   }
4267
4268   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
4269       atom_data_free);
4270 }
4271
4272 AtomInfo *
4273 build_clap_extension (gint width_n, gint width_d, gint height_n, gint height_d,
4274     gint h_off_n, gint h_off_d, gint v_off_n, gint v_off_d)
4275 {
4276   AtomData *atom_data = atom_data_new (FOURCC_clap);
4277   guint8 *data;
4278
4279   atom_data_alloc_mem (atom_data, 32);
4280   data = atom_data->data;
4281
4282   GST_WRITE_UINT32_BE (data, width_n);
4283   GST_WRITE_UINT32_BE (data + 4, width_d);
4284   GST_WRITE_UINT32_BE (data + 8, height_n);
4285   GST_WRITE_UINT32_BE (data + 12, height_d);
4286   GST_WRITE_UINT32_BE (data + 16, h_off_n);
4287   GST_WRITE_UINT32_BE (data + 20, h_off_d);
4288   GST_WRITE_UINT32_BE (data + 24, v_off_n);
4289   GST_WRITE_UINT32_BE (data + 28, v_off_d);
4290
4291   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
4292       atom_data_free);
4293 }
4294
4295 AtomInfo *
4296 build_tapt_extension (gint clef_width, gint clef_height, gint prof_width,
4297     gint prof_height, gint enof_width, gint enof_height)
4298 {
4299   AtomData *atom_data = atom_data_new (FOURCC_tapt);
4300   guint8 *data;
4301
4302   atom_data_alloc_mem (atom_data, 60);
4303   data = atom_data->data;
4304
4305   GST_WRITE_UINT32_BE (data, 20);
4306   GST_WRITE_UINT32_LE (data + 4, FOURCC_clef);
4307   GST_WRITE_UINT32_BE (data + 8, 0);
4308   GST_WRITE_UINT32_BE (data + 12, clef_width);
4309   GST_WRITE_UINT32_BE (data + 16, clef_height);
4310
4311   GST_WRITE_UINT32_BE (data + 20, 20);
4312   GST_WRITE_UINT32_LE (data + 24, FOURCC_prof);
4313   GST_WRITE_UINT32_BE (data + 28, 0);
4314   GST_WRITE_UINT32_BE (data + 32, prof_width);
4315   GST_WRITE_UINT32_BE (data + 36, prof_height);
4316
4317   GST_WRITE_UINT32_BE (data + 40, 20);
4318   GST_WRITE_UINT32_LE (data + 44, FOURCC_enof);
4319   GST_WRITE_UINT32_BE (data + 48, 0);
4320   GST_WRITE_UINT32_BE (data + 52, enof_width);
4321   GST_WRITE_UINT32_BE (data + 56, enof_height);
4322
4323
4324   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
4325       atom_data_free);
4326 }
4327
4328 static AtomInfo *
4329 build_mov_video_sample_description_padding_extension (void)
4330 {
4331   AtomData *atom_data = atom_data_new (FOURCC_clap);
4332
4333   return build_atom_info_wrapper ((Atom *) atom_data, atom_copy_empty,
4334       atom_data_free);
4335 }
4336
4337 SampleTableEntryMP4V *
4338 atom_trak_set_video_type (AtomTRAK * trak, AtomsContext * context,
4339     VisualSampleEntry * entry, guint32 scale, GList * ext_atoms_list)
4340 {
4341   SampleTableEntryMP4V *ste;
4342   guint dwidth, dheight;
4343   gint par_n = 0, par_d = 0;
4344
4345   par_n = entry->par_n;
4346   par_d = entry->par_d;
4347
4348   dwidth = entry->width;
4349   dheight = entry->height;
4350   /* ISO file spec says track header w/h indicates track's visual presentation
4351    * (so this together with pixels w/h implicitly defines PAR) */
4352   if (par_n && (context->flavor != ATOMS_TREE_FLAVOR_MOV)) {
4353     /* Assumes square pixels display */
4354     if (!gst_video_calculate_display_ratio (&dwidth, &dheight, entry->width,
4355             entry->height, par_n, par_d, 1, 1)) {
4356       GST_WARNING ("Could not calculate display ratio");
4357     }
4358   }
4359
4360   atom_trak_set_video_commons (trak, context, scale, dwidth, dheight);
4361   atom_stsd_remove_entries (&trak->mdia.minf.stbl.stsd);
4362   ste = atom_trak_add_video_entry (trak, context, entry->fourcc);
4363
4364   trak->is_video = TRUE;
4365   trak->is_h264 = (entry->fourcc == FOURCC_avc1
4366       || entry->fourcc == FOURCC_avc3);
4367
4368   ste->version = entry->version;
4369   ste->width = entry->width;
4370   ste->height = entry->height;
4371   ste->depth = entry->depth;
4372   ste->color_table_id = entry->color_table_id;
4373   ste->frame_count = entry->frame_count;
4374
4375   if (ext_atoms_list)
4376     ste->extension_atoms = g_list_concat (ste->extension_atoms, ext_atoms_list);
4377
4378   ste->extension_atoms = g_list_append (ste->extension_atoms,
4379       build_pasp_extension (par_n, par_d));
4380
4381   if (context->flavor == ATOMS_TREE_FLAVOR_MOV) {
4382     /* append 0 as a terminator "length" to work around some broken software */
4383     ste->extension_atoms =
4384         g_list_append (ste->extension_atoms,
4385         build_mov_video_sample_description_padding_extension ());
4386   }
4387
4388   return ste;
4389 }
4390
4391 void
4392 subtitle_sample_entry_init (SubtitleSampleEntry * entry)
4393 {
4394   entry->font_size = 0;
4395   entry->font_face = 0;
4396   entry->foreground_color_rgba = 0xFFFFFFFF;    /* all white, opaque */
4397 }
4398
4399 SampleTableEntryTX3G *
4400 atom_trak_set_subtitle_type (AtomTRAK * trak, AtomsContext * context,
4401     SubtitleSampleEntry * entry)
4402 {
4403   SampleTableEntryTX3G *tx3g;
4404
4405   atom_trak_set_subtitle_commons (trak, context);
4406   atom_stsd_remove_entries (&trak->mdia.minf.stbl.stsd);
4407   tx3g = atom_trak_add_subtitle_entry (trak, context, entry->fourcc);
4408
4409   tx3g->font_face = entry->font_face;
4410   tx3g->font_size = entry->font_size;
4411   tx3g->foreground_color_rgba = entry->foreground_color_rgba;
4412
4413   trak->is_video = FALSE;
4414   trak->is_h264 = FALSE;
4415
4416   return tx3g;
4417 }
4418
4419 static void
4420 atom_mfhd_init (AtomMFHD * mfhd, guint32 sequence_number)
4421 {
4422   guint8 flags[3] = { 0, 0, 0 };
4423
4424   atom_full_init (&(mfhd->header), FOURCC_mfhd, 0, 0, 0, flags);
4425   mfhd->sequence_number = sequence_number;
4426 }
4427
4428 static void
4429 atom_moof_init (AtomMOOF * moof, AtomsContext * context,
4430     guint32 sequence_number)
4431 {
4432   atom_header_set (&moof->header, FOURCC_moof, 0, 0);
4433   atom_mfhd_init (&moof->mfhd, sequence_number);
4434   moof->trafs = NULL;
4435 }
4436
4437 AtomMOOF *
4438 atom_moof_new (AtomsContext * context, guint32 sequence_number)
4439 {
4440   AtomMOOF *moof = g_new0 (AtomMOOF, 1);
4441
4442   atom_moof_init (moof, context, sequence_number);
4443   return moof;
4444 }
4445
4446 static void
4447 atom_trun_free (AtomTRUN * trun)
4448 {
4449   atom_full_clear (&trun->header);
4450   atom_array_clear (&trun->entries);
4451   g_free (trun);
4452 }
4453
4454 static void
4455 atom_sdtp_free (AtomSDTP * sdtp)
4456 {
4457   atom_full_clear (&sdtp->header);
4458   atom_array_clear (&sdtp->entries);
4459   g_free (sdtp);
4460 }
4461
4462 void
4463 atom_traf_free (AtomTRAF * traf)
4464 {
4465   GList *walker;
4466
4467   walker = traf->truns;
4468   while (walker) {
4469     atom_trun_free ((AtomTRUN *) walker->data);
4470     walker = g_list_next (walker);
4471   }
4472   g_list_free (traf->truns);
4473   traf->truns = NULL;
4474
4475   walker = traf->sdtps;
4476   while (walker) {
4477     atom_sdtp_free ((AtomSDTP *) walker->data);
4478     walker = g_list_next (walker);
4479   }
4480   g_list_free (traf->sdtps);
4481   traf->sdtps = NULL;
4482
4483   g_free (traf);
4484 }
4485
4486 void
4487 atom_moof_free (AtomMOOF * moof)
4488 {
4489   GList *walker;
4490
4491   walker = moof->trafs;
4492   while (walker) {
4493     atom_traf_free ((AtomTRAF *) walker->data);
4494     walker = g_list_next (walker);
4495   }
4496   g_list_free (moof->trafs);
4497   moof->trafs = NULL;
4498
4499   g_free (moof);
4500 }
4501
4502 static guint64
4503 atom_mfhd_copy_data (AtomMFHD * mfhd, guint8 ** buffer, guint64 * size,
4504     guint64 * offset)
4505 {
4506   guint64 original_offset = *offset;
4507
4508   if (!atom_full_copy_data (&mfhd->header, buffer, size, offset)) {
4509     return 0;
4510   }
4511
4512   prop_copy_uint32 (mfhd->sequence_number, buffer, size, offset);
4513
4514   atom_write_size (buffer, size, offset, original_offset);
4515   return *offset - original_offset;
4516 }
4517
4518 static guint64
4519 atom_tfhd_copy_data (AtomTFHD * tfhd, guint8 ** buffer, guint64 * size,
4520     guint64 * offset)
4521 {
4522   guint64 original_offset = *offset;
4523   guint32 flags;
4524
4525   if (!atom_full_copy_data (&tfhd->header, buffer, size, offset)) {
4526     return 0;
4527   }
4528
4529   prop_copy_uint32 (tfhd->track_ID, buffer, size, offset);
4530
4531   flags = atom_full_get_flags_as_uint (&tfhd->header);
4532
4533   if (flags & TF_BASE_DATA_OFFSET)
4534     prop_copy_uint64 (tfhd->base_data_offset, buffer, size, offset);
4535   if (flags & TF_SAMPLE_DESCRIPTION_INDEX)
4536     prop_copy_uint32 (tfhd->sample_description_index, buffer, size, offset);
4537   if (flags & TF_DEFAULT_SAMPLE_DURATION)
4538     prop_copy_uint32 (tfhd->default_sample_duration, buffer, size, offset);
4539   if (flags & TF_DEFAULT_SAMPLE_SIZE)
4540     prop_copy_uint32 (tfhd->default_sample_size, buffer, size, offset);
4541   if (flags & TF_DEFAULT_SAMPLE_FLAGS)
4542     prop_copy_uint32 (tfhd->default_sample_flags, buffer, size, offset);
4543
4544   atom_write_size (buffer, size, offset, original_offset);
4545   return *offset - original_offset;
4546 }
4547
4548 static guint64
4549 atom_tfdt_copy_data (AtomTFDT * tfdt, guint8 ** buffer, guint64 * size,
4550     guint64 * offset)
4551 {
4552   guint64 original_offset = *offset;
4553
4554   if (!atom_full_copy_data (&tfdt->header, buffer, size, offset)) {
4555     return 0;
4556   }
4557
4558   /* 32-bit time if version == 0 else 64-bit: */
4559   if (tfdt->header.version == 0)
4560     prop_copy_uint32 (tfdt->base_media_decode_time, buffer, size, offset);
4561   else
4562     prop_copy_uint64 (tfdt->base_media_decode_time, buffer, size, offset);
4563
4564   atom_write_size (buffer, size, offset, original_offset);
4565   return *offset - original_offset;
4566 }
4567
4568 static guint64
4569 atom_trun_copy_data (AtomTRUN * trun, guint8 ** buffer, guint64 * size,
4570     guint64 * offset, guint32 * data_offset)
4571 {
4572   guint64 original_offset = *offset;
4573   guint32 flags, i;
4574
4575   flags = atom_full_get_flags_as_uint (&trun->header);
4576
4577   /* if first trun in moof, forcibly add data_offset and record
4578    * where it must be written later on */
4579   if (data_offset && !*data_offset) {
4580     flags |= TR_DATA_OFFSET;
4581   } else {
4582     flags &= ~TR_DATA_OFFSET;
4583   }
4584
4585   atom_full_set_flags_as_uint (&trun->header, flags);
4586
4587   if (!atom_full_copy_data (&trun->header, buffer, size, offset)) {
4588     return 0;
4589   }
4590
4591   prop_copy_uint32 (trun->sample_count, buffer, size, offset);
4592
4593   if (flags & TR_DATA_OFFSET) {
4594     *data_offset = *offset;
4595     prop_copy_int32 (trun->data_offset, buffer, size, offset);
4596   }
4597   if (flags & TR_FIRST_SAMPLE_FLAGS)
4598     prop_copy_uint32 (trun->first_sample_flags, buffer, size, offset);
4599
4600   for (i = 0; i < atom_array_get_len (&trun->entries); i++) {
4601     TRUNSampleEntry *entry = &atom_array_index (&trun->entries, i);
4602
4603     if (flags & TR_SAMPLE_DURATION)
4604       prop_copy_uint32 (entry->sample_duration, buffer, size, offset);
4605     if (flags & TR_SAMPLE_SIZE)
4606       prop_copy_uint32 (entry->sample_size, buffer, size, offset);
4607     if (flags & TR_SAMPLE_FLAGS)
4608       prop_copy_uint32 (entry->sample_flags, buffer, size, offset);
4609     if (flags & TR_COMPOSITION_TIME_OFFSETS)
4610       prop_copy_uint32 (entry->sample_composition_time_offset,
4611           buffer, size, offset);
4612   }
4613
4614   atom_write_size (buffer, size, offset, original_offset);
4615   return *offset - original_offset;
4616 }
4617
4618 static guint64
4619 atom_sdtp_copy_data (AtomSDTP * sdtp, guint8 ** buffer, guint64 * size,
4620     guint64 * offset)
4621 {
4622   guint64 original_offset = *offset;
4623
4624   if (!atom_full_copy_data (&sdtp->header, buffer, size, offset)) {
4625     return 0;
4626   }
4627
4628   /* all entries at once */
4629   prop_copy_fixed_size_string (&atom_array_index (&sdtp->entries, 0),
4630       atom_array_get_len (&sdtp->entries), buffer, size, offset);
4631
4632   atom_write_size (buffer, size, offset, original_offset);
4633   return *offset - original_offset;
4634 }
4635
4636 static guint64
4637 atom_traf_copy_data (AtomTRAF * traf, guint8 ** buffer, guint64 * size,
4638     guint64 * offset, guint32 * data_offset)
4639 {
4640   guint64 original_offset = *offset;
4641   GList *walker;
4642
4643   if (!atom_copy_data (&traf->header, buffer, size, offset)) {
4644     return 0;
4645   }
4646   if (!atom_tfhd_copy_data (&traf->tfhd, buffer, size, offset)) {
4647     return 0;
4648   }
4649   if (!atom_tfdt_copy_data (&traf->tfdt, buffer, size, offset)) {
4650     return 0;
4651   }
4652
4653   walker = g_list_first (traf->truns);
4654   while (walker != NULL) {
4655     if (!atom_trun_copy_data ((AtomTRUN *) walker->data, buffer, size, offset,
4656             data_offset)) {
4657       return 0;
4658     }
4659     walker = g_list_next (walker);
4660   }
4661
4662   walker = g_list_first (traf->sdtps);
4663   while (walker != NULL) {
4664     if (!atom_sdtp_copy_data ((AtomSDTP *) walker->data, buffer, size, offset)) {
4665       return 0;
4666     }
4667     walker = g_list_next (walker);
4668   }
4669
4670   atom_write_size (buffer, size, offset, original_offset);
4671   return *offset - original_offset;
4672 }
4673
4674 /* creates moof atom; metadata is written expecting actual buffer data
4675  * is in mdata directly after moof, and is consecutively written per trak */
4676 guint64
4677 atom_moof_copy_data (AtomMOOF * moof, guint8 ** buffer,
4678     guint64 * size, guint64 * offset)
4679 {
4680   guint64 original_offset = *offset;
4681   GList *walker;
4682   guint32 data_offset = 0;
4683
4684   if (!atom_copy_data (&moof->header, buffer, size, offset))
4685     return 0;
4686
4687   if (!atom_mfhd_copy_data (&moof->mfhd, buffer, size, offset))
4688     return 0;
4689
4690   walker = g_list_first (moof->trafs);
4691   while (walker != NULL) {
4692     if (!atom_traf_copy_data ((AtomTRAF *) walker->data, buffer, size, offset,
4693             &data_offset)) {
4694       return 0;
4695     }
4696     walker = g_list_next (walker);
4697   }
4698
4699   atom_write_size (buffer, size, offset, original_offset);
4700
4701   if (*buffer && data_offset) {
4702     /* first trun needs a data-offset relative to moof start
4703      *   = moof size + mdat prefix */
4704     GST_WRITE_UINT32_BE (*buffer + data_offset, *offset - original_offset + 8);
4705   }
4706
4707   return *offset - original_offset;
4708 }
4709
4710 static void
4711 atom_tfhd_init (AtomTFHD * tfhd, guint32 track_ID)
4712 {
4713   guint8 flags[3] = { 0, 0, 0 };
4714
4715   atom_full_init (&tfhd->header, FOURCC_tfhd, 0, 0, 0, flags);
4716   tfhd->track_ID = track_ID;
4717   tfhd->base_data_offset = 0;
4718   tfhd->sample_description_index = 1;
4719   tfhd->default_sample_duration = 0;
4720   tfhd->default_sample_size = 0;
4721   tfhd->default_sample_flags = 0;
4722 }
4723
4724 static void
4725 atom_tfdt_init (AtomTFDT * tfdt)
4726 {
4727   guint8 flags[3] = { 0, 0, 0 };
4728   atom_full_init (&tfdt->header, FOURCC_tfdt, 0, 0, 0, flags);
4729
4730   tfdt->base_media_decode_time = 0;
4731 }
4732
4733 static void
4734 atom_trun_init (AtomTRUN * trun)
4735 {
4736   guint8 flags[3] = { 0, 0, 0 };
4737
4738   atom_full_init (&trun->header, FOURCC_trun, 0, 0, 0, flags);
4739   trun->sample_count = 0;
4740   trun->data_offset = 0;
4741   trun->first_sample_flags = 0;
4742   atom_array_init (&trun->entries, 512);
4743 }
4744
4745 static AtomTRUN *
4746 atom_trun_new (void)
4747 {
4748   AtomTRUN *trun = g_new0 (AtomTRUN, 1);
4749
4750   atom_trun_init (trun);
4751   return trun;
4752 }
4753
4754 static void
4755 atom_sdtp_init (AtomSDTP * sdtp)
4756 {
4757   guint8 flags[3] = { 0, 0, 0 };
4758
4759   atom_full_init (&sdtp->header, FOURCC_sdtp, 0, 0, 0, flags);
4760   atom_array_init (&sdtp->entries, 512);
4761 }
4762
4763 static AtomSDTP *
4764 atom_sdtp_new (AtomsContext * context)
4765 {
4766   AtomSDTP *sdtp = g_new0 (AtomSDTP, 1);
4767
4768   atom_sdtp_init (sdtp);
4769   return sdtp;
4770 }
4771
4772 static void
4773 atom_traf_add_sdtp (AtomTRAF * traf, AtomSDTP * sdtp)
4774 {
4775   traf->sdtps = g_list_append (traf->sdtps, sdtp);
4776 }
4777
4778 static void
4779 atom_sdtp_add_samples (AtomSDTP * sdtp, guint8 val)
4780 {
4781   /* it does not make much/any sense according to specs,
4782    * but that's how MS isml samples seem to do it */
4783   atom_array_append (&sdtp->entries, val, 256);
4784 }
4785
4786 static void
4787 atom_trun_add_samples (AtomTRUN * trun, guint32 delta, guint32 size,
4788     guint32 flags, gint64 pts_offset)
4789 {
4790   TRUNSampleEntry nentry;
4791
4792   if (pts_offset != 0)
4793     trun->header.flags[1] |= (TR_COMPOSITION_TIME_OFFSETS >> 8);
4794
4795   nentry.sample_duration = delta;
4796   nentry.sample_size = size;
4797   nentry.sample_flags = flags;
4798   nentry.sample_composition_time_offset = pts_offset;
4799   atom_array_append (&trun->entries, nentry, 256);
4800   trun->sample_count++;
4801 }
4802
4803 static void
4804 atom_traf_init (AtomTRAF * traf, AtomsContext * context, guint32 track_ID)
4805 {
4806   atom_header_set (&traf->header, FOURCC_traf, 0, 0);
4807   atom_tfdt_init (&traf->tfdt);
4808   atom_tfhd_init (&traf->tfhd, track_ID);
4809   traf->truns = NULL;
4810
4811   if (context->flavor == ATOMS_TREE_FLAVOR_ISML)
4812     atom_traf_add_sdtp (traf, atom_sdtp_new (context));
4813 }
4814
4815 AtomTRAF *
4816 atom_traf_new (AtomsContext * context, guint32 track_ID)
4817 {
4818   AtomTRAF *traf = g_new0 (AtomTRAF, 1);
4819
4820   atom_traf_init (traf, context, track_ID);
4821   return traf;
4822 }
4823
4824 void
4825 atom_traf_set_base_decode_time (AtomTRAF * traf, guint64 base_decode_time)
4826 {
4827   traf->tfdt.base_media_decode_time = base_decode_time;
4828   /* If we need to write a 64-bit tfdt, set the atom version */
4829   if (base_decode_time > G_MAXUINT32)
4830     traf->tfdt.header.version = 1;
4831 }
4832
4833 static void
4834 atom_traf_add_trun (AtomTRAF * traf, AtomTRUN * trun)
4835 {
4836   traf->truns = g_list_append (traf->truns, trun);
4837 }
4838
4839 void
4840 atom_traf_add_samples (AtomTRAF * traf, guint32 delta, guint32 size,
4841     gboolean sync, gint64 pts_offset, gboolean sdtp_sync)
4842 {
4843   AtomTRUN *trun;
4844   guint32 flags;
4845
4846   /* 0x10000 is sample-is-difference-sample flag
4847    * low byte stuff is what ismv uses */
4848   flags = (sync ? 0x0 : 0x10000) | (sdtp_sync ? 0x40 : 0xc0);
4849
4850   if (G_UNLIKELY (!traf->truns)) {
4851     trun = atom_trun_new ();
4852     atom_traf_add_trun (traf, trun);
4853     /* optimistic; indicate all defaults present in tfhd */
4854     traf->tfhd.header.flags[2] = TF_DEFAULT_SAMPLE_DURATION |
4855         TF_DEFAULT_SAMPLE_SIZE | TF_DEFAULT_SAMPLE_FLAGS;
4856     traf->tfhd.default_sample_duration = delta;
4857     traf->tfhd.default_sample_size = size;
4858     traf->tfhd.default_sample_flags = flags;
4859     trun->first_sample_flags = flags;
4860   }
4861
4862   trun = traf->truns->data;
4863
4864   /* check if still matching defaults,
4865    * if not, abandon default and need entry for each sample */
4866   if (traf->tfhd.default_sample_duration != delta) {
4867     traf->tfhd.header.flags[2] &= ~TF_DEFAULT_SAMPLE_DURATION;
4868     trun->header.flags[1] |= (TR_SAMPLE_DURATION >> 8);
4869   }
4870   if (traf->tfhd.default_sample_size != size) {
4871     traf->tfhd.header.flags[2] &= ~TF_DEFAULT_SAMPLE_SIZE;
4872     trun->header.flags[1] |= (TR_SAMPLE_SIZE >> 8);
4873   }
4874   if (traf->tfhd.default_sample_flags != flags) {
4875     if (trun->sample_count == 1) {
4876       /* at least will need first sample flag */
4877       traf->tfhd.default_sample_flags = flags;
4878       trun->header.flags[2] |= TR_FIRST_SAMPLE_FLAGS;
4879     } else {
4880       /* now we need sample flags for each sample */
4881       traf->tfhd.header.flags[2] &= ~TF_DEFAULT_SAMPLE_FLAGS;
4882       trun->header.flags[1] |= (TR_SAMPLE_FLAGS >> 8);
4883       trun->header.flags[2] &= ~TR_FIRST_SAMPLE_FLAGS;
4884     }
4885   }
4886
4887   atom_trun_add_samples (traf->truns->data, delta, size, flags, pts_offset);
4888
4889   if (traf->sdtps)
4890     atom_sdtp_add_samples (traf->sdtps->data, 0x10 | ((flags & 0xff) >> 4));
4891 }
4892
4893 guint32
4894 atom_traf_get_sample_num (AtomTRAF * traf)
4895 {
4896   AtomTRUN *trun;
4897
4898   if (G_UNLIKELY (!traf->truns))
4899     return 0;
4900
4901   trun = traf->truns->data;
4902   return atom_array_get_len (&trun->entries);
4903 }
4904
4905 void
4906 atom_moof_add_traf (AtomMOOF * moof, AtomTRAF * traf)
4907 {
4908   moof->trafs = g_list_append (moof->trafs, traf);
4909 }
4910
4911 static void
4912 atom_tfra_free (AtomTFRA * tfra)
4913 {
4914   atom_full_clear (&tfra->header);
4915   atom_array_clear (&tfra->entries);
4916   g_free (tfra);
4917 }
4918
4919 AtomMFRA *
4920 atom_mfra_new (AtomsContext * context)
4921 {
4922   AtomMFRA *mfra = g_new0 (AtomMFRA, 1);
4923
4924   atom_header_set (&mfra->header, FOURCC_mfra, 0, 0);
4925   return mfra;
4926 }
4927
4928 void
4929 atom_mfra_add_tfra (AtomMFRA * mfra, AtomTFRA * tfra)
4930 {
4931   mfra->tfras = g_list_append (mfra->tfras, tfra);
4932 }
4933
4934 void
4935 atom_mfra_free (AtomMFRA * mfra)
4936 {
4937   GList *walker;
4938
4939   walker = mfra->tfras;
4940   while (walker) {
4941     atom_tfra_free ((AtomTFRA *) walker->data);
4942     walker = g_list_next (walker);
4943   }
4944   g_list_free (mfra->tfras);
4945   mfra->tfras = NULL;
4946
4947   atom_clear (&mfra->header);
4948   g_free (mfra);
4949 }
4950
4951 static void
4952 atom_tfra_init (AtomTFRA * tfra, guint32 track_ID)
4953 {
4954   guint8 flags[3] = { 0, 0, 0 };
4955
4956   atom_full_init (&tfra->header, FOURCC_tfra, 0, 0, 0, flags);
4957   tfra->track_ID = track_ID;
4958   atom_array_init (&tfra->entries, 512);
4959 }
4960
4961 AtomTFRA *
4962 atom_tfra_new (AtomsContext * context, guint32 track_ID)
4963 {
4964   AtomTFRA *tfra = g_new0 (AtomTFRA, 1);
4965
4966   atom_tfra_init (tfra, track_ID);
4967   return tfra;
4968
4969 }
4970
4971 static inline gint
4972 need_bytes (guint32 num)
4973 {
4974   gint n = 0;
4975
4976   while (num >>= 8)
4977     n++;
4978
4979   return n;
4980 }
4981
4982 void
4983 atom_tfra_add_entry (AtomTFRA * tfra, guint64 dts, guint32 sample_num)
4984 {
4985   TFRAEntry entry;
4986
4987   entry.time = dts;
4988   /* fill in later */
4989   entry.moof_offset = 0;
4990   /* always write a single trun in a single traf */
4991   entry.traf_number = 1;
4992   entry.trun_number = 1;
4993   entry.sample_number = sample_num;
4994
4995   /* auto-use 64 bits if needed */
4996   if (dts > G_MAXUINT32)
4997     tfra->header.version = 1;
4998
4999   /* 1 byte will always do for traf and trun number,
5000    * check how much sample_num needs */
5001   tfra->lengths = (tfra->lengths & 0xfc) ||
5002       MAX (tfra->lengths, need_bytes (sample_num));
5003
5004   atom_array_append (&tfra->entries, entry, 256);
5005 }
5006
5007 void
5008 atom_tfra_update_offset (AtomTFRA * tfra, guint64 offset)
5009 {
5010   gint i;
5011
5012   /* auto-use 64 bits if needed */
5013   if (offset > G_MAXUINT32)
5014     tfra->header.version = 1;
5015
5016   for (i = atom_array_get_len (&tfra->entries) - 1; i >= 0; i--) {
5017     TFRAEntry *entry = &atom_array_index (&tfra->entries, i);
5018
5019     if (entry->moof_offset)
5020       break;
5021     entry->moof_offset = offset;
5022   }
5023 }
5024
5025 static guint64
5026 atom_tfra_copy_data (AtomTFRA * tfra, guint8 ** buffer, guint64 * size,
5027     guint64 * offset)
5028 {
5029   guint64 original_offset = *offset;
5030   guint32 i;
5031   TFRAEntry *entry;
5032   guint32 data;
5033   guint bytes;
5034   guint version;
5035
5036   if (!atom_full_copy_data (&tfra->header, buffer, size, offset)) {
5037     return 0;
5038   }
5039
5040   prop_copy_uint32 (tfra->track_ID, buffer, size, offset);
5041   prop_copy_uint32 (tfra->lengths, buffer, size, offset);
5042   prop_copy_uint32 (atom_array_get_len (&tfra->entries), buffer, size, offset);
5043
5044   version = tfra->header.version;
5045   for (i = 0; i < atom_array_get_len (&tfra->entries); ++i) {
5046     entry = &atom_array_index (&tfra->entries, i);
5047     if (version) {
5048       prop_copy_uint64 (entry->time, buffer, size, offset);
5049       prop_copy_uint64 (entry->moof_offset, buffer, size, offset);
5050     } else {
5051       prop_copy_uint32 (entry->time, buffer, size, offset);
5052       prop_copy_uint32 (entry->moof_offset, buffer, size, offset);
5053     }
5054
5055     bytes = (tfra->lengths & (0x3 << 4)) + 1;
5056     data = GUINT32_TO_BE (entry->traf_number);
5057     prop_copy_fixed_size_string (((guint8 *) & data) + 4 - bytes, bytes,
5058         buffer, size, offset);
5059
5060     bytes = (tfra->lengths & (0x3 << 2)) + 1;
5061     data = GUINT32_TO_BE (entry->trun_number);
5062     prop_copy_fixed_size_string (((guint8 *) & data) + 4 - bytes, bytes,
5063         buffer, size, offset);
5064
5065     bytes = (tfra->lengths & (0x3)) + 1;
5066     data = GUINT32_TO_BE (entry->sample_number);
5067     prop_copy_fixed_size_string (((guint8 *) & data) + 4 - bytes, bytes,
5068         buffer, size, offset);
5069
5070   }
5071
5072   atom_write_size (buffer, size, offset, original_offset);
5073   return *offset - original_offset;
5074 }
5075
5076 static guint64
5077 atom_mfro_copy_data (guint32 s, guint8 ** buffer, guint64 * size,
5078     guint64 * offset)
5079 {
5080   guint64 original_offset = *offset;
5081   guint8 flags[3] = { 0, 0, 0 };
5082   AtomFull mfro;
5083
5084   atom_full_init (&mfro, FOURCC_mfro, 0, 0, 0, flags);
5085
5086   if (!atom_full_copy_data (&mfro, buffer, size, offset)) {
5087     return 0;
5088   }
5089
5090   prop_copy_uint32 (s, buffer, size, offset);
5091
5092   atom_write_size (buffer, size, offset, original_offset);
5093
5094   return *offset - original_offset;
5095 }
5096
5097
5098 guint64
5099 atom_mfra_copy_data (AtomMFRA * mfra, guint8 ** buffer, guint64 * size,
5100     guint64 * offset)
5101 {
5102   guint64 original_offset = *offset;
5103   GList *walker;
5104
5105   if (!atom_copy_data (&mfra->header, buffer, size, offset))
5106     return 0;
5107
5108   walker = g_list_first (mfra->tfras);
5109   while (walker != NULL) {
5110     if (!atom_tfra_copy_data ((AtomTFRA *) walker->data, buffer, size, offset)) {
5111       return 0;
5112     }
5113     walker = g_list_next (walker);
5114   }
5115
5116   /* 16 is the size of the mfro atom */
5117   if (!atom_mfro_copy_data (*offset - original_offset + 16, buffer,
5118           size, offset))
5119     return 0;
5120
5121   atom_write_size (buffer, size, offset, original_offset);
5122   return *offset - original_offset;
5123 }
5124
5125 /* some sample description construction helpers */
5126
5127 AtomInfo *
5128 build_esds_extension (AtomTRAK * trak, guint8 object_type, guint8 stream_type,
5129     const GstBuffer * codec_data, guint32 avg_bitrate, guint32 max_bitrate)
5130 {
5131   guint32 track_id;
5132   AtomESDS *esds;
5133
5134   track_id = trak->tkhd.track_ID;
5135
5136   esds = atom_esds_new ();
5137   esds->es.id = track_id & 0xFFFF;
5138   esds->es.dec_conf_desc.object_type = object_type;
5139   esds->es.dec_conf_desc.stream_type = stream_type << 2 | 0x01;
5140
5141   if (avg_bitrate > 0)
5142     esds->es.dec_conf_desc.avg_bitrate = avg_bitrate;
5143   if (max_bitrate > 0)
5144     esds->es.dec_conf_desc.max_bitrate = max_bitrate;
5145
5146   /* optional DecoderSpecificInfo */
5147   if (codec_data) {
5148     DecoderSpecificInfoDescriptor *desc;
5149     gsize size;
5150
5151     esds->es.dec_conf_desc.dec_specific_info = desc =
5152         desc_dec_specific_info_new ();
5153     size = gst_buffer_get_size ((GstBuffer *) codec_data);
5154     desc_dec_specific_info_alloc_data (desc, size);
5155     gst_buffer_extract ((GstBuffer *) codec_data, 0, desc->data, size);
5156   }
5157
5158   return build_atom_info_wrapper ((Atom *) esds, atom_esds_copy_data,
5159       atom_esds_free);
5160 }
5161
5162 AtomInfo *
5163 build_btrt_extension (guint32 buffer_size_db, guint32 avg_bitrate,
5164     guint32 max_bitrate)
5165 {
5166   AtomData *atom_data = atom_data_new (FOURCC_btrt);
5167   guint8 *data;
5168
5169   atom_data_alloc_mem (atom_data, 12);
5170   data = atom_data->data;
5171
5172   GST_WRITE_UINT32_BE (data, buffer_size_db);
5173   GST_WRITE_UINT32_BE (data + 4, max_bitrate);
5174   GST_WRITE_UINT32_BE (data + 8, avg_bitrate);
5175
5176   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
5177       atom_data_free);
5178 }
5179
5180 static AtomInfo *
5181 build_mov_wave_extension (guint32 fourcc, AtomInfo * atom1, AtomInfo * atom2,
5182     gboolean terminator)
5183 {
5184   AtomWAVE *wave;
5185   AtomFRMA *frma;
5186   Atom *ext_atom;
5187
5188   /* Build WAVE atom for sample table entry */
5189   wave = atom_wave_new ();
5190
5191   /* Prepend Terminator atom to the WAVE list first, so it ends up last */
5192   if (terminator) {
5193     ext_atom = (Atom *) atom_data_new (FOURCC_null);
5194     wave->extension_atoms =
5195         atom_info_list_prepend_atom (wave->extension_atoms, (Atom *) ext_atom,
5196         (AtomCopyDataFunc) atom_data_copy_data, (AtomFreeFunc) atom_data_free);
5197   }
5198
5199   /* Add supplied atoms to WAVE */
5200   if (atom2)
5201     wave->extension_atoms = g_list_prepend (wave->extension_atoms, atom2);
5202   if (atom1)
5203     wave->extension_atoms = g_list_prepend (wave->extension_atoms, atom1);
5204
5205   /* Add FRMA to the WAVE */
5206   frma = atom_frma_new ();
5207   frma->media_type = fourcc;
5208
5209   wave->extension_atoms =
5210       atom_info_list_prepend_atom (wave->extension_atoms, (Atom *) frma,
5211       (AtomCopyDataFunc) atom_frma_copy_data, (AtomFreeFunc) atom_frma_free);
5212
5213   return build_atom_info_wrapper ((Atom *) wave, atom_wave_copy_data,
5214       atom_wave_free);
5215 }
5216
5217 AtomInfo *
5218 build_mov_aac_extension (AtomTRAK * trak, const GstBuffer * codec_data,
5219     guint32 avg_bitrate, guint32 max_bitrate)
5220 {
5221   AtomInfo *esds, *mp4a;
5222   GstBuffer *buf;
5223   guint32 tmp = 0;
5224
5225   /* Add ESDS atom to WAVE */
5226   esds = build_esds_extension (trak, ESDS_OBJECT_TYPE_MPEG4_P3,
5227       ESDS_STREAM_TYPE_AUDIO, codec_data, avg_bitrate, max_bitrate);
5228
5229   /* Add MP4A atom to the WAVE:
5230    * not really in spec, but makes offset based players happy */
5231   buf = GST_BUFFER_NEW_READONLY (&tmp, 4);
5232   mp4a = build_codec_data_extension (FOURCC_mp4a, buf);
5233   gst_buffer_unref (buf);
5234
5235   return build_mov_wave_extension (FOURCC_mp4a, mp4a, esds, TRUE);
5236 }
5237
5238 AtomInfo *
5239 build_mov_alac_extension (const GstBuffer * codec_data)
5240 {
5241   AtomInfo *alac;
5242
5243   alac = build_codec_data_extension (FOURCC_alac, codec_data);
5244
5245   return build_mov_wave_extension (FOURCC_alac, NULL, alac, TRUE);
5246 }
5247
5248 AtomInfo *
5249 build_jp2x_extension (const GstBuffer * prefix)
5250 {
5251   AtomData *atom_data;
5252
5253   if (!prefix) {
5254     return NULL;
5255   }
5256
5257   atom_data = atom_data_new_from_gst_buffer (FOURCC_jp2x, prefix);
5258
5259   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
5260       atom_data_free);
5261 }
5262
5263 AtomInfo *
5264 build_jp2h_extension (gint width, gint height, const gchar * colorspace,
5265     gint ncomp, const GValue * cmap_array, const GValue * cdef_array)
5266 {
5267   AtomData *atom_data;
5268   GstBuffer *buf;
5269   guint8 cenum;
5270   gint i;
5271   gint idhr_size = 22;
5272   gint colr_size = 15;
5273   gint cmap_size = 0, cdef_size = 0;
5274   gint cmap_array_size = 0;
5275   gint cdef_array_size = 0;
5276   GstByteWriter writer;
5277
5278   g_return_val_if_fail (cmap_array == NULL ||
5279       GST_VALUE_HOLDS_ARRAY (cmap_array), NULL);
5280   g_return_val_if_fail (cdef_array == NULL ||
5281       GST_VALUE_HOLDS_ARRAY (cdef_array), NULL);
5282
5283   if (g_str_equal (colorspace, "sRGB")) {
5284     cenum = 0x10;
5285     if (ncomp == 0)
5286       ncomp = 3;
5287   } else if (g_str_equal (colorspace, "GRAY")) {
5288     cenum = 0x11;
5289     if (ncomp == 0)
5290       ncomp = 1;
5291   } else if (g_str_equal (colorspace, "sYUV")) {
5292     cenum = 0x12;
5293     if (ncomp == 0)
5294       ncomp = 3;
5295   } else
5296     return NULL;
5297
5298   if (cmap_array) {
5299     cmap_array_size = gst_value_array_get_size (cmap_array);
5300     cmap_size = 8 + cmap_array_size * 4;
5301   }
5302   if (cdef_array) {
5303     cdef_array_size = gst_value_array_get_size (cdef_array);
5304     cdef_size = 8 + 2 + cdef_array_size * 6;
5305   }
5306
5307   gst_byte_writer_init_with_size (&writer,
5308       idhr_size + colr_size + cmap_size + cdef_size, TRUE);
5309
5310   /* ihdr = image header box */
5311   gst_byte_writer_put_uint32_be_unchecked (&writer, 22);
5312   gst_byte_writer_put_uint32_le_unchecked (&writer, FOURCC_ihdr);
5313   gst_byte_writer_put_uint32_be_unchecked (&writer, height);
5314   gst_byte_writer_put_uint32_be_unchecked (&writer, width);
5315   gst_byte_writer_put_uint16_be_unchecked (&writer, ncomp);
5316   /* 8 bits per component, unsigned */
5317   gst_byte_writer_put_uint8_unchecked (&writer, 0x7);
5318   /* compression type; reserved */
5319   gst_byte_writer_put_uint8_unchecked (&writer, 0x7);
5320   /* colour space (un)known */
5321   gst_byte_writer_put_uint8_unchecked (&writer, 0x0);
5322   /* intellectual property right (box present) */
5323   gst_byte_writer_put_uint8_unchecked (&writer, 0x0);
5324
5325   /* colour specification box */
5326   gst_byte_writer_put_uint32_be_unchecked (&writer, 15);
5327   gst_byte_writer_put_uint32_le_unchecked (&writer, FOURCC_colr);
5328
5329   /* specification method: enumerated */
5330   gst_byte_writer_put_uint8_unchecked (&writer, 0x1);
5331   /* precedence; reserved */
5332   gst_byte_writer_put_uint8_unchecked (&writer, 0x0);
5333   /* approximation; reserved */
5334   gst_byte_writer_put_uint8_unchecked (&writer, 0x0);
5335   /* enumerated colourspace */
5336   gst_byte_writer_put_uint32_be_unchecked (&writer, cenum);
5337
5338   if (cmap_array) {
5339     gst_byte_writer_put_uint32_be_unchecked (&writer, cmap_size);
5340     gst_byte_writer_put_uint32_le_unchecked (&writer, FOURCC_cmap);
5341     for (i = 0; i < cmap_array_size; i++) {
5342       const GValue *item;
5343       gint value;
5344       guint16 cmp;
5345       guint8 mtyp;
5346       guint8 pcol;
5347       item = gst_value_array_get_value (cmap_array, i);
5348       value = g_value_get_int (item);
5349
5350       /* value is '(mtyp << 24) | (pcol << 16) | cmp' */
5351       cmp = value & 0xFFFF;
5352       mtyp = value >> 24;
5353       pcol = (value >> 16) & 0xFF;
5354
5355       if (mtyp == 1)
5356         GST_WARNING ("MTYP of cmap atom signals Pallete Mapping, but we don't "
5357             "handle Pallete mapping atoms yet");
5358
5359       gst_byte_writer_put_uint16_be_unchecked (&writer, cmp);
5360       gst_byte_writer_put_uint8_unchecked (&writer, mtyp);
5361       gst_byte_writer_put_uint8_unchecked (&writer, pcol);
5362     }
5363   }
5364
5365   if (cdef_array) {
5366     gst_byte_writer_put_uint32_be_unchecked (&writer, cdef_size);
5367     gst_byte_writer_put_uint32_le_unchecked (&writer, FOURCC_cdef);
5368     gst_byte_writer_put_uint16_be_unchecked (&writer, cdef_array_size);
5369     for (i = 0; i < cdef_array_size; i++) {
5370       const GValue *item;
5371       gint value;
5372       item = gst_value_array_get_value (cdef_array, i);
5373       value = g_value_get_int (item);
5374
5375       gst_byte_writer_put_uint16_be_unchecked (&writer, i);
5376       if (value > 0) {
5377         gst_byte_writer_put_uint16_be_unchecked (&writer, 0);
5378         gst_byte_writer_put_uint16_be_unchecked (&writer, value);
5379       } else if (value < 0) {
5380         gst_byte_writer_put_uint16_be_unchecked (&writer, -value);
5381         gst_byte_writer_put_uint16_be_unchecked (&writer, 0);   /* TODO what here? */
5382       } else {
5383         gst_byte_writer_put_uint16_be_unchecked (&writer, 1);
5384         gst_byte_writer_put_uint16_be_unchecked (&writer, 0);
5385       }
5386     }
5387   }
5388
5389   g_assert (gst_byte_writer_get_remaining (&writer) == 0);
5390   buf = gst_byte_writer_reset_and_get_buffer (&writer);
5391
5392   atom_data = atom_data_new_from_gst_buffer (FOURCC_jp2h, buf);
5393   gst_buffer_unref (buf);
5394
5395   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
5396       atom_data_free);
5397 }
5398
5399 AtomInfo *
5400 build_codec_data_extension (guint32 fourcc, const GstBuffer * codec_data)
5401 {
5402   AtomData *data;
5403   AtomInfo *result = NULL;
5404
5405   if (codec_data) {
5406     data = atom_data_new_from_gst_buffer (fourcc, codec_data);
5407     result = build_atom_info_wrapper ((Atom *) data, atom_data_copy_data,
5408         atom_data_free);
5409   }
5410
5411   return result;
5412 }
5413
5414 AtomInfo *
5415 build_amr_extension (void)
5416 {
5417   guint8 ext[9];
5418   GstBuffer *buf;
5419   AtomInfo *res;
5420
5421   /* vendor */
5422   GST_WRITE_UINT32_LE (ext, 0);
5423   /* decoder version */
5424   GST_WRITE_UINT8 (ext + 4, 0);
5425   /* mode set (all modes) */
5426   GST_WRITE_UINT16_BE (ext + 5, 0x81FF);
5427   /* mode change period (no restriction) */
5428   GST_WRITE_UINT8 (ext + 7, 0);
5429   /* frames per sample */
5430   GST_WRITE_UINT8 (ext + 8, 1);
5431
5432   buf = GST_BUFFER_NEW_READONLY (ext, sizeof (ext));
5433   res = build_codec_data_extension (FOURCC_damr, buf);
5434   gst_buffer_unref (buf);
5435   return res;
5436 }
5437
5438 AtomInfo *
5439 build_h263_extension (void)
5440 {
5441   guint8 ext[7];
5442   GstBuffer *buf;
5443   AtomInfo *res;
5444
5445   /* vendor */
5446   GST_WRITE_UINT32_LE (ext, 0);
5447   /* decoder version */
5448   GST_WRITE_UINT8 (ext + 4, 0);
5449   /* level / profile */
5450   /* FIXME ? maybe ? obtain somewhere; baseline for now */
5451   GST_WRITE_UINT8 (ext + 5, 10);
5452   GST_WRITE_UINT8 (ext + 6, 0);
5453
5454   buf = GST_BUFFER_NEW_READONLY (ext, sizeof (ext));
5455   res = build_codec_data_extension (FOURCC_d263, buf);
5456   gst_buffer_unref (buf);
5457   return res;
5458 }
5459
5460 AtomInfo *
5461 build_gama_atom (gdouble gamma)
5462 {
5463   AtomInfo *res;
5464   guint32 gamma_fp;
5465   GstBuffer *buf;
5466
5467   /* convert to uint32 from fixed point */
5468   gamma_fp = (guint32) 65536 *gamma;
5469
5470   gamma_fp = GUINT32_TO_BE (gamma_fp);
5471   buf = GST_BUFFER_NEW_READONLY (&gamma_fp, 4);
5472   res = build_codec_data_extension (FOURCC_gama, buf);
5473   gst_buffer_unref (buf);
5474   return res;
5475 }
5476
5477 AtomInfo *
5478 build_SMI_atom (const GstBuffer * seqh)
5479 {
5480   AtomInfo *res;
5481   GstBuffer *buf;
5482   gsize size;
5483   guint8 *data;
5484
5485   /* the seqh plus its size and fourcc */
5486   size = gst_buffer_get_size ((GstBuffer *) seqh);
5487   data = g_malloc (size + 8);
5488
5489   GST_WRITE_UINT32_LE (data, FOURCC_SEQH);
5490   GST_WRITE_UINT32_BE (data + 4, size + 8);
5491   gst_buffer_extract ((GstBuffer *) seqh, 0, data + 8, size);
5492   buf = gst_buffer_new_wrapped (data, size + 8);
5493   res = build_codec_data_extension (FOURCC_SMI_, buf);
5494   gst_buffer_unref (buf);
5495   return res;
5496 }
5497
5498 static AtomInfo *
5499 build_ima_adpcm_atom (gint channels, gint rate, gint blocksize)
5500 {
5501 #define IMA_ADPCM_ATOM_SIZE 20
5502   AtomData *atom_data;
5503   guint8 *data;
5504   guint32 fourcc;
5505   gint samplesperblock;
5506   gint bytespersec;
5507
5508   /* The FOURCC for WAV codecs in QT is 'ms' followed by the 16 bit wave codec
5509      identifier. Note that the identifier here is big-endian, but when used
5510      within the WAVE header (below), it's little endian. */
5511   fourcc = MS_WAVE_FOURCC (0x11);
5512
5513   atom_data = atom_data_new (fourcc);
5514   atom_data_alloc_mem (atom_data, IMA_ADPCM_ATOM_SIZE);
5515   data = atom_data->data;
5516
5517   /* This atom's content is a WAVE header, including 2 bytes of extra data.
5518      Note that all of this is little-endian, unlike most stuff in qt. */
5519   /* 4 bytes header per channel (including 1 sample). Then 2 samples per byte
5520      for the rest. Simplifies to this. */
5521   samplesperblock = 2 * blocksize / channels - 7;
5522   bytespersec = rate * blocksize / samplesperblock;
5523   GST_WRITE_UINT16_LE (data, 0x11);
5524   GST_WRITE_UINT16_LE (data + 2, channels);
5525   GST_WRITE_UINT32_LE (data + 4, rate);
5526   GST_WRITE_UINT32_LE (data + 8, bytespersec);
5527   GST_WRITE_UINT16_LE (data + 12, blocksize);
5528   GST_WRITE_UINT16_LE (data + 14, 4);
5529   GST_WRITE_UINT16_LE (data + 16, 2);   /* Two extra bytes */
5530   GST_WRITE_UINT16_LE (data + 18, samplesperblock);
5531
5532   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
5533       atom_data_free);
5534 }
5535
5536 AtomInfo *
5537 build_ima_adpcm_extension (gint channels, gint rate, gint blocksize)
5538 {
5539   AtomWAVE *wave;
5540   AtomFRMA *frma;
5541   Atom *ext_atom;
5542
5543   /* Add WAVE atom */
5544   wave = atom_wave_new ();
5545
5546   /* Prepend Terminator atom to the WAVE list first, so it ends up last */
5547   ext_atom = (Atom *) atom_data_new (FOURCC_null);
5548   wave->extension_atoms =
5549       atom_info_list_prepend_atom (wave->extension_atoms, (Atom *) ext_atom,
5550       (AtomCopyDataFunc) atom_data_copy_data, (AtomFreeFunc) atom_data_free);
5551
5552   /* Add wave ima adpcm atom to WAVE */
5553   wave->extension_atoms = g_list_prepend (wave->extension_atoms,
5554       build_ima_adpcm_atom (channels, rate, blocksize));
5555
5556   /* Add FRMA to the WAVE */
5557   frma = atom_frma_new ();
5558   frma->media_type = MS_WAVE_FOURCC (0x11);
5559
5560   wave->extension_atoms =
5561       atom_info_list_prepend_atom (wave->extension_atoms, (Atom *) frma,
5562       (AtomCopyDataFunc) atom_frma_copy_data, (AtomFreeFunc) atom_frma_free);
5563
5564   return build_atom_info_wrapper ((Atom *) wave, atom_wave_copy_data,
5565       atom_wave_free);
5566 }
5567
5568 AtomInfo *
5569 build_ac3_extension (guint8 fscod, guint8 bsid, guint8 bsmod, guint8 acmod,
5570     guint8 lfe_on, guint8 bitrate_code)
5571 {
5572   AtomData *atom_data = atom_data_new (FOURCC_dac3);
5573   guint8 *data;
5574
5575   atom_data_alloc_mem (atom_data, 3);
5576   data = atom_data->data;
5577
5578   /* Bits from the spec
5579    * fscod 2
5580    * bsid  5
5581    * bsmod 3
5582    * acmod 3
5583    * lfeon 1
5584    * bit_rate_code 5
5585    * reserved 5
5586    */
5587
5588   /* Some bit manipulation magic. Need bitwriter */
5589   data[0] = (fscod << 6) | (bsid << 1) | ((bsmod >> 2) & 1);
5590   data[1] =
5591       ((bsmod & 0x3) << 6) | (acmod << 3) | ((lfe_on & 1) << 2) | ((bitrate_code
5592           >> 3) & 0x3);
5593   data[2] = ((bitrate_code & 0x7) << 5);
5594
5595   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
5596       atom_data_free);
5597 }
5598
5599 AtomInfo *
5600 build_opus_extension (guint32 rate, guint8 channels, guint8 mapping_family,
5601     guint8 stream_count, guint8 coupled_count, guint8 channel_mapping[256],
5602     guint16 pre_skip, guint16 output_gain)
5603 {
5604   AtomData *atom_data;
5605   guint8 *data_block;
5606   GstByteWriter bw;
5607   gboolean hdl = TRUE;
5608   guint data_block_len;
5609
5610   gst_byte_writer_init (&bw);
5611   hdl &= gst_byte_writer_put_uint8 (&bw, 0x00); /* version number */
5612   hdl &= gst_byte_writer_put_uint8 (&bw, channels);
5613   hdl &= gst_byte_writer_put_uint16_le (&bw, pre_skip);
5614   hdl &= gst_byte_writer_put_uint32_le (&bw, rate);
5615   hdl &= gst_byte_writer_put_uint16_le (&bw, output_gain);
5616   hdl &= gst_byte_writer_put_uint8 (&bw, mapping_family);
5617   if (mapping_family > 0) {
5618     hdl &= gst_byte_writer_put_uint8 (&bw, stream_count);
5619     hdl &= gst_byte_writer_put_uint8 (&bw, coupled_count);
5620     hdl &= gst_byte_writer_put_data (&bw, channel_mapping, channels);
5621   }
5622
5623   if (!hdl) {
5624     GST_WARNING ("Error creating header");
5625     return NULL;
5626   }
5627
5628   data_block_len = gst_byte_writer_get_size (&bw);
5629   data_block = gst_byte_writer_reset_and_get_data (&bw);
5630   atom_data = atom_data_new_from_data (FOURCC_dops, data_block, data_block_len);
5631   g_free (data_block);
5632
5633   return build_atom_info_wrapper ((Atom *) atom_data, atom_data_copy_data,
5634       atom_data_free);
5635 }
5636
5637 AtomInfo *
5638 build_uuid_xmp_atom (GstBuffer * xmp_data)
5639 {
5640   AtomUUID *uuid;
5641   gsize size;
5642   static const guint8 xmp_uuid[] = { 0xBE, 0x7A, 0xCF, 0xCB,
5643     0x97, 0xA9, 0x42, 0xE8,
5644     0x9C, 0x71, 0x99, 0x94,
5645     0x91, 0xE3, 0xAF, 0xAC
5646   };
5647
5648   if (xmp_data == NULL)
5649     return NULL;
5650
5651   uuid = atom_uuid_new ();
5652   memcpy (uuid->uuid, xmp_uuid, 16);
5653
5654   size = gst_buffer_get_size (xmp_data);
5655   uuid->data = g_malloc (size);
5656   uuid->datalen = size;
5657   gst_buffer_extract (xmp_data, 0, uuid->data, size);
5658
5659   return build_atom_info_wrapper ((Atom *) uuid, atom_uuid_copy_data,
5660       atom_uuid_free);
5661 }