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