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