]> git.sesse.net Git - vlc/blob - modules/mux/mp4.c
mux: mp4: handle box/bo failed alloc/realloc
[vlc] / modules / mux / mp4.c
1 /*****************************************************************************
2  * mp4.c: mp4/mov muxer
3  *****************************************************************************
4  * Copyright (C) 2001, 2002, 2003, 2006 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin at videolan dot org>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_sout.h>
36 #include <vlc_block.h>
37
38 #include <vlc_bits.h>
39
40 #include <time.h>
41
42 #include <vlc_iso_lang.h>
43 #include <vlc_meta.h>
44
45 #include "../demux/mpeg/mpeg_parser_helpers.h"
46 #include "../demux/mp4/libmp4.h"
47
48 #include "assert.h"
49 /*****************************************************************************
50  * Module descriptor
51  *****************************************************************************/
52 #define FASTSTART_TEXT N_("Create \"Fast Start\" files")
53 #define FASTSTART_LONGTEXT N_(\
54     "Create \"Fast Start\" files. " \
55     "\"Fast Start\" files are optimized for downloads and allow the user " \
56     "to start previewing the file while it is downloading.")
57
58 static int  Open   (vlc_object_t *);
59 static void Close  (vlc_object_t *);
60 static int  OpenFrag   (vlc_object_t *);
61 static void CloseFrag  (vlc_object_t *);
62
63 #define SOUT_CFG_PREFIX "sout-mp4-"
64
65 vlc_module_begin ()
66     set_description(N_("MP4/MOV muxer"))
67     set_category(CAT_SOUT)
68     set_subcategory(SUBCAT_SOUT_MUX)
69     set_shortname("MP4")
70
71     add_bool(SOUT_CFG_PREFIX "faststart", true,
72               FASTSTART_TEXT, FASTSTART_LONGTEXT,
73               true)
74     set_capability("sout mux", 5)
75     add_shortcut("mp4", "mov", "3gp")
76     set_callbacks(Open, Close)
77
78 add_submodule ()
79     set_description(N_("Fragmented and streamable MP4 muxer"))
80     set_category(CAT_SOUT)
81     set_subcategory(SUBCAT_SOUT_MUX)
82     set_shortname("MP4 Frag")
83     add_shortcut("mp4frag", "mp4stream")
84     set_capability("sout mux", 0)
85     set_callbacks(OpenFrag, CloseFrag)
86
87 vlc_module_end ()
88
89 /*****************************************************************************
90  * Exported prototypes
91  *****************************************************************************/
92 static const char *const ppsz_sout_options[] = {
93     "faststart", NULL
94 };
95
96 static int Control(sout_mux_t *, int, va_list);
97 static int AddStream(sout_mux_t *, sout_input_t *);
98 static void DelStream(sout_mux_t *, sout_input_t *);
99 static int Mux      (sout_mux_t *);
100 static int MuxFrag  (sout_mux_t *);
101
102 /*****************************************************************************
103  * Local prototypes
104  *****************************************************************************/
105 typedef struct
106 {
107     uint64_t i_pos;
108     int      i_size;
109
110     mtime_t  i_pts_dts;
111     mtime_t  i_length;
112     unsigned int i_flags;
113 } mp4_entry_t;
114
115 typedef struct mp4_fragentry_t mp4_fragentry_t;
116
117 struct mp4_fragentry_t
118 {
119     block_t  *p_block;
120     uint32_t  i_run;
121     mp4_fragentry_t *p_next;
122 };
123
124 typedef struct mp4_fragindex_t
125 {
126     uint64_t i_moofoffset;
127     mtime_t  i_time;
128     uint8_t  i_traf;
129     uint8_t  i_trun;
130     uint32_t i_sample;
131 } mp4_fragindex_t;
132
133 typedef struct mp4_fragqueue_t
134 {
135     mp4_fragentry_t *p_first;
136     mp4_fragentry_t *p_last;
137 } mp4_fragqueue_t;
138
139 typedef struct
140 {
141     es_format_t   fmt;
142     unsigned int  i_track_id;
143
144     /* index */
145     unsigned int i_entry_count;
146     unsigned int i_entry_max;
147     mp4_entry_t  *entry;
148     int64_t      i_length_neg;
149
150     /* stats */
151     int64_t      i_dts_start; /* applies to current segment only */
152     int64_t      i_read_duration;
153     uint32_t     i_timescale;
154     mtime_t      i_starttime; /* the really first packet */
155     bool         b_hasbframes;
156
157     /* XXX: needed for other codecs too, see lavf */
158     block_t      *a52_frame;
159
160     /* for later stco fix-up (fast start files) */
161     uint64_t i_stco_pos;
162     bool b_stco64;
163
164     /* for spu */
165     int64_t i_last_dts; /* applies to current segment only */
166     int64_t i_last_length;
167
168     /*** mp4frag ***/
169     bool         b_hasiframes;
170     uint32_t     i_trex_length;
171     uint32_t     i_trex_size;
172     uint32_t     i_tfhd_flags;
173
174     uint32_t         i_current_run;
175     mp4_fragentry_t *p_held_entry;
176     mp4_fragqueue_t  read;
177     mp4_fragqueue_t  towrite;
178     mtime_t          i_last_iframe_time;
179     mtime_t          i_written_duration;
180     mp4_fragindex_t *p_indexentries;
181     uint32_t         i_indexentriesmax;
182     uint32_t         i_indexentries;
183 } mp4_stream_t;
184
185 struct sout_mux_sys_t
186 {
187     bool b_mov;
188     bool b_3gp;
189     bool b_64_ext;
190     bool b_fast_start;
191
192     uint64_t i_mdat_pos;
193     uint64_t i_pos;
194     mtime_t  i_read_duration;
195
196     unsigned int   i_nb_streams;
197     mp4_stream_t **pp_streams;
198
199     /* mp4frag */
200     bool           b_fragmented;
201     bool           b_header_sent;
202     mtime_t        i_written_duration;
203     uint32_t       i_mfhd_sequence;
204 };
205
206 static bo_t *box_new     (const char *fcc);
207 static bo_t *box_full_new(const char *fcc, uint8_t v, uint32_t f);
208 static void  box_fix     (bo_t *box, uint32_t);
209 static void  box_gather  (bo_t *box, bo_t *box2);
210
211 static inline void bo_add_mp4_tag_descr(bo_t *box, uint8_t tag, uint32_t size)
212 {
213     bo_add_8(box, tag);
214     for (int i = 3; i>0; i--)
215         bo_add_8(box, (size>>(7*i)) | 0x80);
216     bo_add_8(box, size & 0x7F);
217 }
218
219 static void box_send(sout_mux_t *p_mux,  bo_t *box);
220
221 static bo_t *GetMoovBox(sout_mux_t *p_mux);
222
223 static block_t *ConvertSUBT(block_t *);
224 static block_t *ConvertFromAnnexB(block_t *);
225
226 static const char avc1_short_start_code[3] = { 0, 0, 1 };
227 static const char avc1_start_code[4] = { 0, 0, 0, 1 };
228
229 /*****************************************************************************
230  * Open:
231  *****************************************************************************/
232 static int Open(vlc_object_t *p_this)
233 {
234     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
235     sout_mux_sys_t  *p_sys;
236     bo_t            *box;
237
238     msg_Dbg(p_mux, "Mp4 muxer opened");
239     config_ChainParse(p_mux, SOUT_CFG_PREFIX, ppsz_sout_options, p_mux->p_cfg);
240
241     p_mux->pf_control   = Control;
242     p_mux->pf_addstream = AddStream;
243     p_mux->pf_delstream = DelStream;
244     p_mux->pf_mux       = Mux;
245     p_mux->p_sys        = p_sys = malloc(sizeof(sout_mux_sys_t));
246     if (!p_sys)
247         return VLC_ENOMEM;
248     p_sys->i_pos        = 0;
249     p_sys->i_nb_streams = 0;
250     p_sys->pp_streams   = NULL;
251     p_sys->i_mdat_pos   = 0;
252     p_sys->b_mov        = p_mux->psz_mux && !strcmp(p_mux->psz_mux, "mov");
253     p_sys->b_3gp        = p_mux->psz_mux && !strcmp(p_mux->psz_mux, "3gp");
254     p_sys->i_read_duration   = 0;
255     p_sys->b_fragmented = false;
256
257     if (!p_sys->b_mov) {
258         /* Now add ftyp header */
259         box = box_new("ftyp");
260         if(!box)
261         {
262             free(p_sys);
263             return VLC_ENOMEM;
264         }
265         if (p_sys->b_3gp)
266             bo_add_fourcc(box, "3gp6");
267         else
268             bo_add_fourcc(box, "isom");
269         bo_add_32be  (box, 0);
270         if (p_sys->b_3gp)
271             bo_add_fourcc(box, "3gp4");
272         else
273             bo_add_fourcc(box, "mp41");
274         bo_add_fourcc(box, "avc1");
275         if(box->b)
276         {
277             box_fix(box, box->b->i_buffer);
278             p_sys->i_pos += box->b->i_buffer;
279             p_sys->i_mdat_pos = p_sys->i_pos;
280
281             box_send(p_mux, box);
282         }
283     }
284
285     /* FIXME FIXME
286      * Quicktime actually doesn't like the 64 bits extensions !!! */
287     p_sys->b_64_ext = false;
288
289     /* Now add mdat header */
290     box = box_new("mdat");
291     if(!box)
292     {
293         free(p_sys);
294         return VLC_ENOMEM;
295     }
296     bo_add_64be  (box, 0); // enough to store an extended size
297
298     if(box->b)
299         p_sys->i_pos += box->b->i_buffer;
300
301     box_send(p_mux, box);
302
303     return VLC_SUCCESS;
304 }
305
306 /*****************************************************************************
307  * Close:
308  *****************************************************************************/
309 static void Close(vlc_object_t *p_this)
310 {
311     sout_mux_t      *p_mux = (sout_mux_t*)p_this;
312     sout_mux_sys_t  *p_sys = p_mux->p_sys;
313
314     msg_Dbg(p_mux, "Close");
315
316     /* Update mdat size */
317     bo_t bo;
318     if (!bo_init(&bo, 16))
319         goto cleanup;
320     if (p_sys->i_pos - p_sys->i_mdat_pos >= (((uint64_t)1)<<32)) {
321         /* Extended size */
322         bo_add_32be  (&bo, 1);
323         bo_add_fourcc(&bo, "mdat");
324         bo_add_64be  (&bo, p_sys->i_pos - p_sys->i_mdat_pos);
325     } else {
326         bo_add_32be  (&bo, 8);
327         bo_add_fourcc(&bo, "wide");
328         bo_add_32be  (&bo, p_sys->i_pos - p_sys->i_mdat_pos - 8);
329         bo_add_fourcc(&bo, "mdat");
330     }
331
332     sout_AccessOutSeek(p_mux->p_access, p_sys->i_mdat_pos);
333     sout_AccessOutWrite(p_mux->p_access, bo.b);
334
335     /* Create MOOV header */
336     uint64_t i_moov_pos = p_sys->i_pos;
337     bo_t *moov = GetMoovBox(p_mux);
338
339     /* Check we need to create "fast start" files */
340     p_sys->b_fast_start = var_GetBool(p_this, SOUT_CFG_PREFIX "faststart");
341     while (p_sys->b_fast_start && moov && moov->b) {
342         /* Move data to the end of the file so we can fit the moov header
343          * at the start */
344         int64_t i_size = p_sys->i_pos - p_sys->i_mdat_pos;
345         int i_moov_size = moov->b->i_buffer;
346
347         while (i_size > 0) {
348             int64_t i_chunk = __MIN(32768, i_size);
349             block_t *p_buf = block_Alloc(i_chunk);
350             sout_AccessOutSeek(p_mux->p_access,
351                                 p_sys->i_mdat_pos + i_size - i_chunk);
352             if (sout_AccessOutRead(p_mux->p_access, p_buf) < i_chunk) {
353                 msg_Warn(p_this, "read() not supported by access output, "
354                           "won't create a fast start file");
355                 p_sys->b_fast_start = false;
356                 block_Release(p_buf);
357                 break;
358             }
359             sout_AccessOutSeek(p_mux->p_access, p_sys->i_mdat_pos + i_size +
360                                 i_moov_size - i_chunk);
361             sout_AccessOutWrite(p_mux->p_access, p_buf);
362             i_size -= i_chunk;
363         }
364
365         if (!p_sys->b_fast_start)
366             break;
367
368         /* Update pos pointers */
369         i_moov_pos = p_sys->i_mdat_pos;
370         p_sys->i_mdat_pos += moov->b->i_buffer;
371
372         /* Fix-up samples to chunks table in MOOV header */
373         for (unsigned int i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++) {
374             mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
375             unsigned i_written = 0;
376             for (unsigned i = 0; i < p_stream->i_entry_count; ) {
377                 mp4_entry_t *entry = p_stream->entry;
378                 if (p_stream->b_stco64)
379                     bo_set_64be(moov, p_stream->i_stco_pos + i_written++ * 8, entry[i].i_pos + p_sys->i_mdat_pos - i_moov_pos);
380                 else
381                     bo_set_32be(moov, p_stream->i_stco_pos + i_written++ * 4, entry[i].i_pos + p_sys->i_mdat_pos - i_moov_pos);
382
383                 for (; i < p_stream->i_entry_count; i++)
384                     if (i >= p_stream->i_entry_count - 1 ||
385                         entry[i].i_pos + entry[i].i_size != entry[i+1].i_pos) {
386                         i++;
387                         break;
388                     }
389             }
390         }
391
392         p_sys->b_fast_start = false;
393     }
394
395     /* Write MOOV header */
396     sout_AccessOutSeek(p_mux->p_access, i_moov_pos);
397     box_send(p_mux, moov);
398
399 cleanup:
400     /* Clean-up */
401     for (unsigned int i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++) {
402         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
403
404         es_format_Clean(&p_stream->fmt);
405         if (p_stream->a52_frame)
406             block_Release(p_stream->a52_frame);
407         free(p_stream->entry);
408         free(p_stream);
409     }
410     if (p_sys->i_nb_streams)
411         free(p_sys->pp_streams);
412     free(p_sys);
413 }
414
415 /*****************************************************************************
416  * Control:
417  *****************************************************************************/
418 static int Control(sout_mux_t *p_mux, int i_query, va_list args)
419 {
420     VLC_UNUSED(p_mux);
421     bool *pb_bool;
422
423     switch(i_query)
424     {
425     case MUX_CAN_ADD_STREAM_WHILE_MUXING:
426         pb_bool = (bool*)va_arg(args, bool *);
427         *pb_bool = false;
428         return VLC_SUCCESS;
429
430     case MUX_GET_ADD_STREAM_WAIT:
431         pb_bool = (bool*)va_arg(args, bool *);
432         *pb_bool = true;
433         return VLC_SUCCESS;
434
435     case MUX_GET_MIME:   /* Not needed, as not streamable */
436     default:
437         return VLC_EGENERIC;
438     }
439 }
440
441 /*****************************************************************************
442  * AddStream:
443  *****************************************************************************/
444 static int AddStream(sout_mux_t *p_mux, sout_input_t *p_input)
445 {
446     sout_mux_sys_t  *p_sys = p_mux->p_sys;
447     mp4_stream_t    *p_stream;
448
449     switch(p_input->p_fmt->i_codec)
450     {
451     case VLC_CODEC_A52:
452     case VLC_CODEC_EAC3:
453     case VLC_CODEC_MP4A:
454     case VLC_CODEC_MP4V:
455     case VLC_CODEC_MPGA:
456     case VLC_CODEC_MPGV:
457     case VLC_CODEC_MP2V:
458     case VLC_CODEC_MP1V:
459     case VLC_CODEC_MJPG:
460     case VLC_CODEC_MJPGB:
461     case VLC_CODEC_SVQ1:
462     case VLC_CODEC_SVQ3:
463     case VLC_CODEC_H263:
464     case VLC_CODEC_H264:
465     case VLC_CODEC_HEVC:
466     case VLC_CODEC_AMR_NB:
467     case VLC_CODEC_AMR_WB:
468     case VLC_CODEC_YV12:
469     case VLC_CODEC_YUYV:
470         break;
471     case VLC_CODEC_SUBT:
472         msg_Warn(p_mux, "subtitle track added like in .mov (even when creating .mp4)");
473         break;
474     default:
475         msg_Err(p_mux, "unsupported codec %4.4s in mp4",
476                  (char*)&p_input->p_fmt->i_codec);
477         return VLC_EGENERIC;
478     }
479
480     p_stream = malloc(sizeof(mp4_stream_t));
481     if (!p_stream)
482         return VLC_ENOMEM;
483     es_format_Copy(&p_stream->fmt, p_input->p_fmt);
484     p_stream->i_track_id    = p_sys->i_nb_streams + 1;
485     p_stream->i_length_neg  = 0;
486     p_stream->i_entry_count = 0;
487     p_stream->i_entry_max   = 1000;
488     p_stream->entry         =
489         calloc(p_stream->i_entry_max, sizeof(mp4_entry_t));
490     p_stream->i_dts_start   = 0;
491     p_stream->i_read_duration    = 0;
492     p_stream->a52_frame = NULL;
493     switch( p_stream->fmt.i_cat )
494     {
495     case AUDIO_ES:
496         if(!p_stream->fmt.audio.i_rate)
497         {
498             msg_Warn( p_mux, "no audio rate given for stream %d, assuming 48KHz",
499                       p_sys->i_nb_streams );
500             p_stream->fmt.audio.i_rate = 48000;
501         }
502         p_stream->i_timescale = p_stream->fmt.audio.i_rate;
503         break;
504     case VIDEO_ES:
505         if( !p_stream->fmt.video.i_frame_rate ||
506             !p_stream->fmt.video.i_frame_rate_base )
507         {
508             msg_Warn( p_mux, "Missing frame rate for stream %d, assuming 25fps",
509                       p_sys->i_nb_streams );
510             p_stream->fmt.video.i_frame_rate = 25;
511             p_stream->fmt.video.i_frame_rate_base = 1;
512         }
513         p_stream->i_timescale = p_stream->fmt.video.i_frame_rate * 1000 /
514                                 p_stream->fmt.video.i_frame_rate_base;
515         break;
516     default:
517         p_stream->i_timescale = CLOCK_FREQ;
518         break;
519     }
520
521     p_stream->i_starttime   = p_sys->i_read_duration;
522     p_stream->b_hasbframes  = false;
523
524     p_stream->i_last_dts    = 0;
525     p_stream->i_last_length = 0;
526
527     p_stream->b_hasiframes  = false;
528     p_stream->i_trex_length = 0;
529     p_stream->i_trex_size   = 0;
530
531     p_stream->i_current_run = 0;
532     p_stream->read.p_first  = NULL;
533     p_stream->read.p_last   = NULL;
534     p_stream->towrite.p_first = NULL;
535     p_stream->towrite.p_last  = NULL;
536     p_stream->p_held_entry    = NULL;
537     p_stream->i_last_iframe_time = 0;
538     p_stream->i_written_duration = 0;
539     p_stream->p_indexentries     = NULL;
540     p_stream->i_indexentriesmax  = 0;
541     p_stream->i_indexentries     = 0;
542
543     p_input->p_sys          = p_stream;
544
545     msg_Dbg(p_mux, "adding input");
546
547     TAB_APPEND(p_sys->i_nb_streams, p_sys->pp_streams, p_stream);
548     return VLC_SUCCESS;
549 }
550
551 /*****************************************************************************
552  * DelStream:
553  *****************************************************************************/
554 static void DelStream(sout_mux_t *p_mux, sout_input_t *p_input)
555 {
556     VLC_UNUSED(p_input);
557     msg_Dbg(p_mux, "removing input");
558 }
559
560 /*****************************************************************************
561  * Mux:
562  *****************************************************************************/
563 static int Mux(sout_mux_t *p_mux)
564 {
565     sout_mux_sys_t *p_sys = p_mux->p_sys;
566
567     for (;;) {
568         int i_stream = sout_MuxGetStream(p_mux, 2, NULL);
569         if (i_stream < 0)
570             return(VLC_SUCCESS);
571
572         sout_input_t *p_input  = p_mux->pp_inputs[i_stream];
573         mp4_stream_t *p_stream = (mp4_stream_t*)p_input->p_sys;
574
575         block_t *p_data;
576         do {
577             p_data = block_FifoGet(p_input->p_fifo);
578             if (p_stream->fmt.i_codec == VLC_CODEC_H264 ||
579                 p_stream->fmt.i_codec == VLC_CODEC_HEVC)
580                 p_data = ConvertFromAnnexB(p_data);
581             else if (p_stream->fmt.i_codec == VLC_CODEC_SUBT)
582                 p_data = ConvertSUBT(p_data);
583             else if (p_stream->fmt.i_codec == VLC_CODEC_A52 ||
584                      p_stream->fmt.i_codec == VLC_CODEC_EAC3) {
585                 if (p_stream->a52_frame == NULL && p_data->i_buffer >= 8)
586                     p_stream->a52_frame = block_Duplicate(p_data);
587             }
588         } while (!p_data);
589
590         /* Reset reference dts in case of discontinuity (ex: gather sout) */
591         if ( p_stream->i_entry_count == 0 || p_data->i_flags & BLOCK_FLAG_DISCONTINUITY )
592         {
593             p_stream->i_dts_start = p_data->i_dts;
594             p_stream->i_last_dts = p_data->i_dts;
595             p_stream->i_length_neg = 0;
596         }
597
598         if (p_stream->fmt.i_cat != SPU_ES) {
599             /* Fix length of the sample */
600             if (block_FifoCount(p_input->p_fifo) > 0) {
601                 block_t *p_next = block_FifoShow(p_input->p_fifo);
602                 if ( p_next->i_flags & BLOCK_FLAG_DISCONTINUITY )
603                 { /* we have no way to know real length except by decoding */
604                     if ( p_stream->fmt.i_cat == VIDEO_ES )
605                     {
606                         p_data->i_length = CLOCK_FREQ *
607                                            p_stream->fmt.video.i_frame_rate_base /
608                                            p_stream->fmt.video.i_frame_rate;
609                         msg_Dbg( p_mux, "video track %u fixup to %"PRId64" for sample %u",
610                                  p_stream->i_track_id, p_data->i_length, p_stream->i_entry_count );
611                     }
612                     else if ( p_stream->fmt.i_cat == AUDIO_ES &&
613                               p_stream->fmt.audio.i_rate &&
614                               p_data->i_nb_samples )
615                     {
616                         p_data->i_length = CLOCK_FREQ * p_data->i_nb_samples /
617                                            p_stream->fmt.audio.i_rate;
618                         msg_Dbg( p_mux, "audio track %u fixup to %"PRId64" for sample %u",
619                                  p_stream->i_track_id, p_data->i_length, p_stream->i_entry_count );
620                     }
621                     else if ( p_data->i_length <= 0 )
622                     {
623                         msg_Warn( p_mux, "unknown length for track %u sample %u",
624                                   p_stream->i_track_id, p_stream->i_entry_count );
625                         p_data->i_length = 1;
626                     }
627                 }
628                 else
629                 {
630                     int64_t i_diff  = p_next->i_dts - p_data->i_dts;
631                     if (i_diff < CLOCK_FREQ) /* protection */
632                         p_data->i_length = i_diff;
633                 }
634             }
635             if (p_data->i_length <= 0) {
636                 msg_Warn(p_mux, "i_length <= 0");
637                 p_stream->i_length_neg += p_data->i_length - 1;
638                 p_data->i_length = 1;
639             } else if (p_stream->i_length_neg < 0) {
640                 int64_t i_recover = __MIN(p_data->i_length / 4, - p_stream->i_length_neg);
641
642                 p_data->i_length -= i_recover;
643                 p_stream->i_length_neg += i_recover;
644             }
645         }
646
647         if (p_stream->fmt.i_cat == SPU_ES && p_stream->i_entry_count > 0) {
648             int64_t i_length = p_data->i_dts - p_stream->i_last_dts;
649
650             if (i_length <= 0) /* FIXME handle this broken case */
651                 i_length = 1;
652
653             /* Fix last entry */
654             if (p_stream->entry[p_stream->i_entry_count-1].i_length <= 0)
655                 p_stream->entry[p_stream->i_entry_count-1].i_length = i_length;
656         }
657
658         /* add index entry */
659         mp4_entry_t *e = &p_stream->entry[p_stream->i_entry_count];
660         e->i_pos    = p_sys->i_pos;
661         e->i_size   = p_data->i_buffer;
662
663         if ( p_data->i_dts > VLC_TS_INVALID && p_data->i_pts > p_data->i_dts )
664         {
665             e->i_pts_dts = p_data->i_pts - p_data->i_dts;
666             if ( !p_stream->b_hasbframes )
667                 p_stream->b_hasbframes = true;
668         }
669         else e->i_pts_dts = 0;
670
671         e->i_length = p_data->i_length;
672         e->i_flags  = p_data->i_flags;
673
674         p_stream->i_entry_count++;
675         /* XXX: -1 to always have 2 entry for easy adding of empty SPU */
676         if (p_stream->i_entry_count >= p_stream->i_entry_max - 1) {
677             p_stream->i_entry_max += 1000;
678             p_stream->entry = xrealloc(p_stream->entry,
679                          p_stream->i_entry_max * sizeof(mp4_entry_t));
680         }
681
682         /* update */
683         p_stream->i_read_duration += __MAX( 0, p_data->i_length );
684         p_stream->i_last_length = p_data->i_length;
685         p_sys->i_pos += p_data->i_buffer;
686
687         /* Save the DTS for SPU */
688         p_stream->i_last_dts = p_data->i_dts;
689
690         /* write data */
691         sout_AccessOutWrite(p_mux->p_access, p_data);
692
693         /* close subtitle with empty frame */
694         if (p_stream->fmt.i_cat == SPU_ES) {
695             int64_t i_length = p_stream->entry[p_stream->i_entry_count-1].i_length;
696
697             if ( i_length != 0 && (p_data = block_Alloc(3)) ) {
698                 /* TODO */
699                 msg_Dbg(p_mux, "writing an empty sub") ;
700
701                 /* Append a idx entry */
702                 mp4_entry_t *e = &p_stream->entry[p_stream->i_entry_count];
703                 e->i_pos    = p_sys->i_pos;
704                 e->i_size   = 3;
705                 e->i_pts_dts= 0;
706                 e->i_length = 0;
707                 e->i_flags  = 0;
708
709                 /* XXX: No need to grow the entry here */
710                 p_stream->i_entry_count++;
711
712                 /* Fix last dts */
713                 p_stream->i_last_dts += i_length;
714
715                 /* Write a " " */
716                 p_data->i_dts = p_stream->i_last_dts;
717                 p_data->i_dts = p_data->i_pts;
718                 p_data->p_buffer[0] = 0;
719                 p_data->p_buffer[1] = 1;
720                 p_data->p_buffer[2] = ' ';
721
722                 p_sys->i_pos += p_data->i_buffer;
723
724                 sout_AccessOutWrite(p_mux->p_access, p_data);
725             }
726
727             /* Fix duration = current segment starttime + duration within */
728             p_stream->i_read_duration = p_stream->i_starttime + ( p_stream->i_last_dts - p_stream->i_dts_start );
729         }
730     }
731
732     /* Update the global segment/media duration */
733     for ( unsigned int i=0; i<p_sys->i_nb_streams; i++ )
734     {
735         if ( p_sys->pp_streams[i]->i_read_duration > p_sys->i_read_duration )
736             p_sys->i_read_duration = p_sys->pp_streams[i]->i_read_duration;
737     }
738
739     return(VLC_SUCCESS);
740 }
741
742 /*****************************************************************************
743  *
744  *****************************************************************************/
745 static block_t *ConvertSUBT(block_t *p_block)
746 {
747     p_block = block_Realloc(p_block, 2, p_block->i_buffer);
748     if( !p_block )
749         return NULL;
750     /* No trailling '\0' */
751     if (p_block->i_buffer > 2 && p_block->p_buffer[p_block->i_buffer-1] == '\0')
752         p_block->i_buffer--;
753
754     p_block->p_buffer[0] = ((p_block->i_buffer - 2) >> 8)&0xff;
755     p_block->p_buffer[1] = ((p_block->i_buffer - 2)     )&0xff;
756
757     return p_block;
758 }
759
760 static block_t *ConvertFromAnnexB(block_t *p_block)
761 {
762     if(p_block->i_buffer < 4)
763     {
764         block_Release(p_block);
765         return NULL;
766     }
767
768     if(memcmp(p_block->p_buffer, avc1_start_code, 4))
769     {
770         if(!memcmp(p_block->p_buffer, avc1_short_start_code, 3))
771         {
772             p_block = block_Realloc(p_block, 1, p_block->i_buffer);
773             if( !p_block )
774                 return NULL;
775         }
776         else /* No startcode on start */
777         {
778             block_Release(p_block);
779             return NULL;
780         }
781     }
782
783     uint8_t *last = p_block->p_buffer;
784     uint8_t *dat  = &p_block->p_buffer[4];
785     uint8_t *end = &p_block->p_buffer[p_block->i_buffer];
786
787     /* Replace the 4 bytes start code with 4 bytes size */
788     while (dat < end) {
789         while (dat < end - 4) {
790             if (!memcmp(dat, avc1_start_code, 4))
791             {
792                 break;
793             }
794             else if(!memcmp(dat, avc1_short_start_code, 3))
795             {
796                 /* save offsets as we don't know if realloc will replace buffer */
797                 size_t i_last = last - p_block->p_buffer;
798                 size_t i_dat = dat - p_block->p_buffer;
799                 size_t i_end = end - p_block->p_buffer;
800
801                 p_block = block_Realloc(p_block, 0, p_block->i_buffer + 1);
802                 if( !p_block )
803                     return NULL;
804
805                 /* restore offsets */
806                 last = &p_block->p_buffer[i_last];
807                 dat = &p_block->p_buffer[i_dat];
808                 end = &p_block->p_buffer[i_end];
809
810                 /* Shift data */
811                 memmove(&dat[4], &dat[3], end - &dat[3]);
812                 end++;
813                 break;
814             }
815             dat++;
816         }
817         if (dat >= end - 4)
818             dat = end;
819
820         /* Fix size */
821         SetDWBE(last, dat - &last[4]);
822
823         /* Skip blocks with SPS/PPS */
824         //if ((last[4]&0x1f) == 7 || (last[4]&0x1f) == 8)
825         //    ; // FIXME Find a way to skip dat without frelling everything
826         last = dat;
827         dat += 4;
828     }
829     return p_block;
830 }
831
832 static bo_t *GetESDS(mp4_stream_t *p_stream)
833 {
834     bo_t *esds;
835     int64_t i_bitrate_avg = 0;
836     int64_t i_bitrate_max = 0;
837
838     /* Compute avg/max bitrate */
839     for (unsigned i = 0; i < p_stream->i_entry_count; i++) {
840         i_bitrate_avg += p_stream->entry[i].i_size;
841         if (p_stream->entry[i].i_length > 0) {
842             int64_t i_bitrate = INT64_C(8000000) * p_stream->entry[i].i_size / p_stream->entry[i].i_length;
843             if (i_bitrate > i_bitrate_max)
844                 i_bitrate_max = i_bitrate;
845         }
846     }
847
848     if (p_stream->i_read_duration > 0)
849         i_bitrate_avg = INT64_C(8000000) * i_bitrate_avg / p_stream->i_read_duration;
850     else
851         i_bitrate_avg = 0;
852     if (i_bitrate_max <= 1)
853         i_bitrate_max = 0x7fffffff;
854
855     /* */
856     int i_decoder_specific_info_size = (p_stream->fmt.i_extra > 0) ? 5 + p_stream->fmt.i_extra : 0;
857
858     esds = box_full_new("esds", 0, 0);
859     if(!esds)
860         return NULL;
861
862     /* ES_Descr */
863     bo_add_mp4_tag_descr(esds, 0x03, 3 + 5 + 13 + i_decoder_specific_info_size + 5 + 1);
864     bo_add_16be(esds, p_stream->i_track_id);
865     bo_add_8   (esds, 0x1f);      // flags=0|streamPriority=0x1f
866
867     /* DecoderConfigDescr */
868     bo_add_mp4_tag_descr(esds, 0x04, 13 + i_decoder_specific_info_size);
869
870     int  i_object_type_indication;
871     switch(p_stream->fmt.i_codec)
872     {
873     case VLC_CODEC_MP4V:
874         i_object_type_indication = 0x20;
875         break;
876     case VLC_CODEC_MP2V:
877         /* MPEG-I=0x6b, MPEG-II = 0x60 -> 0x65 */
878         i_object_type_indication = 0x65;
879         break;
880     case VLC_CODEC_MP1V:
881         /* MPEG-I=0x6b, MPEG-II = 0x60 -> 0x65 */
882         i_object_type_indication = 0x6b;
883         break;
884     case VLC_CODEC_MP4A:
885         /* FIXME for mpeg2-aac == 0x66->0x68 */
886         i_object_type_indication = 0x40;
887         break;
888     case VLC_CODEC_MPGA:
889         i_object_type_indication =
890             p_stream->fmt.audio.i_rate < 32000 ? 0x69 : 0x6b;
891         break;
892     default:
893         i_object_type_indication = 0x00;
894         break;
895     }
896     int i_stream_type = p_stream->fmt.i_cat == VIDEO_ES ? 0x04 : 0x05;
897
898     bo_add_8   (esds, i_object_type_indication);
899     bo_add_8   (esds, (i_stream_type << 2) | 1);
900     bo_add_24be(esds, 1024 * 1024);       // bufferSizeDB
901     bo_add_32be(esds, i_bitrate_max);     // maxBitrate
902     bo_add_32be(esds, i_bitrate_avg);     // avgBitrate
903
904     if (p_stream->fmt.i_extra > 0) {
905         /* DecoderSpecificInfo */
906         bo_add_mp4_tag_descr(esds, 0x05, p_stream->fmt.i_extra);
907
908         for (int i = 0; i < p_stream->fmt.i_extra; i++)
909             bo_add_8(esds, ((uint8_t*)p_stream->fmt.p_extra)[i]);
910     }
911
912     /* SL_Descr mandatory */
913     bo_add_mp4_tag_descr(esds, 0x06, 1);
914     bo_add_8    (esds, 0x02);  // sl_predefined
915
916     return esds;
917 }
918
919 static bo_t *GetWaveTag(mp4_stream_t *p_stream)
920 {
921     bo_t *wave;
922     bo_t *box;
923
924     wave = box_new("wave");
925     if(wave)
926     {
927         box = box_new("frma");
928         if(box)
929         {
930             bo_add_fourcc(box, "mp4a");
931             box_gather(wave, box);
932         }
933
934         box = box_new("mp4a");
935         if(box)
936         {
937             bo_add_32be(box, 0);
938             box_gather(wave, box);
939         }
940
941         box = GetESDS(p_stream);
942         box_gather(wave, box);
943
944         box = box_new("srcq");
945         if(box)
946         {
947             bo_add_32be(box, 0x40);
948             box_gather(wave, box);
949         }
950
951         /* wazza ? */
952         bo_add_32be(wave, 8); /* new empty box */
953         bo_add_32be(wave, 0); /* box label */
954     }
955     return wave;
956 }
957
958 static bo_t *GetDec3Tag(mp4_stream_t *p_stream)
959 {
960     if (!p_stream->a52_frame)
961         return NULL;
962
963     bs_t s;
964     bs_init(&s, p_stream->a52_frame->p_buffer, sizeof(p_stream->a52_frame->i_buffer));
965     bs_skip(&s, 16); // syncword
966
967     uint8_t fscod, bsid, bsmod, acmod, lfeon, strmtyp;
968
969     bsmod = 0;
970
971     strmtyp = bs_read(&s, 2);
972
973     if (strmtyp & 0x1) // dependant or reserved stream
974         return NULL;
975
976     if (bs_read(&s, 3) != 0x0) // substreamid: we don't support more than 1 stream
977         return NULL;
978
979     int numblkscod;
980     bs_skip(&s, 11); // frmsizecod
981     fscod = bs_read(&s, 2);
982     if (fscod == 0x03) {
983         bs_skip(&s, 2); // fscod2
984         numblkscod = 3;
985     } else {
986         numblkscod = bs_read(&s, 2);
987     }
988
989     acmod = bs_read(&s, 3);
990     lfeon = bs_read1(&s);
991
992     bsid = bs_read(&s, 5);
993
994     bs_skip(&s, 5); // dialnorm
995     if (bs_read1(&s)) // compre
996         bs_skip(&s, 5); // compr
997
998     if (acmod == 0) {
999         bs_skip(&s, 5); // dialnorm2
1000         if (bs_read1(&s)) // compr2e
1001             bs_skip(&s, 8); // compr2
1002     }
1003
1004     if (strmtyp == 0x1) // dependant stream XXX: unsupported
1005         if (bs_read1(&s)) // chanmape
1006             bs_skip(&s, 16); // chanmap
1007
1008     /* we have to skip mixing info to read bsmod */
1009     if (bs_read1(&s)) { // mixmdate
1010         if (acmod > 0x2) // 2+ channels
1011             bs_skip(&s, 2); // dmixmod
1012         if ((acmod & 0x1) && (acmod > 0x2)) // 3 front channels
1013             bs_skip(&s, 3 + 3); // ltrtcmixlev + lorocmixlev
1014         if (acmod & 0x4) // surround channel
1015             bs_skip(&s, 3 + 3); // ltrsurmixlev + lorosurmixlev
1016         if (lfeon)
1017             if (bs_read1(&s))
1018                 bs_skip(&s, 5); // lfemixlevcod
1019         if (strmtyp == 0) { // independant stream
1020             if (bs_read1(&s)) // pgmscle
1021                 bs_skip(&s, 6); // pgmscl
1022             if (acmod == 0x0) // dual mono
1023                 if (bs_read1(&s)) // pgmscl2e
1024                     bs_skip(&s, 6); // pgmscl2
1025             if (bs_read1(&s)) // extpgmscle
1026                 bs_skip(&s, 6); // extpgmscl
1027             uint8_t mixdef = bs_read(&s, 2);
1028             if (mixdef == 0x1)
1029                 bs_skip(&s, 5);
1030             else if (mixdef == 0x2)
1031                 bs_skip(&s, 12);
1032             else if (mixdef == 0x3) {
1033                 uint8_t mixdeflen = bs_read(&s, 5);
1034                 bs_skip(&s, 8 * (mixdeflen + 2));
1035             }
1036             if (acmod < 0x2) { // mono or dual mono
1037                 if (bs_read1(&s)) // paninfoe
1038                     bs_skip(&s, 14); // paninfo
1039                 if (acmod == 0) // dual mono
1040                     if (bs_read1(&s)) // paninfo2e
1041                         bs_skip(&s, 14); // paninfo2
1042             }
1043             if (bs_read1(&s)) { // frmmixcfginfoe
1044                 static const int blocks[4] = { 1, 2, 3, 6 };
1045                 int number_of_blocks = blocks[numblkscod];
1046                 if (number_of_blocks == 1)
1047                     bs_skip(&s, 5); // blkmixcfginfo[0]
1048                 else for (int i = 0; i < number_of_blocks; i++)
1049                     if (bs_read1(&s)) // blkmixcfginfoe
1050                         bs_skip(&s, 5); // blkmixcfginfo[i]
1051             }
1052         }
1053     }
1054
1055     if (bs_read1(&s)) // infomdate
1056         bsmod = bs_read(&s, 3);
1057
1058     uint8_t mp4_eac3_header[5];
1059     bs_init(&s, mp4_eac3_header, sizeof(mp4_eac3_header));
1060
1061     int data_rate = p_stream->fmt.i_bitrate / 1000;
1062     bs_write(&s, 13, data_rate);
1063     bs_write(&s, 3, 0); // num_ind_sub - 1
1064     bs_write(&s, 2, fscod);
1065     bs_write(&s, 5, bsid);
1066     bs_write(&s, 5, bsmod);
1067     bs_write(&s, 3, acmod);
1068     bs_write(&s, 1, lfeon);
1069     bs_write(&s, 3, 0); // reserved
1070     bs_write(&s, 4, 0); // num_dep_sub
1071     bs_write(&s, 1, 0); // reserved
1072
1073     bo_t *dec3 = box_new("dec3");
1074     if(dec3)
1075         bo_add_mem(dec3, sizeof(mp4_eac3_header), mp4_eac3_header);
1076
1077     return dec3;
1078 }
1079
1080 static bo_t *GetDac3Tag(mp4_stream_t *p_stream)
1081 {
1082     if (!p_stream->a52_frame)
1083         return NULL;
1084
1085     bo_t *dac3 = box_new("dac3");
1086     if(!dac3)
1087         return NULL;
1088
1089     bs_t s;
1090     bs_init(&s, p_stream->a52_frame->p_buffer, sizeof(p_stream->a52_frame->i_buffer));
1091
1092     uint8_t fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
1093
1094     bs_skip(&s, 16 + 16); // syncword + crc
1095
1096     fscod = bs_read(&s, 2);
1097     frmsizecod = bs_read(&s, 6);
1098     bsid = bs_read(&s, 5);
1099     bsmod = bs_read(&s, 3);
1100     acmod = bs_read(&s, 3);
1101     if (acmod == 2)
1102         bs_skip(&s, 2); // dsurmod
1103     else {
1104         if ((acmod & 1) && acmod != 1)
1105             bs_skip(&s, 2); // cmixlev
1106         if (acmod & 4)
1107             bs_skip(&s, 2); // surmixlev
1108     }
1109
1110     lfeon = bs_read1(&s);
1111
1112     uint8_t mp4_a52_header[3];
1113     bs_init(&s, mp4_a52_header, sizeof(mp4_a52_header));
1114
1115     bs_write(&s, 2, fscod);
1116     bs_write(&s, 5, bsid);
1117     bs_write(&s, 3, bsmod);
1118     bs_write(&s, 3, acmod);
1119     bs_write(&s, 1, lfeon);
1120     bs_write(&s, 5, frmsizecod >> 1); // bit_rate_code
1121     bs_write(&s, 5, 0); // reserved
1122
1123     bo_add_mem(dac3, sizeof(mp4_a52_header), mp4_a52_header);
1124
1125     return dac3;
1126 }
1127
1128 static bo_t *GetDamrTag(mp4_stream_t *p_stream)
1129 {
1130     bo_t *damr = box_new("damr");
1131     if(!damr)
1132         return NULL;
1133
1134     bo_add_fourcc(damr, "REFC");
1135     bo_add_8(damr, 0);
1136
1137     if (p_stream->fmt.i_codec == VLC_CODEC_AMR_NB)
1138         bo_add_16be(damr, 0x81ff); /* Mode set (all modes for AMR_NB) */
1139     else
1140         bo_add_16be(damr, 0x83ff); /* Mode set (all modes for AMR_WB) */
1141     bo_add_16be(damr, 0x1); /* Mode change period (no restriction) */
1142
1143     return damr;
1144 }
1145
1146 static bo_t *GetD263Tag(void)
1147 {
1148     bo_t *d263 = box_new("d263");
1149     if(!d263)
1150         return NULL;
1151
1152     bo_add_fourcc(d263, "VLC ");
1153     bo_add_16be(d263, 0xa);
1154     bo_add_8(d263, 0);
1155
1156     return d263;
1157 }
1158
1159 static void hevcParseVPS(uint8_t * p_buffer, size_t i_buffer, uint8_t *general,
1160                          uint8_t * numTemporalLayer, bool * temporalIdNested)
1161 {
1162     const size_t i_decoded_nal_size = 512;
1163     uint8_t p_dec_nal[i_decoded_nal_size];
1164     size_t i_size = (i_buffer < i_decoded_nal_size)?i_buffer:i_decoded_nal_size;
1165     nal_decode(p_buffer, p_dec_nal, i_size);
1166
1167     /* first two bytes are the NAL header, 3rd and 4th are:
1168         vps_video_parameter_set_id(4)
1169         vps_reserved_3_2bis(2)
1170         vps_max_layers_minus1(6)
1171         vps_max_sub_layers_minus1(3)
1172         vps_temporal_id_nesting_flags
1173     */
1174     *numTemporalLayer =  ((p_dec_nal[3] & 0x0E) >> 1) + 1;
1175     *temporalIdNested = (bool)(p_dec_nal[3] & 0x01);
1176
1177     /* 5th & 6th are reserved 0xffff */
1178     /* copy the first 12 bytes of profile tier */
1179     memcpy(general, &p_dec_nal[6], 12);
1180 }
1181
1182 static void hevcParseSPS(uint8_t * p_buffer, size_t i_buffer, uint8_t * chroma_idc,
1183                          uint8_t *bit_depth_luma_minus8, uint8_t *bit_depth_chroma_minus8)
1184 {
1185     const size_t i_decoded_nal_size = 512;
1186     uint8_t p_dec_nal[i_decoded_nal_size];
1187     size_t i_size = (i_buffer < i_decoded_nal_size)?i_buffer-2:i_decoded_nal_size;
1188     nal_decode(p_buffer+2, p_dec_nal, i_size);
1189     bs_t bs;
1190     bs_init(&bs, p_dec_nal, i_size);
1191
1192     /* skip vps id */
1193     bs_skip(&bs, 4);
1194     uint32_t sps_max_sublayer_minus1 = bs_read(&bs, 3);
1195
1196     /* skip nesting flag */
1197     bs_skip(&bs, 1);
1198
1199     hevc_skip_profile_tiers_level(&bs, sps_max_sublayer_minus1);
1200
1201     /* skip sps id */
1202     (void) bs_read_ue( &bs );
1203
1204     *chroma_idc = bs_read_ue(&bs);
1205     if (*chroma_idc == 3)
1206         bs_skip(&bs, 1);
1207
1208     /* skip width and heigh */
1209     (void) bs_read_ue( &bs );
1210     (void) bs_read_ue( &bs );
1211
1212     uint32_t conformance_window_flag = bs_read1(&bs);
1213     if (conformance_window_flag) {
1214         /* skip offsets*/
1215         (void) bs_read_ue(&bs);
1216         (void) bs_read_ue(&bs);
1217         (void) bs_read_ue(&bs);
1218         (void) bs_read_ue(&bs);
1219     }
1220     *bit_depth_luma_minus8 = bs_read_ue(&bs);
1221     *bit_depth_chroma_minus8 = bs_read_ue(&bs);
1222 }
1223
1224 static bo_t *GetHvcCTag(mp4_stream_t *p_stream)
1225 {
1226     /* Generate hvcC box matching iso/iec 14496-15 3rd edition */
1227     bo_t *hvcC = box_new("hvcC");
1228     if(!hvcC || !p_stream->fmt.i_extra)
1229         return hvcC;
1230
1231     struct nal {
1232         size_t i_buffer;
1233         uint8_t * p_buffer;
1234     };
1235
1236     /* According to the specification HEVC stream can have
1237      * 16 vps id and an "unlimited" number of sps and pps id using ue(v) id*/
1238     struct nal p_vps[16], *p_sps = NULL, *p_pps = NULL, *p_sei = NULL,
1239                *p_nal = NULL;
1240     size_t i_vps = 0, i_sps = 0, i_pps = 0, i_sei = 0;
1241     uint8_t i_num_arrays = 0;
1242
1243     uint8_t * p_buffer = p_stream->fmt.p_extra;
1244     size_t i_buffer = p_stream->fmt.i_extra;
1245
1246     uint8_t general_configuration[12] = {0};
1247     uint8_t i_numTemporalLayer = 0;
1248     uint8_t i_chroma_idc = 1;
1249     uint8_t i_bit_depth_luma_minus8 = 0;
1250     uint8_t i_bit_depth_chroma_minus8 = 0;
1251     bool b_temporalIdNested = false;
1252
1253     uint32_t cmp = 0xFFFFFFFF;
1254     while (i_buffer) {
1255         /* look for start code 0X0000001 */
1256         while (i_buffer) {
1257             cmp = (cmp << 8) | *p_buffer;
1258             if((cmp ^ UINT32_C(0x100)) <= UINT32_C(0xFF))
1259                 break;
1260             p_buffer++;
1261             i_buffer--;
1262         }
1263         if (p_nal)
1264             p_nal->i_buffer = p_buffer - p_nal->p_buffer - ((i_buffer)?3:0);
1265
1266         switch (*p_buffer & 0x72) {
1267             /* VPS */
1268         case 0x40:
1269             p_nal = &p_vps[i_vps++];
1270             p_nal->p_buffer = p_buffer;
1271             /* Only keep the general profile from the first VPS
1272              * if there are several (this shouldn't happen so soon) */
1273             if (i_vps == 1) {
1274                 hevcParseVPS(p_buffer, i_buffer, general_configuration,
1275                              &i_numTemporalLayer, &b_temporalIdNested);
1276                 i_num_arrays++;
1277             }
1278             break;
1279             /* SPS */
1280         case 0x42: {
1281             struct nal * p_tmp =  realloc(p_sps, sizeof(struct nal) * (i_sps + 1));
1282             if (!p_tmp)
1283                 break;
1284             p_sps = p_tmp;
1285             p_nal = &p_sps[i_sps++];
1286             p_nal->p_buffer = p_buffer;
1287             if (i_sps == 1 && i_buffer > 15) {
1288                 /* Get Chroma_idc and bitdepths */
1289                 hevcParseSPS(p_buffer, i_buffer, &i_chroma_idc,
1290                              &i_bit_depth_luma_minus8, &i_bit_depth_chroma_minus8);
1291                 i_num_arrays++;
1292             }
1293             break;
1294             }
1295         /* PPS */
1296         case 0x44: {
1297             struct nal * p_tmp =  realloc(p_pps, sizeof(struct nal) * (i_pps + 1));
1298             if (!p_tmp)
1299                 break;
1300             p_pps = p_tmp;
1301             p_nal = &p_pps[i_pps++];
1302             p_nal->p_buffer = p_buffer;
1303             if (i_pps == 1)
1304                 i_num_arrays++;
1305             break;
1306             }
1307         /* SEI */
1308         case 0x4E:
1309         case 0x50: {
1310             struct nal * p_tmp =  realloc(p_sei, sizeof(struct nal) * (i_sei + 1));
1311             if (!p_tmp)
1312                 break;
1313             p_sei = p_tmp;
1314             p_nal = &p_sei[i_sei++];
1315             p_nal->p_buffer = p_buffer;
1316             if(i_sei == 1)
1317                 i_num_arrays++;
1318             break;
1319         }
1320         default:
1321             p_nal = NULL;
1322             break;
1323         }
1324     }
1325     bo_add_8(hvcC, 0x01);
1326     bo_add_mem(hvcC, 12, general_configuration);
1327     /* Don't set min spatial segmentation */
1328     bo_add_16be(hvcC, 0xF000);
1329     /* Don't set parallelism type since segmentation isn't set */
1330     bo_add_8(hvcC, 0xFC);
1331     bo_add_8(hvcC, (0xFC | (i_chroma_idc & 0x03)));
1332     bo_add_8(hvcC, (0xF8 | (i_bit_depth_luma_minus8 & 0x07)));
1333     bo_add_8(hvcC, (0xF8 | (i_bit_depth_chroma_minus8 & 0x07)));
1334
1335     /* Don't set framerate */
1336     bo_add_16be(hvcC, 0x0000);
1337     /* Force NAL size of 4 bytes that replace the startcode */
1338     bo_add_8(hvcC, (((i_numTemporalLayer & 0x07) << 3) |
1339                     (b_temporalIdNested << 2) | 0x03));
1340     bo_add_8(hvcC, i_num_arrays);
1341
1342     if (i_vps)
1343     {
1344         /* Write VPS without forcing array_completeness */
1345         bo_add_8(hvcC, 32);
1346         bo_add_16be(hvcC, i_vps);
1347         for (size_t i = 0; i < i_vps; i++) {
1348             p_nal = &p_vps[i];
1349             bo_add_16be(hvcC, p_nal->i_buffer);
1350             bo_add_mem(hvcC, p_nal->i_buffer, p_nal->p_buffer);
1351         }
1352     }
1353
1354     if (i_sps) {
1355         /* Write SPS without forcing array_completeness */
1356         bo_add_8(hvcC, 33);
1357         bo_add_16be(hvcC, i_sps);
1358         for (size_t i = 0; i < i_sps; i++) {
1359             p_nal = &p_sps[i];
1360             bo_add_16be(hvcC, p_nal->i_buffer);
1361             bo_add_mem(hvcC, p_nal->i_buffer, p_nal->p_buffer);
1362         }
1363     }
1364
1365     if (i_pps) {
1366         /* Write PPS without forcing array_completeness */
1367         bo_add_8(hvcC, 34);
1368         bo_add_16be(hvcC, i_pps);
1369         for (size_t i = 0; i < i_pps; i++) {
1370             p_nal = &p_pps[i];
1371             bo_add_16be(hvcC, p_nal->i_buffer);
1372             bo_add_mem(hvcC, p_nal->i_buffer, p_nal->p_buffer);
1373         }
1374     }
1375
1376     if (i_sei) {
1377         /* Write SEI without forcing array_completeness */
1378         bo_add_8(hvcC, 39);
1379         bo_add_16be(hvcC, i_sei);
1380         for (size_t i = 0; i < i_sei; i++) {
1381             p_nal = &p_sei[i];
1382             bo_add_16be(hvcC, p_nal->i_buffer);
1383             bo_add_mem(hvcC, p_nal->i_buffer, p_nal->p_buffer);
1384         }
1385     }
1386     return hvcC;
1387 }
1388
1389 static bo_t *GetAvcCTag(mp4_stream_t *p_stream)
1390 {
1391     bo_t    *avcC = box_new("avcC");/* FIXME use better value */
1392     if(!avcC)
1393         return NULL;
1394     uint8_t *p_sps = NULL;
1395     uint8_t *p_pps = NULL;
1396     int     i_sps_size = 0;
1397     int     i_pps_size = 0;
1398
1399     if (p_stream->fmt.i_extra > 0) {
1400         /* FIXME: take into account multiple sps/pps */
1401         uint8_t *p_buffer = p_stream->fmt.p_extra;
1402         int     i_buffer = p_stream->fmt.i_extra;
1403
1404         while (i_buffer > 3) {
1405             while (memcmp(p_buffer, &avc1_start_code[1], 3)) {
1406                  i_buffer--;
1407                  p_buffer++;
1408             }
1409             const int i_nal_type = p_buffer[3]&0x1f;
1410             int i_startcode = 0;
1411
1412             for (int i_offset = 1; i_offset+2 < i_buffer ; i_offset++)
1413                 if (!memcmp(&p_buffer[i_offset], &avc1_start_code[1], 3)) {
1414                     /* we found another startcode */
1415                     i_startcode = i_offset;
1416                     while (p_buffer[i_startcode-1] == 0 && i_startcode > 0)
1417                         i_startcode--;
1418                     break;
1419                 }
1420
1421             int i_size = i_startcode ? i_startcode : i_buffer;
1422
1423             if (i_nal_type == 7) {
1424                 p_sps = &p_buffer[3];
1425                 i_sps_size = i_size - 3;
1426             }
1427             if (i_nal_type == 8) {
1428                 p_pps = &p_buffer[3];
1429                 i_pps_size = i_size - 3;
1430             }
1431             i_buffer -= i_size;
1432             p_buffer += i_size;
1433         }
1434     }
1435
1436     bo_add_8(avcC, 1);      /* configuration version */
1437     bo_add_8(avcC, i_sps_size ? p_sps[1] : 77);
1438     bo_add_8(avcC, i_sps_size ? p_sps[2] : 64);
1439     bo_add_8(avcC, i_sps_size ? p_sps[3] : 30);       /* level, 5.1 */
1440     bo_add_8(avcC, 0xff);   /* 0b11111100 | lengthsize = 0x11 */
1441
1442     bo_add_8(avcC, 0xe0 | (i_sps_size > 0 ? 1 : 0));   /* 0b11100000 | sps_count */
1443     if (i_sps_size > 0) {
1444         bo_add_16be(avcC, i_sps_size);
1445         bo_add_mem(avcC, i_sps_size, p_sps);
1446     }
1447
1448     bo_add_8(avcC, (i_pps_size > 0 ? 1 : 0));   /* pps_count */
1449     if (i_pps_size > 0) {
1450         bo_add_16be(avcC, i_pps_size);
1451         bo_add_mem(avcC, i_pps_size, p_pps);
1452     }
1453
1454     return avcC;
1455 }
1456
1457 /* TODO: No idea about these values */
1458 static bo_t *GetSVQ3Tag(mp4_stream_t *p_stream)
1459 {
1460     bo_t *smi = box_new("SMI ");
1461     if(!smi)
1462         return NULL;
1463
1464     if (p_stream->fmt.i_extra > 0x4e) {
1465         uint8_t *p_end = &((uint8_t*)p_stream->fmt.p_extra)[p_stream->fmt.i_extra];
1466         uint8_t *p     = &((uint8_t*)p_stream->fmt.p_extra)[0x46];
1467
1468         while (p + 8 < p_end) {
1469             int i_size = GetDWBE(p);
1470             if (i_size <= 1) /* FIXME handle 1 as long size */
1471                 break;
1472             if (!strncmp((const char *)&p[4], "SMI ", 4)) {
1473                 bo_add_mem(smi, p_end - p - 8, &p[8]);
1474                 return smi;
1475             }
1476             p += i_size;
1477         }
1478     }
1479
1480     /* Create a dummy one in fallback */
1481     bo_add_fourcc(smi, "SEQH");
1482     bo_add_32be(smi, 0x5);
1483     bo_add_32be(smi, 0xe2c0211d);
1484     bo_add_8(smi, 0xc0);
1485
1486     return smi;
1487 }
1488
1489 static bo_t *GetUdtaTag(sout_mux_t *p_mux)
1490 {
1491     sout_mux_sys_t *p_sys = p_mux->p_sys;
1492     bo_t *udta = box_new("udta");
1493     if (!udta)
1494         return NULL;
1495
1496     /* Requirements */
1497     for (unsigned int i_track = 0; i_track < p_sys->i_nb_streams; i_track++) {
1498         mp4_stream_t *p_stream = p_sys->pp_streams[i_track];
1499         vlc_fourcc_t codec = p_stream->fmt.i_codec;
1500
1501         if (codec == VLC_CODEC_MP4V || codec == VLC_CODEC_MP4A) {
1502             bo_t *box = box_new("\251req");
1503             if(!box)
1504                 break;
1505             /* String length */
1506             bo_add_16be(box, sizeof("QuickTime 6.0 or greater") - 1);
1507             bo_add_16be(box, 0);
1508             bo_add_mem(box, sizeof("QuickTime 6.0 or greater") - 1,
1509                         (uint8_t *)"QuickTime 6.0 or greater");
1510             box_gather(udta, box);
1511             break;
1512         }
1513     }
1514
1515     /* Encoder */
1516     {
1517         bo_t *box = box_new("\251enc");
1518         if(box)
1519         {
1520             /* String length */
1521             bo_add_16be(box, sizeof(PACKAGE_STRING " stream output") - 1);
1522             bo_add_16be(box, 0);
1523             bo_add_mem(box, sizeof(PACKAGE_STRING " stream output") - 1,
1524                         (uint8_t*)PACKAGE_STRING " stream output");
1525             box_gather(udta, box);
1526         }
1527     }
1528 #if 0
1529     /* Misc atoms */
1530     vlc_meta_t *p_meta = p_mux->p_sout->p_meta;
1531     if (p_meta) {
1532 #define ADD_META_BOX(type, box_string) { \
1533         bo_t *box = NULL;  \
1534         if (vlc_meta_Get(p_meta, vlc_meta_##type)) \
1535             box = box_new("\251" box_string); \
1536         if (box) { \
1537             bo_add_16be(box, strlen(vlc_meta_Get(p_meta, vlc_meta_##type))); \
1538             bo_add_16be(box, 0); \
1539             bo_add_mem(box, strlen(vlc_meta_Get(p_meta, vlc_meta_##type)), \
1540                         (uint8_t*)(vlc_meta_Get(p_meta, vlc_meta_##type))); \
1541             box_gather(udta, box); \
1542         } }
1543
1544         ADD_META_BOX(Title, "nam");
1545         ADD_META_BOX(Artist, "ART");
1546         ADD_META_BOX(Genre, "gen");
1547         ADD_META_BOX(Copyright, "cpy");
1548         ADD_META_BOX(Description, "des");
1549         ADD_META_BOX(Date, "day");
1550         ADD_META_BOX(URL, "url");
1551 #undef ADD_META_BOX
1552     }
1553 #endif
1554     return udta;
1555 }
1556
1557 static bo_t *GetSounBox(sout_mux_t *p_mux, mp4_stream_t *p_stream)
1558 {
1559     sout_mux_sys_t *p_sys = p_mux->p_sys;
1560     bool b_descr = true;
1561     vlc_fourcc_t codec = p_stream->fmt.i_codec;
1562     char fcc[4];
1563
1564     if (codec == VLC_CODEC_MPGA) {
1565         if (p_sys->b_mov) {
1566             b_descr = false;
1567             memcpy(fcc, ".mp3", 4);
1568         } else
1569             memcpy(fcc, "mp4a", 4);
1570     } else if (codec == VLC_CODEC_A52) {
1571         memcpy(fcc, "ac-3", 4);
1572     } else if (codec == VLC_CODEC_EAC3) {
1573         memcpy(fcc, "ec-3", 4);
1574     } else
1575         vlc_fourcc_to_char(codec, fcc);
1576
1577     bo_t *soun = box_new(fcc);
1578     if(!soun)
1579         return NULL;
1580     for (int i = 0; i < 6; i++)
1581         bo_add_8(soun, 0);        // reserved;
1582     bo_add_16be(soun, 1);         // data-reference-index
1583
1584     /* SoundDescription */
1585     if (p_sys->b_mov && codec == VLC_CODEC_MP4A)
1586         bo_add_16be(soun, 1);     // version 1;
1587     else
1588         bo_add_16be(soun, 0);     // version 0;
1589     bo_add_16be(soun, 0);         // revision level (0)
1590     bo_add_32be(soun, 0);         // vendor
1591     // channel-count
1592     bo_add_16be(soun, p_stream->fmt.audio.i_channels);
1593     // sample size
1594     bo_add_16be(soun, p_stream->fmt.audio.i_bitspersample ?
1595                  p_stream->fmt.audio.i_bitspersample : 16);
1596     bo_add_16be(soun, -2);        // compression id
1597     bo_add_16be(soun, 0);         // packet size (0)
1598     bo_add_16be(soun, p_stream->fmt.audio.i_rate); // sampleratehi
1599     bo_add_16be(soun, 0);                             // sampleratelo
1600
1601     /* Extended data for SoundDescription V1 */
1602     if (p_sys->b_mov && p_stream->fmt.i_codec == VLC_CODEC_MP4A) {
1603         /* samples per packet */
1604         bo_add_32be(soun, p_stream->fmt.audio.i_frame_length);
1605         bo_add_32be(soun, 1536); /* bytes per packet */
1606         bo_add_32be(soun, 2);    /* bytes per frame */
1607         /* bytes per sample */
1608         bo_add_32be(soun, 2 /*p_stream->fmt.audio.i_bitspersample/8 */);
1609     }
1610
1611     /* Add an ES Descriptor */
1612     if (b_descr) {
1613         bo_t *box;
1614
1615         if (p_sys->b_mov && codec == VLC_CODEC_MP4A)
1616             box = GetWaveTag(p_stream);
1617         else if (codec == VLC_CODEC_AMR_NB)
1618             box = GetDamrTag(p_stream);
1619         else if (codec == VLC_CODEC_A52)
1620             box = GetDac3Tag(p_stream);
1621         else if (codec == VLC_CODEC_EAC3)
1622             box = GetDec3Tag(p_stream);
1623         else
1624             box = GetESDS(p_stream);
1625
1626         if (box)
1627             box_gather(soun, box);
1628     }
1629
1630     return soun;
1631 }
1632
1633 static bo_t *GetVideBox(mp4_stream_t *p_stream)
1634 {
1635     char fcc[4];
1636
1637     switch(p_stream->fmt.i_codec)
1638     {
1639     case VLC_CODEC_MP4V:
1640     case VLC_CODEC_MPGV: memcpy(fcc, "mp4v", 4); break;
1641     case VLC_CODEC_MJPG: memcpy(fcc, "mjpa", 4); break;
1642     case VLC_CODEC_SVQ1: memcpy(fcc, "SVQ1", 4); break;
1643     case VLC_CODEC_SVQ3: memcpy(fcc, "SVQ3", 4); break;
1644     case VLC_CODEC_H263: memcpy(fcc, "s263", 4); break;
1645     case VLC_CODEC_H264: memcpy(fcc, "avc1", 4); break;
1646     case VLC_CODEC_HEVC: memcpy(fcc, "hvc1", 4); break;
1647     case VLC_CODEC_YV12: memcpy(fcc, "yv12", 4); break;
1648     case VLC_CODEC_YUYV: memcpy(fcc, "yuy2", 4); break;
1649     default:
1650         vlc_fourcc_to_char(p_stream->fmt.i_codec, fcc);
1651         break;
1652     }
1653
1654     bo_t *vide = box_new(fcc);
1655     if(!vide)
1656         return NULL;
1657     for (int i = 0; i < 6; i++)
1658         bo_add_8(vide, 0);        // reserved;
1659     bo_add_16be(vide, 1);         // data-reference-index
1660
1661     bo_add_16be(vide, 0);         // predefined;
1662     bo_add_16be(vide, 0);         // reserved;
1663     for (int i = 0; i < 3; i++)
1664         bo_add_32be(vide, 0);     // predefined;
1665
1666     bo_add_16be(vide, p_stream->fmt.video.i_width);  // i_width
1667     bo_add_16be(vide, p_stream->fmt.video.i_height); // i_height
1668
1669     bo_add_32be(vide, 0x00480000);                // h 72dpi
1670     bo_add_32be(vide, 0x00480000);                // v 72dpi
1671
1672     bo_add_32be(vide, 0);         // data size, always 0
1673     bo_add_16be(vide, 1);         // frames count per sample
1674
1675     // compressor name;
1676     for (int i = 0; i < 32; i++)
1677         bo_add_8(vide, 0);
1678
1679     bo_add_16be(vide, 0x18);      // depth
1680     bo_add_16be(vide, 0xffff);    // predefined
1681
1682     /* add an ES Descriptor */
1683     switch(p_stream->fmt.i_codec)
1684     {
1685     case VLC_CODEC_MP4V:
1686     case VLC_CODEC_MPGV:
1687         box_gather(vide, GetESDS(p_stream));
1688         break;
1689
1690     case VLC_CODEC_H263:
1691         box_gather(vide, GetD263Tag());
1692         break;
1693
1694     case VLC_CODEC_SVQ3:
1695         box_gather(vide, GetSVQ3Tag(p_stream));
1696         break;
1697
1698     case VLC_CODEC_H264:
1699         box_gather(vide, GetAvcCTag(p_stream));
1700         break;
1701
1702     case VLC_CODEC_HEVC:
1703         box_gather(vide, GetHvcCTag(p_stream));
1704         break;
1705     }
1706
1707     return vide;
1708 }
1709
1710 static bo_t *GetTextBox(void)
1711 {
1712     bo_t *text = box_new("text");
1713     if(!text)
1714         return NULL;
1715
1716     for (int i = 0; i < 6; i++)
1717         bo_add_8(text, 0);        // reserved;
1718     bo_add_16be(text, 1);         // data-reference-index
1719
1720     bo_add_32be(text, 0);         // display flags
1721     bo_add_32be(text, 0);         // justification
1722     for (int i = 0; i < 3; i++)
1723         bo_add_16be(text, 0);     // back ground color
1724
1725     bo_add_16be(text, 0);         // box text
1726     bo_add_16be(text, 0);         // box text
1727     bo_add_16be(text, 0);         // box text
1728     bo_add_16be(text, 0);         // box text
1729
1730     bo_add_64be(text, 0);         // reserved
1731     for (int i = 0; i < 3; i++)
1732         bo_add_16be(text, 0xff);  // foreground color
1733
1734     bo_add_8 (text, 9);
1735     bo_add_mem(text, 9, (uint8_t*)"Helvetica");
1736
1737     return text;
1738 }
1739
1740 static bo_t *GetStblBox(sout_mux_t *p_mux, mp4_stream_t *p_stream)
1741 {
1742     sout_mux_sys_t *p_sys = p_mux->p_sys;
1743
1744     /* sample description */
1745     bo_t *stsd = box_full_new("stsd", 0, 0);
1746     if(!stsd)
1747         return NULL;
1748     bo_add_32be(stsd, 1);
1749     if (p_stream->fmt.i_cat == AUDIO_ES)
1750         box_gather(stsd, GetSounBox(p_mux, p_stream));
1751     else if (p_stream->fmt.i_cat == VIDEO_ES)
1752         box_gather(stsd, GetVideBox(p_stream));
1753     else if (p_stream->fmt.i_cat == SPU_ES)
1754         box_gather(stsd, GetTextBox());
1755
1756     /* chunk offset table */
1757     bo_t *stco;
1758     if (p_sys->i_pos >= (((uint64_t)0x1) << 32)) {
1759         /* 64 bits version */
1760         p_stream->b_stco64 = true;
1761         stco = box_full_new("co64", 0, 0);
1762     } else {
1763         /* 32 bits version */
1764         p_stream->b_stco64 = false;
1765         stco = box_full_new("stco", 0, 0);
1766     }
1767     if(!stco)
1768     {
1769         bo_free(stsd);
1770         return NULL;
1771     }
1772     bo_add_32be(stco, 0);     // entry-count (fixed latter)
1773
1774     /* sample to chunk table */
1775     bo_t *stsc = box_full_new("stsc", 0, 0);
1776     bo_add_32be(stsc, 0);     // entry-count (fixed latter)
1777
1778     unsigned i_chunk = 0;
1779     unsigned i_stsc_last_val = 0, i_stsc_entries = 0;
1780     for (unsigned i = 0; i < p_stream->i_entry_count; i_chunk++) {
1781         mp4_entry_t *entry = p_stream->entry;
1782         int i_first = i;
1783
1784         if (p_stream->b_stco64)
1785             bo_add_64be(stco, entry[i].i_pos);
1786         else
1787             bo_add_32be(stco, entry[i].i_pos);
1788
1789         for (; i < p_stream->i_entry_count; i++)
1790             if (i >= p_stream->i_entry_count - 1 ||
1791                     entry[i].i_pos + entry[i].i_size != entry[i+1].i_pos) {
1792                 i++;
1793                 break;
1794             }
1795
1796         /* Add entry to the stsc table */
1797         if (i_stsc_last_val != i - i_first) {
1798             bo_add_32be(stsc, 1 + i_chunk);   // first-chunk
1799             bo_add_32be(stsc, i - i_first) ;  // samples-per-chunk
1800             bo_add_32be(stsc, 1);             // sample-descr-index
1801             i_stsc_last_val = i - i_first;
1802             i_stsc_entries++;
1803         }
1804     }
1805
1806     /* Fix stco entry count */
1807     bo_swap_32be(stco, 12, i_chunk);
1808     msg_Dbg(p_mux, "created %d chunks (stco)", i_chunk);
1809
1810     /* Fix stsc entry count */
1811     bo_swap_32be(stsc, 12, i_stsc_entries );
1812
1813     /* add stts */
1814     bo_t *stts = box_full_new("stts", 0, 0);
1815     if(!stts)
1816     {
1817         bo_free(stsd);
1818         bo_free(stco);
1819         return NULL;
1820     }
1821     bo_add_32be(stts, 0);     // entry-count (fixed latter)
1822
1823     unsigned i_index = 0;
1824     for (unsigned i = 0; i < p_stream->i_entry_count; i_index++) {
1825         int     i_first = i;
1826         mtime_t i_delta = p_stream->entry[i].i_length;
1827
1828         for (; i < p_stream->i_entry_count; ++i)
1829             if (i == p_stream->i_entry_count || p_stream->entry[i].i_length != i_delta)
1830                 break;
1831
1832         bo_add_32be(stts, i - i_first); // sample-count
1833         bo_add_32be(stts, (uint64_t)i_delta  * p_stream->i_timescale / CLOCK_FREQ); // sample-delta
1834     }
1835     bo_swap_32be(stts, 12, i_index);
1836
1837     /* composition time handling */
1838     bo_t *ctts = NULL;
1839     if ( p_stream->b_hasbframes && (ctts = box_full_new("ctts", 0, 0)) )
1840     {
1841         bo_add_32be(ctts, 0);
1842         i_index = 0;
1843         for (unsigned i = 0; i < p_stream->i_entry_count; i_index++)
1844         {
1845             int     i_first = i;
1846             mtime_t i_offset = p_stream->entry[i].i_pts_dts;
1847
1848             for (; i < p_stream->i_entry_count; ++i)
1849                 if (i == p_stream->i_entry_count || p_stream->entry[i].i_pts_dts != i_offset)
1850                     break;
1851
1852             bo_add_32be(ctts, i - i_first); // sample-count
1853             bo_add_32be(ctts, i_offset * p_stream->i_timescale / CLOCK_FREQ ); // sample-offset
1854         }
1855         bo_swap_32be(ctts, 12, i_index);
1856     }
1857
1858     bo_t *stsz = box_full_new("stsz", 0, 0);
1859     if(!stsz)
1860     {
1861         bo_free(stsd);
1862         bo_free(stco);
1863         bo_free(stts);
1864         return NULL;
1865     }
1866     int i_size = 0;
1867     for (unsigned i = 0; i < p_stream->i_entry_count; i++)
1868     {
1869         if ( i == 0 )
1870             i_size = p_stream->entry[i].i_size;
1871         else if ( p_stream->entry[i].i_size != i_size )
1872         {
1873             i_size = 0;
1874             break;
1875         }
1876     }
1877     bo_add_32be(stsz, i_size);                         // sample-size
1878     bo_add_32be(stsz, p_stream->i_entry_count);       // sample-count
1879     if ( i_size == 0 ) // all samples have different size
1880     {
1881         for (unsigned i = 0; i < p_stream->i_entry_count; i++)
1882             bo_add_32be(stsz, p_stream->entry[i].i_size); // sample-size
1883     }
1884
1885     /* create stss table */
1886     bo_t *stss = NULL;
1887     i_index = 0;
1888     if ( p_stream->fmt.i_cat == VIDEO_ES || p_stream->fmt.i_cat == AUDIO_ES )
1889     {
1890         mtime_t i_interval = -1;
1891         for (unsigned i = 0; i < p_stream->i_entry_count; i++)
1892         {
1893             if ( i_interval != -1 )
1894             {
1895                 i_interval += p_stream->entry[i].i_length + p_stream->entry[i].i_pts_dts;
1896                 if ( i_interval < CLOCK_FREQ * 2 )
1897                     continue;
1898             }
1899
1900             if (p_stream->entry[i].i_flags & BLOCK_FLAG_TYPE_I) {
1901                 if (stss == NULL) {
1902                     stss = box_full_new("stss", 0, 0);
1903                     if(!stss)
1904                         break;
1905                     bo_add_32be(stss, 0); /* fixed later */
1906                 }
1907                 bo_add_32be(stss, 1 + i);
1908                 i_index++;
1909                 i_interval = 0;
1910             }
1911         }
1912     }
1913
1914     if (stss)
1915         bo_swap_32be(stss, 12, i_index);
1916
1917     /* Now gather all boxes into stbl */
1918     bo_t *stbl = box_new("stbl");
1919     if(!stbl)
1920     {
1921         bo_free(stsd);
1922         bo_free(stco);
1923         bo_free(stts);
1924         bo_free(stsz);
1925         bo_free(stss);
1926         return NULL;
1927     }
1928     box_gather(stbl, stsd);
1929     box_gather(stbl, stts);
1930     if (stss)
1931         box_gather(stbl, stss);
1932     if (ctts)
1933         box_gather(stbl, ctts);
1934     box_gather(stbl, stsc);
1935     box_gather(stbl, stsz);
1936     p_stream->i_stco_pos = stbl->b->i_buffer + 16;
1937     box_gather(stbl, stco);
1938
1939     return stbl;
1940 }
1941
1942 static int64_t get_timestamp(void);
1943
1944 static void matrix_apply_rotation(es_format_t *fmt, uint32_t mvhd_matrix[9])
1945 {
1946     enum video_orientation_t orientation = ORIENT_NORMAL;
1947     if (fmt->i_cat == VIDEO_ES)
1948         orientation = fmt->video.orientation;
1949
1950 #define ATAN(a, b) do { mvhd_matrix[1] = (a) << 16; \
1951     mvhd_matrix[0] = (b) << 16; \
1952     } while(0)
1953
1954     switch (orientation) {
1955     case ORIENT_ROTATED_90:  ATAN( 1,  0); break;
1956     case ORIENT_ROTATED_180: ATAN( 0, -1); break;
1957     case ORIENT_ROTATED_270: ATAN( -1, 0); break;
1958     default:                 ATAN( 0,  1); break;
1959     }
1960
1961     mvhd_matrix[3] = mvhd_matrix[0] ? 0 : 0x10000;
1962     mvhd_matrix[4] = mvhd_matrix[1] ? 0 : 0x10000;
1963 }
1964
1965 static bo_t *GetMoovBox(sout_mux_t *p_mux)
1966 {
1967     sout_mux_sys_t *p_sys = p_mux->p_sys;
1968
1969     bo_t            *moov, *mvhd;
1970
1971     uint32_t        i_movie_timescale = 90000;
1972     int64_t         i_movie_duration  = 0;
1973     int64_t         i_timestamp = get_timestamp();
1974
1975     moov = box_new("moov");
1976     if(!moov)
1977         return NULL;
1978     /* Create general info */
1979     if ( !p_sys->b_fragmented )
1980     {
1981         for (unsigned int i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++) {
1982             mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
1983             i_movie_duration = __MAX(i_movie_duration, p_stream->i_read_duration);
1984         }
1985         msg_Dbg(p_mux, "movie duration %"PRId64"s", i_movie_duration / CLOCK_FREQ);
1986
1987         i_movie_duration = i_movie_duration * i_movie_timescale / CLOCK_FREQ;
1988     }
1989     else
1990         i_movie_duration = 0;
1991
1992     /* *** add /moov/mvhd *** */
1993     if (!p_sys->b_64_ext) {
1994         mvhd = box_full_new("mvhd", 0, 0);
1995         if(!mvhd)
1996         {
1997             bo_free(moov);
1998             return NULL;
1999         }
2000         bo_add_32be(mvhd, i_timestamp);   // creation time
2001         bo_add_32be(mvhd, i_timestamp);   // modification time
2002         bo_add_32be(mvhd, i_movie_timescale);  // timescale
2003         bo_add_32be(mvhd, i_movie_duration);  // duration
2004     } else {
2005         mvhd = box_full_new("mvhd", 1, 0);
2006         if(!mvhd)
2007         {
2008             bo_free(moov);
2009             return NULL;
2010         }
2011         bo_add_64be(mvhd, i_timestamp);   // creation time
2012         bo_add_64be(mvhd, i_timestamp);   // modification time
2013         bo_add_32be(mvhd, i_movie_timescale);  // timescale
2014         bo_add_64be(mvhd, i_movie_duration);  // duration
2015     }
2016     bo_add_32be(mvhd, 0x10000);           // rate
2017     bo_add_16be(mvhd, 0x100);             // volume
2018     bo_add_16be(mvhd, 0);                 // reserved
2019     for (int i = 0; i < 2; i++)
2020         bo_add_32be(mvhd, 0);             // reserved
2021
2022     uint32_t mvhd_matrix[9] = { 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000 };
2023
2024     for (int i = 0; i < 9; i++)
2025         bo_add_32be(mvhd, mvhd_matrix[i]);// matrix
2026     for (int i = 0; i < 6; i++)
2027         bo_add_32be(mvhd, 0);             // pre-defined
2028
2029     /* Next available track id */
2030     bo_add_32be(mvhd, p_sys->i_nb_streams + 1); // next-track-id
2031
2032     box_gather(moov, mvhd);
2033
2034     for (unsigned int i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++) {
2035         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
2036
2037         mtime_t i_stream_duration;
2038         if ( !p_sys->b_fragmented )
2039             i_stream_duration = p_stream->i_read_duration * i_movie_timescale / CLOCK_FREQ;
2040         else
2041             i_stream_duration = 0;
2042
2043         /* *** add /moov/trak *** */
2044         bo_t *trak = box_new("trak");
2045         if(!trak)
2046             continue;
2047
2048         /* *** add /moov/trak/tkhd *** */
2049         bo_t *tkhd;
2050         if (!p_sys->b_64_ext) {
2051             if (p_sys->b_mov)
2052                 tkhd = box_full_new("tkhd", 0, 0x0f);
2053             else
2054                 tkhd = box_full_new("tkhd", 0, 1);
2055             if(!tkhd)
2056             {
2057                 bo_free(trak);
2058                 continue;
2059             }
2060             bo_add_32be(tkhd, i_timestamp);       // creation time
2061             bo_add_32be(tkhd, i_timestamp);       // modification time
2062             bo_add_32be(tkhd, p_stream->i_track_id);
2063             bo_add_32be(tkhd, 0);                     // reserved 0
2064             bo_add_32be(tkhd, i_stream_duration); // duration
2065         } else {
2066             if (p_sys->b_mov)
2067                 tkhd = box_full_new("tkhd", 1, 0x0f);
2068             else
2069                 tkhd = box_full_new("tkhd", 1, 1);
2070             if(!tkhd)
2071             {
2072                 bo_free(trak);
2073                 continue;
2074             }
2075             bo_add_64be(tkhd, i_timestamp);       // creation time
2076             bo_add_64be(tkhd, i_timestamp);       // modification time
2077             bo_add_32be(tkhd, p_stream->i_track_id);
2078             bo_add_32be(tkhd, 0);                     // reserved 0
2079             bo_add_64be(tkhd, i_stream_duration); // duration
2080         }
2081
2082         for (int i = 0; i < 2; i++)
2083             bo_add_32be(tkhd, 0);                 // reserved
2084         bo_add_16be(tkhd, 0);                     // layer
2085         bo_add_16be(tkhd, 0);                     // pre-defined
2086         // volume
2087         bo_add_16be(tkhd, p_stream->fmt.i_cat == AUDIO_ES ? 0x100 : 0);
2088         bo_add_16be(tkhd, 0);                     // reserved
2089         matrix_apply_rotation(&p_stream->fmt, mvhd_matrix);
2090         for (int i = 0; i < 9; i++)
2091             bo_add_32be(tkhd, mvhd_matrix[i]);    // matrix
2092         if (p_stream->fmt.i_cat == AUDIO_ES) {
2093             bo_add_32be(tkhd, 0);                 // width (presentation)
2094             bo_add_32be(tkhd, 0);                 // height(presentation)
2095         } else if (p_stream->fmt.i_cat == VIDEO_ES) {
2096             int i_width = p_stream->fmt.video.i_width << 16;
2097             if (p_stream->fmt.video.i_sar_num > 0 && p_stream->fmt.video.i_sar_den > 0) {
2098                 i_width = (int64_t)p_stream->fmt.video.i_sar_num *
2099                           ((int64_t)p_stream->fmt.video.i_width << 16) /
2100                           p_stream->fmt.video.i_sar_den;
2101             }
2102             // width (presentation)
2103             bo_add_32be(tkhd, i_width);
2104             // height(presentation)
2105             bo_add_32be(tkhd, p_stream->fmt.video.i_height << 16);
2106         } else {
2107             int i_width = 320 << 16;
2108             int i_height = 200;
2109             for (unsigned int i = 0; i < p_sys->i_nb_streams; i++) {
2110                 mp4_stream_t *tk = p_sys->pp_streams[i];
2111                 if (tk->fmt.i_cat == VIDEO_ES) {
2112                     if (tk->fmt.video.i_sar_num > 0 &&
2113                         tk->fmt.video.i_sar_den > 0)
2114                         i_width = (int64_t)tk->fmt.video.i_sar_num *
2115                                   ((int64_t)tk->fmt.video.i_width << 16) /
2116                                   tk->fmt.video.i_sar_den;
2117                     else
2118                         i_width = tk->fmt.video.i_width << 16;
2119                     i_height = tk->fmt.video.i_height;
2120                     break;
2121                 }
2122             }
2123             bo_add_32be(tkhd, i_width);     // width (presentation)
2124             bo_add_32be(tkhd, i_height << 16);    // height(presentation)
2125         }
2126
2127         box_gather(trak, tkhd);
2128
2129         /* *** add /moov/trak/edts and elst */
2130         if ( !p_sys->b_fragmented )
2131         {
2132             bo_t *elst = box_full_new("elst", p_sys->b_64_ext ? 1 : 0, 0);
2133             if(elst)
2134             {
2135                 if (p_stream->i_starttime > 0) {
2136                     bo_add_32be(elst, 2);
2137
2138                     if (p_sys->b_64_ext) {
2139                         bo_add_64be(elst, p_stream->i_starttime *
2140                                     i_movie_timescale / CLOCK_FREQ);
2141                         bo_add_64be(elst, -1);
2142                     } else {
2143                         bo_add_32be(elst, p_stream->i_starttime *
2144                                     i_movie_timescale / CLOCK_FREQ);
2145                         bo_add_32be(elst, -1);
2146                     }
2147                     bo_add_16be(elst, 1);
2148                     bo_add_16be(elst, 0);
2149                 } else {
2150                     bo_add_32be(elst, 1);
2151                 }
2152                 if (p_sys->b_64_ext) {
2153                     bo_add_64be(elst, p_stream->i_read_duration *
2154                                 i_movie_timescale / CLOCK_FREQ);
2155                     bo_add_64be(elst, 0);
2156                 } else {
2157                     bo_add_32be(elst, p_stream->i_read_duration *
2158                                 i_movie_timescale / CLOCK_FREQ);
2159                     bo_add_32be(elst, 0);
2160                 }
2161                 bo_add_16be(elst, 1);
2162                 bo_add_16be(elst, 0);
2163
2164                 bo_t *edts = box_new("edts");
2165                 if(edts)
2166                 {
2167                     box_gather(edts, elst);
2168                     box_gather(trak, edts);
2169                 }
2170                 else bo_free(elst);
2171             }
2172         }
2173
2174         /* *** add /moov/trak/mdia *** */
2175         bo_t *mdia = box_new("mdia");
2176         if(!mdia)
2177         {
2178             bo_free(trak);
2179             continue;
2180         }
2181
2182         /* media header */
2183         bo_t *mdhd;
2184         if (!p_sys->b_64_ext) {
2185             mdhd = box_full_new("mdhd", 0, 0);
2186             if(!mdhd)
2187             {
2188                 bo_free(mdia);
2189                 bo_free(trak);
2190                 continue;
2191             }
2192             bo_add_32be(mdhd, i_timestamp);   // creation time
2193             bo_add_32be(mdhd, i_timestamp);   // modification time
2194             bo_add_32be(mdhd, p_stream->i_timescale); // timescale
2195             bo_add_32be(mdhd, i_stream_duration);  // duration
2196         } else {
2197             mdhd = box_full_new("mdhd", 1, 0);
2198             if(!mdhd)
2199             {
2200                 bo_free(mdia);
2201                 bo_free(trak);
2202                 continue;
2203             }
2204             bo_add_64be(mdhd, i_timestamp);   // creation time
2205             bo_add_64be(mdhd, i_timestamp);   // modification time
2206             bo_add_32be(mdhd, p_stream->i_timescale); // timescale
2207             bo_add_64be(mdhd, i_stream_duration);  // duration
2208         }
2209
2210         if (p_stream->fmt.psz_language) {
2211             char *psz = p_stream->fmt.psz_language;
2212             const iso639_lang_t *pl = NULL;
2213             uint16_t lang = 0x0;
2214
2215             if (strlen(psz) == 2)
2216                 pl = GetLang_1(psz);
2217             else if (strlen(psz) == 3) {
2218                 pl = GetLang_2B(psz);
2219                 if (!strcmp(pl->psz_iso639_1, "??"))
2220                     pl = GetLang_2T(psz);
2221             }
2222
2223             if (pl && strcmp(pl->psz_iso639_1, "??"))
2224                 lang = ((pl->psz_iso639_2T[0] - 0x60) << 10) |
2225                        ((pl->psz_iso639_2T[1] - 0x60) <<  5) |
2226                        ((pl->psz_iso639_2T[2] - 0x60));
2227             bo_add_16be(mdhd, lang);          // language
2228         } else
2229             bo_add_16be(mdhd, 0   );          // language
2230         bo_add_16be(mdhd, 0   );              // predefined
2231         box_gather(mdia, mdhd);
2232
2233         /* handler reference */
2234         bo_t *hdlr = box_full_new("hdlr", 0, 0);
2235         if(!hdlr)
2236         {
2237             bo_free(mdia);
2238             bo_free(trak);
2239             continue;
2240         }
2241
2242         if (p_sys->b_mov)
2243             bo_add_fourcc(hdlr, "mhlr");         // media handler
2244         else
2245             bo_add_32be(hdlr, 0);
2246
2247         if (p_stream->fmt.i_cat == AUDIO_ES)
2248             bo_add_fourcc(hdlr, "soun");
2249         else if (p_stream->fmt.i_cat == VIDEO_ES)
2250             bo_add_fourcc(hdlr, "vide");
2251         else if (p_stream->fmt.i_cat == SPU_ES)
2252             bo_add_fourcc(hdlr, "text");
2253
2254         bo_add_32be(hdlr, 0);         // reserved
2255         bo_add_32be(hdlr, 0);         // reserved
2256         bo_add_32be(hdlr, 0);         // reserved
2257
2258         if (p_sys->b_mov)
2259             bo_add_8(hdlr, 12);   /* Pascal string for .mov */
2260
2261         if (p_stream->fmt.i_cat == AUDIO_ES)
2262             bo_add_mem(hdlr, 12, (uint8_t*)"SoundHandler");
2263         else if (p_stream->fmt.i_cat == VIDEO_ES)
2264             bo_add_mem(hdlr, 12, (uint8_t*)"VideoHandler");
2265         else
2266             bo_add_mem(hdlr, 12, (uint8_t*)"Text Handler");
2267
2268         if (!p_sys->b_mov)
2269             bo_add_8(hdlr, 0);   /* asciiz string for .mp4, yes that's BRAIN DAMAGED F**K MP4 */
2270
2271         box_gather(mdia, hdlr);
2272
2273         /* minf*/
2274         bo_t *minf = box_new("minf");
2275         if(!minf)
2276         {
2277             bo_free(mdia);
2278             bo_free(trak);
2279             continue;
2280         }
2281
2282         /* add smhd|vmhd */
2283         if (p_stream->fmt.i_cat == AUDIO_ES) {
2284             bo_t *smhd = box_full_new("smhd", 0, 0);
2285             if(smhd)
2286             {
2287                 bo_add_16be(smhd, 0);     // balance
2288                 bo_add_16be(smhd, 0);     // reserved
2289
2290                 box_gather(minf, smhd);
2291             }
2292         } else if (p_stream->fmt.i_cat == VIDEO_ES) {
2293             bo_t *vmhd = box_full_new("vmhd", 0, 1);
2294             if(vmhd)
2295             {
2296                 bo_add_16be(vmhd, 0);     // graphicsmode
2297                 for (int i = 0; i < 3; i++)
2298                     bo_add_16be(vmhd, 0); // opcolor
2299                 box_gather(minf, vmhd);
2300             }
2301         } else if (p_stream->fmt.i_cat == SPU_ES) {
2302             bo_t *gmin = box_full_new("gmin", 0, 1);
2303             if(gmin)
2304             {
2305                 bo_add_16be(gmin, 0);     // graphicsmode
2306                 for (int i = 0; i < 3; i++)
2307                     bo_add_16be(gmin, 0); // opcolor
2308                 bo_add_16be(gmin, 0);     // balance
2309                 bo_add_16be(gmin, 0);     // reserved
2310
2311                 bo_t *gmhd = box_new("gmhd");
2312                 if(gmhd)
2313                 {
2314                     box_gather(gmhd, gmin);
2315                     box_gather(minf, gmhd);
2316                 }
2317                 else bo_free(gmin);
2318             }
2319         }
2320
2321         /* dinf */
2322         bo_t *dref = box_full_new("dref", 0, 0);
2323         if(dref)
2324         {
2325             bo_add_32be(dref, 1);
2326
2327             bo_t *url = box_full_new("url ", 0, 0x01);
2328             if(url)
2329                 box_gather(dref, url);
2330
2331             bo_t *dinf = box_new("dinf");
2332             if(dinf)
2333             {
2334                 box_gather(dinf, dref);
2335
2336                 /* append dinf to mdia */
2337                 box_gather(minf, dinf);
2338             }
2339             else bo_free(dinf);
2340         }
2341
2342         /* add stbl */
2343         bo_t *stbl;
2344         if ( p_sys->b_fragmented )
2345         {
2346             uint32_t i_backup = p_stream->i_entry_count;
2347             p_stream->i_entry_count = 0;
2348             stbl = GetStblBox(p_mux, p_stream);
2349             p_stream->i_entry_count = i_backup;
2350         }
2351         else
2352             stbl = GetStblBox(p_mux, p_stream);
2353
2354         /* append stbl to minf */
2355         p_stream->i_stco_pos += minf->b->i_buffer;
2356         box_gather(minf, stbl);
2357
2358         /* append minf to mdia */
2359         p_stream->i_stco_pos += mdia->b->i_buffer;
2360         box_gather(mdia, minf);
2361
2362         /* append mdia to trak */
2363         p_stream->i_stco_pos += trak->b->i_buffer;
2364         box_gather(trak, mdia);
2365
2366         /* append trak to moov */
2367         p_stream->i_stco_pos += moov->b->i_buffer;
2368         box_gather(moov, trak);
2369     }
2370
2371     /* Add user data tags */
2372     box_gather(moov, GetUdtaTag(p_mux));
2373
2374     if ( p_sys->b_fragmented )
2375     {
2376         bo_t *mvex = box_new("mvex");
2377         for (unsigned int i_trak = 0; mvex && i_trak < p_sys->i_nb_streams; i_trak++)
2378         {
2379             mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
2380
2381             /* Try to find some defaults */
2382             if ( p_stream->i_entry_count )
2383             {
2384                 // FIXME: find highest occurence
2385                 p_stream->i_trex_length = p_stream->entry[0].i_length;
2386                 p_stream->i_trex_size = p_stream->entry[0].i_size;
2387             }
2388
2389             /* *** add /mvex/trex *** */
2390             bo_t *trex = box_full_new("trex", 0, 0);
2391             bo_add_32be(trex, p_stream->i_track_id);
2392             bo_add_32be(trex, 1); // sample desc index
2393             bo_add_32be(trex, (uint64_t)p_stream->i_trex_length * p_stream->i_timescale / CLOCK_FREQ); // sample duration
2394             bo_add_32be(trex, p_stream->i_trex_size); // sample size
2395             bo_add_32be(trex, 0); // sample flags
2396             box_gather(mvex, trex);
2397         }
2398         box_gather(moov, mvex);
2399     }
2400
2401     if(moov->b)
2402         box_fix(moov, moov->b->i_buffer);
2403     return moov;
2404 }
2405
2406 /****************************************************************************/
2407
2408 static bo_t *box_new(const char *fcc)
2409 {
2410     bo_t *box = malloc(sizeof(*box));
2411     if (!box)
2412         return NULL;
2413
2414     bo_init(box, 1024);
2415
2416     bo_add_32be  (box, 0);
2417     bo_add_fourcc(box, fcc);
2418
2419     return box;
2420 }
2421
2422 static bo_t *box_full_new(const char *fcc, uint8_t v, uint32_t f)
2423 {
2424     bo_t *box = box_new(fcc);
2425     if (!box)
2426         return NULL;
2427
2428     bo_add_8     (box, v);
2429     bo_add_24be  (box, f);
2430
2431     return box;
2432 }
2433
2434 static void box_fix(bo_t *box, uint32_t i_size)
2435 {
2436     bo_set_32be(box, 0, i_size);
2437 }
2438
2439 static void box_gather (bo_t *box, bo_t *box2)
2440 {
2441     if(box2 && box2->b && box && box->b)
2442     {
2443         box_fix(box2, box2->b->i_buffer);
2444         size_t i_offset = box->b->i_buffer;
2445         box->b = block_Realloc(box->b, 0, box->b->i_buffer + box2->b->i_buffer);
2446         memcpy(&box->b->p_buffer[i_offset], box2->b->p_buffer, box2->b->i_buffer);
2447     }
2448     bo_free(box2);
2449 }
2450
2451 static void box_send(sout_mux_t *p_mux,  bo_t *box)
2452 {
2453     if(box && box->b)
2454         sout_AccessOutWrite(p_mux->p_access, box->b);
2455     free(box);
2456 }
2457
2458 static int64_t get_timestamp(void)
2459 {
2460     int64_t i_timestamp = time(NULL);
2461
2462     i_timestamp += 2082844800; // MOV/MP4 start date is 1/1/1904
2463     // 208284480 is (((1970 - 1904) * 365) + 17) * 24 * 60 * 60
2464
2465     return i_timestamp;
2466 }
2467
2468 /***************************************************************************
2469     MP4 Live submodule
2470 ****************************************************************************/
2471 #define FRAGMENT_LENGTH  (CLOCK_FREQ * 3/2)
2472
2473 #define ENQUEUE_ENTRY(object, entry) \
2474     do {\
2475         if (object.p_last)\
2476             object.p_last->p_next = entry;\
2477         object.p_last = entry;\
2478         if (!object.p_first)\
2479             object.p_first = entry;\
2480     } while(0)
2481
2482 #define DEQUEUE_ENTRY(object, entry) \
2483     do {\
2484         entry = object.p_first;\
2485         if (object.p_last == entry)\
2486             object.p_last = NULL;\
2487         object.p_first = object.p_first->p_next;\
2488         entry->p_next = NULL;\
2489     } while(0)
2490
2491 /* Creates mfra/traf index entries */
2492 static void AddKeyframeEntry(mp4_stream_t *p_stream, const uint64_t i_moof_pos,
2493                              const uint8_t i_traf, const uint32_t i_sample,
2494                              const mtime_t i_time)
2495 {
2496     /* alloc or realloc */
2497     mp4_fragindex_t *p_entries = p_stream->p_indexentries;
2498     if (p_stream->i_indexentries >= p_stream->i_indexentriesmax)
2499     {
2500         p_stream->i_indexentriesmax += 256;
2501         p_entries = xrealloc(p_stream->p_indexentries,
2502                              p_stream->i_indexentriesmax * sizeof(mp4_fragindex_t));
2503         if (p_entries) /* realloc can fail */
2504             p_stream->p_indexentries = p_entries;
2505     }
2506
2507     mtime_t i_last_entry_time;
2508     if (p_stream->i_indexentries)
2509         i_last_entry_time = p_stream->p_indexentries[p_stream->i_indexentries - 1].i_time;
2510     else
2511         i_last_entry_time = 0;
2512
2513     if (p_entries && i_time - i_last_entry_time >= CLOCK_FREQ * 2)
2514     {
2515         mp4_fragindex_t *p_indexentry = &p_stream->p_indexentries[p_stream->i_indexentries];
2516         p_indexentry->i_time = i_time;
2517         p_indexentry->i_moofoffset = i_moof_pos;
2518         p_indexentry->i_sample = i_sample;
2519         p_indexentry->i_traf = i_traf;
2520         p_indexentry->i_trun = 1;
2521         p_stream->i_indexentries++;
2522     }
2523 }
2524
2525 /* Creates moof box and traf/trun information.
2526  * Single run per traf is absolutely not optimal as interleaving should be done
2527  * using runs and not limiting moof size, but creating an relative offset only
2528  * requires base_offset_is_moof and then comply to late iso brand spec which
2529  * breaks clients. */
2530 static bo_t *GetMoofBox(sout_mux_t *p_mux, size_t *pi_mdat_total_size,
2531                         mtime_t i_barrier_time, const uint64_t i_write_pos)
2532 {
2533     sout_mux_sys_t *p_sys = p_mux->p_sys;
2534
2535     bo_t            *moof, *mfhd;
2536     size_t           i_fixupoffset = 0;
2537
2538     *pi_mdat_total_size = 0;
2539
2540     moof = box_new("moof");
2541     if(!moof)
2542         return NULL;
2543
2544     /* *** add /moof/mfhd *** */
2545
2546     mfhd = box_full_new("mfhd", 0, 0);
2547     if(!mfhd)
2548     {
2549         bo_free(moof);
2550         return NULL;
2551     }
2552     bo_add_32be(mfhd, p_sys->i_mfhd_sequence++);   // sequence number
2553
2554     box_gather(moof, mfhd);
2555
2556     for (unsigned int i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++)
2557     {
2558         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
2559
2560         /* *** add /moof/traf *** */
2561         bo_t *traf = box_new("traf");
2562         if(!traf)
2563             continue;
2564         uint32_t i_sample = 0;
2565         mtime_t i_time = p_stream->i_written_duration;
2566         bool b_allsamesize = true;
2567         bool b_allsamelength = true;
2568         if ( p_stream->read.p_first )
2569         {
2570             mp4_fragentry_t *p_entry = p_stream->read.p_first->p_next;
2571             while (p_entry && (b_allsamelength || b_allsamesize))
2572             {
2573                 /* compare against queue head */
2574                 b_allsamelength &= ( p_entry->p_block->i_length == p_stream->read.p_first->p_block->i_length );
2575                 b_allsamesize &= ( p_entry->p_block->i_buffer == p_stream->read.p_first->p_block->i_buffer );
2576                 p_entry = p_entry->p_next;
2577             }
2578         }
2579
2580         uint32_t i_tfhd_flags = 0x0;
2581         if (p_stream->read.p_first)
2582         {
2583             /* Current segment have all same duration value, different than trex's default */
2584             if (b_allsamelength &&
2585                 p_stream->read.p_first->p_block->i_length != p_stream->i_trex_length &&
2586                 p_stream->read.p_first->p_block->i_length)
2587                     i_tfhd_flags |= MP4_TFHD_DFLT_SAMPLE_DURATION;
2588
2589             /* Current segment have all same size value, different than trex's default */
2590             if (b_allsamesize &&
2591                 p_stream->read.p_first->p_block->i_buffer != p_stream->i_trex_size &&
2592                 p_stream->read.p_first->p_block->i_buffer)
2593                     i_tfhd_flags |= MP4_TFHD_DFLT_SAMPLE_SIZE;
2594         }
2595         else
2596         {
2597             /* We have no samples */
2598             i_tfhd_flags |= MP4_TFHD_DURATION_IS_EMPTY;
2599         }
2600
2601         /* *** add /moof/traf/tfhd *** */
2602         bo_t *tfhd = box_full_new("tfhd", 0, i_tfhd_flags);
2603         if(!tfhd)
2604         {
2605             bo_free(traf);
2606             continue;
2607         }
2608         bo_add_32be(tfhd, p_stream->i_track_id);
2609
2610         /* set the local sample duration default */
2611         if (i_tfhd_flags & MP4_TFHD_DFLT_SAMPLE_DURATION)
2612             bo_add_32be(tfhd, p_stream->read.p_first->p_block->i_length * p_stream->i_timescale / CLOCK_FREQ);
2613
2614         /* set the local sample size default */
2615         if (i_tfhd_flags & MP4_TFHD_DFLT_SAMPLE_SIZE)
2616             bo_add_32be(tfhd, p_stream->read.p_first->p_block->i_buffer);
2617
2618         box_gather(traf, tfhd);
2619
2620         /* *** add /moof/traf/tfdt *** */
2621         bo_t *tfdt = box_full_new("tfdt", 1, 0);
2622         if(!tfdt)
2623         {
2624             bo_free(traf);
2625             continue;
2626         }
2627         bo_add_64be(tfdt, p_stream->i_written_duration * p_stream->i_timescale / CLOCK_FREQ );
2628         box_gather(traf, tfdt);
2629
2630         /* *** add /moof/traf/trun *** */
2631         if (p_stream->read.p_first)
2632         {
2633             uint32_t i_trun_flags = 0x0;
2634
2635             if (p_stream->b_hasiframes && !(p_stream->read.p_first->p_block->i_flags & BLOCK_FLAG_TYPE_I))
2636                 i_trun_flags |= MP4_TRUN_FIRST_FLAGS;
2637
2638             if (!b_allsamelength ||
2639                 ( !(i_tfhd_flags & MP4_TFHD_DFLT_SAMPLE_DURATION) && p_stream->i_trex_length == 0 ))
2640                 i_trun_flags |= MP4_TRUN_SAMPLE_DURATION;
2641
2642             if (!b_allsamesize ||
2643                 ( !(i_tfhd_flags & MP4_TFHD_DFLT_SAMPLE_SIZE) && p_stream->i_trex_size == 0 ))
2644                 i_trun_flags |= MP4_TRUN_SAMPLE_SIZE;
2645
2646             if (p_stream->b_hasbframes)
2647                 i_trun_flags |= MP4_TRUN_SAMPLE_TIME_OFFSET;
2648
2649             if (i_fixupoffset == 0)
2650                 i_trun_flags |= MP4_TRUN_DATA_OFFSET;
2651
2652             bo_t *trun = box_full_new("trun", 0, i_trun_flags);
2653             if(!trun)
2654             {
2655                 bo_free(traf);
2656                 continue;
2657             }
2658
2659             /* count entries */
2660             uint32_t i_entry_count = 0;
2661             mtime_t i_run_time = p_stream->i_written_duration;
2662             mp4_fragentry_t *p_entry = p_stream->read.p_first;
2663             while(p_entry)
2664             {
2665                 if ( i_barrier_time && i_run_time + p_entry->p_block->i_length > i_barrier_time )
2666                     break;
2667                 i_entry_count++;
2668                 i_run_time += p_entry->p_block->i_length;
2669                 p_entry = p_entry->p_next;
2670             }
2671             bo_add_32be(trun, i_entry_count); // sample count
2672
2673             if (i_trun_flags & MP4_TRUN_DATA_OFFSET)
2674             {
2675                 i_fixupoffset = moof->b->i_buffer + traf->b->i_buffer + trun->b->i_buffer;
2676                 bo_add_32be(trun, 0xdeadbeef); // data offset
2677             }
2678
2679             if (i_trun_flags & MP4_TRUN_FIRST_FLAGS)
2680                 bo_add_32be(trun, 1<<16); // flag as non keyframe
2681
2682             while(p_stream->read.p_first && i_entry_count)
2683             {
2684                 DEQUEUE_ENTRY(p_stream->read, p_entry);
2685
2686                 if (i_trun_flags & MP4_TRUN_SAMPLE_DURATION)
2687                     bo_add_32be(trun, p_entry->p_block->i_length * p_stream->i_timescale / CLOCK_FREQ); // sample duration
2688
2689                 if (i_trun_flags & MP4_TRUN_SAMPLE_SIZE)
2690                     bo_add_32be(trun, p_entry->p_block->i_buffer); // sample size
2691
2692                 if (i_trun_flags & MP4_TRUN_SAMPLE_TIME_OFFSET)
2693                 {
2694                     uint32_t i_diff = 0;
2695                     if ( p_entry->p_block->i_dts  > VLC_TS_INVALID &&
2696                          p_entry->p_block->i_pts > p_entry->p_block->i_dts )
2697                     {
2698                         i_diff = p_entry->p_block->i_pts - p_entry->p_block->i_dts;
2699                     }
2700                     bo_add_32be(trun, i_diff * p_stream->i_timescale / CLOCK_FREQ); // ctts
2701                 }
2702
2703                 *pi_mdat_total_size += p_entry->p_block->i_buffer;
2704
2705                 ENQUEUE_ENTRY(p_stream->towrite, p_entry);
2706                 i_entry_count--;
2707                 i_sample++;
2708
2709                 /* Add keyframe entry if needed */
2710                 if (p_stream->b_hasiframes && (p_entry->p_block->i_flags & BLOCK_FLAG_TYPE_I) &&
2711                     (p_stream->fmt.i_cat == VIDEO_ES || p_stream->fmt.i_cat == AUDIO_ES))
2712                 {
2713                     AddKeyframeEntry(p_stream, i_write_pos, i_trak, i_sample, i_time);
2714                 }
2715
2716                 i_time += p_entry->p_block->i_length;
2717             }
2718
2719             box_gather(traf, trun);
2720         }
2721
2722         box_gather(moof, traf);
2723     }
2724
2725     if(!moof->b)
2726     {
2727         bo_free(moof);
2728         return NULL;
2729     }
2730
2731     box_fix(moof, moof->b->i_buffer);
2732
2733     /* do tfhd base data offset fixup */
2734     if (i_fixupoffset)
2735     {
2736         /* mdat will follow moof */
2737         bo_set_32be(moof, i_fixupoffset, moof->b->i_buffer + 8);
2738     }
2739
2740     /* set iframe flag, so the streaming server always starts from moof */
2741     moof->b->i_flags |= BLOCK_FLAG_TYPE_I;
2742
2743     return moof;
2744 }
2745
2746 static void WriteFragmentMDAT(sout_mux_t *p_mux, size_t i_total_size)
2747 {
2748     sout_mux_sys_t *p_sys = p_mux->p_sys;
2749
2750     /* Now add mdat header */
2751     bo_t *mdat = box_new("mdat");
2752     if(!mdat)
2753         return;
2754     /* force update of real size */
2755     assert(mdat->b->i_buffer==8);
2756     box_fix(mdat, mdat->b->i_buffer + i_total_size);
2757     p_sys->i_pos += mdat->b->i_buffer;
2758     /* only write header */
2759     sout_AccessOutWrite(p_mux->p_access, mdat->b);
2760     free(mdat);
2761     /* Header and its size are written and good, now write content */
2762     for (unsigned int i_trak = 0; i_trak < p_sys->i_nb_streams; i_trak++)
2763     {
2764         mp4_stream_t *p_stream = p_sys->pp_streams[i_trak];
2765
2766         while(p_stream->towrite.p_first)
2767         {
2768             mp4_fragentry_t *p_entry = p_stream->towrite.p_first;
2769             p_sys->i_pos += p_entry->p_block->i_buffer;
2770             p_stream->i_written_duration += p_entry->p_block->i_length;
2771
2772             p_entry->p_block->i_flags &= ~BLOCK_FLAG_TYPE_I; // clear flag for http stream
2773             sout_AccessOutWrite(p_mux->p_access, p_entry->p_block);
2774
2775             p_stream->towrite.p_first = p_entry->p_next;
2776             free(p_entry);
2777             if (!p_stream->towrite.p_first)
2778                 p_stream->towrite.p_last = NULL;
2779         }
2780     }
2781 }
2782
2783 static bo_t *GetMfraBox(sout_mux_t *p_mux)
2784 {
2785     sout_mux_sys_t *p_sys = (sout_mux_sys_t*) p_mux->p_sys;
2786     bo_t *mfra = NULL;
2787     for (unsigned int i = 0; i < p_sys->i_nb_streams; i++)
2788     {
2789         mp4_stream_t *p_stream = p_sys->pp_streams[i];
2790         if (p_stream->i_indexentries)
2791         {
2792             bo_t *tfra = box_full_new("tfra", 0, 0x0);
2793             if (!tfra) continue;
2794             bo_add_32be(tfra, p_stream->i_track_id);
2795             bo_add_32be(tfra, 0x3); // reserved + lengths (1,1,4)=>(0,0,3)
2796             bo_add_32be(tfra, p_stream->i_indexentries);
2797             for(uint32_t i_index=0; i_index<p_stream->i_indexentries; i_index++)
2798             {
2799                 const mp4_fragindex_t *p_indexentry = &p_stream->p_indexentries[i_index];
2800                 bo_add_32be(tfra, p_indexentry->i_time);
2801                 bo_add_32be(tfra, p_indexentry->i_moofoffset);
2802                 assert(sizeof(p_indexentry->i_traf)==1); /* guard against sys changes */
2803                 assert(sizeof(p_indexentry->i_trun)==1);
2804                 assert(sizeof(p_indexentry->i_sample)==4);
2805                 bo_add_8(tfra, p_indexentry->i_traf);
2806                 bo_add_8(tfra, p_indexentry->i_trun);
2807                 bo_add_32be(tfra, p_indexentry->i_sample);
2808             }
2809
2810             if (!mfra && !(mfra = box_new("mfra")))
2811             {
2812                 bo_free(tfra);
2813                 return NULL;
2814             }
2815
2816             box_gather(mfra,tfra);
2817         }
2818     }
2819     return mfra;
2820 }
2821
2822 static void FlushHeader(sout_mux_t *p_mux)
2823 {
2824     sout_mux_sys_t *p_sys = (sout_mux_sys_t*) p_mux->p_sys;
2825
2826     /* Now add ftyp header */
2827     bo_t *ftyp = box_new("ftyp");
2828     if(!ftyp)
2829         return;
2830     bo_add_fourcc(ftyp, "isom");
2831     bo_add_32be  (ftyp, 0); // minor version
2832     if(ftyp->b)
2833         box_fix(ftyp, ftyp->b->i_buffer);
2834
2835     bo_t *moov = GetMoovBox(p_mux);
2836
2837     /* merge into a single block */
2838     box_gather(ftyp, moov);
2839
2840     /* add header flag for streaming server */
2841     ftyp->b->i_flags |= BLOCK_FLAG_HEADER;
2842     p_sys->i_pos += ftyp->b->i_buffer;
2843     box_send(p_mux, ftyp);
2844     p_sys->b_header_sent = true;
2845 }
2846
2847 static int OpenFrag(vlc_object_t *p_this)
2848 {
2849     sout_mux_t *p_mux = (sout_mux_t*) p_this;
2850     sout_mux_sys_t *p_sys = malloc(sizeof(sout_mux_sys_t));
2851     if (!p_sys)
2852         return VLC_ENOMEM;
2853
2854     p_mux->p_sys = (sout_mux_sys_t *) p_sys;
2855     p_mux->pf_control   = Control;
2856     p_mux->pf_addstream = AddStream;
2857     p_mux->pf_delstream = DelStream;
2858     p_mux->pf_mux       = MuxFrag;
2859
2860     /* unused */
2861     p_sys->b_mov        = false;
2862     p_sys->b_3gp        = false;
2863     p_sys->b_64_ext     = false;
2864     /* !unused */
2865
2866     p_sys->i_pos        = 0;
2867     p_sys->i_nb_streams = 0;
2868     p_sys->pp_streams   = NULL;
2869     p_sys->i_mdat_pos   = 0;
2870     p_sys->i_read_duration   = 0;
2871     p_sys->i_written_duration= 0;
2872
2873     p_sys->b_header_sent = false;
2874     p_sys->b_fragmented  = true;
2875     p_sys->i_mfhd_sequence = 1;
2876
2877     return VLC_SUCCESS;
2878 }
2879
2880 static void WriteFragments(sout_mux_t *p_mux, bool b_flush)
2881 {
2882     sout_mux_sys_t *p_sys = (sout_mux_sys_t*) p_mux->p_sys;
2883     bo_t *moof = NULL;
2884     mtime_t i_barrier_time = p_sys->i_written_duration + FRAGMENT_LENGTH;
2885     size_t i_mdat_size = 0;
2886     bool b_has_samples = false;
2887
2888     for (unsigned int i = 0; i < p_sys->i_nb_streams; i++)
2889     {
2890         const mp4_stream_t *p_stream = p_sys->pp_streams[i];
2891         if (p_stream->read.p_first)
2892         {
2893             b_has_samples = true;
2894
2895             /* set a barrier so we try to align to keyframe */
2896             if (p_stream->b_hasiframes &&
2897                     p_stream->i_last_iframe_time > p_stream->i_written_duration &&
2898                     (p_stream->fmt.i_cat == VIDEO_ES ||
2899                      p_stream->fmt.i_cat == AUDIO_ES) )
2900             {
2901                 i_barrier_time = __MIN(i_barrier_time, p_stream->i_last_iframe_time);
2902             }
2903         }
2904     }
2905
2906     if (!p_sys->b_header_sent)
2907         FlushHeader(p_mux);
2908
2909     if (b_has_samples)
2910         moof = GetMoofBox(p_mux, &i_mdat_size, (b_flush)?0:i_barrier_time, p_sys->i_pos);
2911
2912     if (moof && i_mdat_size == 0)
2913     {
2914         block_Release(moof->b);
2915         FREENULL(moof);
2916     }
2917
2918     if (moof)
2919     {
2920         msg_Dbg(p_mux, "writing moof @ %"PRId64, p_sys->i_pos);
2921         p_sys->i_pos += moof->b->i_buffer;
2922         assert(moof->b->i_flags & BLOCK_FLAG_TYPE_I); /* http sout */
2923         box_send(p_mux, moof);
2924         msg_Dbg(p_mux, "writing mdat @ %"PRId64, p_sys->i_pos);
2925         WriteFragmentMDAT(p_mux, i_mdat_size);
2926
2927         /* update iframe point */
2928         for (unsigned int i = 0; i < p_sys->i_nb_streams; i++)
2929         {
2930             mp4_stream_t *p_stream = p_sys->pp_streams[i];
2931             p_stream->i_last_iframe_time = 0;
2932         }
2933     }
2934 }
2935
2936 /* Do an entry length fixup using only its own info.
2937  * This is the end boundary case. */
2938 static void LengthLocalFixup(sout_mux_t *p_mux, const mp4_stream_t *p_stream, block_t *p_entrydata)
2939 {
2940     if ( p_stream->fmt.i_cat == VIDEO_ES )
2941     {
2942         p_entrydata->i_length = CLOCK_FREQ *
2943                 p_stream->fmt.video.i_frame_rate_base /
2944                 p_stream->fmt.video.i_frame_rate;
2945         msg_Dbg(p_mux, "video track %d fixup to %"PRId64" for sample %u",
2946                 p_stream->i_track_id, p_entrydata->i_length, p_stream->i_entry_count - 1);
2947     }
2948     else if (p_stream->fmt.i_cat == AUDIO_ES &&
2949              p_stream->fmt.audio.i_rate &&
2950              p_entrydata->i_nb_samples)
2951     {
2952         p_entrydata->i_length = CLOCK_FREQ * p_entrydata->i_nb_samples /
2953                 p_stream->fmt.audio.i_rate;
2954         msg_Dbg(p_mux, "audio track %d fixup to %"PRId64" for sample %u",
2955                 p_stream->i_track_id, p_entrydata->i_length, p_stream->i_entry_count - 1);
2956     }
2957     else
2958     {
2959         msg_Warn(p_mux, "unknown length for track %d sample %u",
2960                  p_stream->i_track_id, p_stream->i_entry_count - 1);
2961         p_entrydata->i_length = 1;
2962     }
2963 }
2964
2965 static void CleanupFrag(sout_mux_sys_t *p_sys)
2966 {
2967     for (unsigned int i = 0; i < p_sys->i_nb_streams; i++)
2968     {
2969         mp4_stream_t *p_stream = p_sys->pp_streams[i];
2970         if (p_stream->p_held_entry)
2971         {
2972             block_Release(p_stream->p_held_entry->p_block);
2973             free(p_stream->p_held_entry);
2974         }
2975         while(p_stream->read.p_first)
2976         {
2977             mp4_fragentry_t *p_next = p_stream->read.p_first->p_next;
2978             block_Release(p_stream->read.p_first->p_block);
2979             free(p_stream->read.p_first);
2980             p_stream->read.p_first = p_next;
2981         }
2982         while(p_stream->towrite.p_first)
2983         {
2984             mp4_fragentry_t *p_next = p_stream->towrite.p_first->p_next;
2985             block_Release(p_stream->towrite.p_first->p_block);
2986             free(p_stream->towrite.p_first);
2987             p_stream->towrite.p_first = p_next;
2988         }
2989         free(p_stream->p_indexentries);
2990     }
2991     free(p_sys);
2992 }
2993
2994 static void CloseFrag(vlc_object_t *p_this)
2995 {
2996     sout_mux_t *p_mux = (sout_mux_t *) p_this;
2997     sout_mux_sys_t *p_sys = (sout_mux_sys_t*) p_mux->p_sys;
2998
2999     /* Flush remaining entries */
3000     for (unsigned int i = 0; i < p_sys->i_nb_streams; i++)
3001     {
3002         mp4_stream_t *p_stream = p_sys->pp_streams[i];
3003         if (p_stream->p_held_entry)
3004         {
3005             if (p_stream->p_held_entry->p_block->i_length < 1)
3006                 LengthLocalFixup(p_mux, p_stream, p_stream->p_held_entry->p_block);
3007             ENQUEUE_ENTRY(p_stream->read, p_stream->p_held_entry);
3008             p_stream->p_held_entry = NULL;
3009         }
3010     }
3011
3012     /* and force creating a fragment from it */
3013     WriteFragments(p_mux, true);
3014
3015     /* Write indexes, but only for non streamed content
3016        as they refer to moof by absolute position */
3017     if (!strcmp(p_mux->psz_mux, "mp4frag"))
3018     {
3019         bo_t *mfra = GetMfraBox(p_mux);
3020         if (mfra)
3021         {
3022             bo_t *mfro = box_full_new("mfro", 0, 0x0);
3023             if (mfro && mfra->b)
3024             {
3025                 box_fix(mfra, mfra->b->i_buffer);
3026                 bo_add_32be(mfro, mfra->b->i_buffer + MP4_MFRO_BOXSIZE);
3027                 box_gather(mfra, mfro);
3028             }
3029             box_send(p_mux, mfra);
3030         }
3031     }
3032
3033     CleanupFrag(p_sys);
3034 }
3035
3036 static int MuxFrag(sout_mux_t *p_mux)
3037 {
3038     sout_mux_sys_t *p_sys = (sout_mux_sys_t*) p_mux->p_sys;
3039
3040     int i_stream = sout_MuxGetStream(p_mux, 1, NULL);
3041     if (i_stream < 0)
3042         return VLC_SUCCESS;
3043     sout_input_t *p_input  = p_mux->pp_inputs[i_stream];
3044     mp4_stream_t *p_stream = (mp4_stream_t*) p_input->p_sys;
3045     block_t *p_currentblock = block_FifoGet(p_input->p_fifo);
3046
3047     /* do block conversion */
3048     switch(p_stream->fmt.i_codec)
3049     {
3050     case VLC_CODEC_H264:
3051     case VLC_CODEC_HEVC:
3052         p_currentblock = ConvertFromAnnexB(p_currentblock);
3053         break;
3054     case VLC_CODEC_SUBT:
3055         p_currentblock = ConvertSUBT(p_currentblock);
3056         break;
3057     default:
3058         break;
3059     }
3060
3061     if( !p_currentblock )
3062         return VLC_ENOMEM;
3063
3064     /* If we have a previous entry for outgoing queue */
3065     if (p_stream->p_held_entry)
3066     {
3067         block_t *p_heldblock = p_stream->p_held_entry->p_block;
3068
3069         /* Fix previous block length from current */
3070         if (p_heldblock->i_length < 1)
3071         {
3072
3073             /* Fix using dts if not on a boundary */
3074             if ((p_currentblock->i_flags & BLOCK_FLAG_DISCONTINUITY) == 0)
3075                 p_heldblock->i_length = p_currentblock->i_dts - p_heldblock->i_dts;
3076
3077             if (p_heldblock->i_length < 1)
3078                 LengthLocalFixup(p_mux, p_stream, p_heldblock);
3079         }
3080
3081         /* enqueue */
3082         ENQUEUE_ENTRY(p_stream->read, p_stream->p_held_entry);
3083         p_stream->p_held_entry = NULL;
3084
3085         if (p_stream->b_hasiframes && (p_heldblock->i_flags & BLOCK_FLAG_TYPE_I) &&
3086             p_stream->i_read_duration - p_sys->i_written_duration < FRAGMENT_LENGTH)
3087         {
3088             /* Flag the last iframe time, we'll use it as boundary so it will start
3089                next fragment */
3090             p_stream->i_last_iframe_time = p_stream->i_read_duration;
3091         }
3092
3093         /* update buffered time */
3094         p_stream->i_read_duration += __MAX(0, p_heldblock->i_length);
3095     }
3096
3097
3098     /* set temp entry */
3099     p_stream->p_held_entry = malloc(sizeof(mp4_fragentry_t));
3100     if (unlikely(!p_stream->p_held_entry))
3101         return VLC_ENOMEM;
3102
3103     p_stream->p_held_entry->p_block  = p_currentblock;
3104     p_stream->p_held_entry->i_run    = p_stream->i_current_run;
3105     p_stream->p_held_entry->p_next   = NULL;
3106
3107     if (p_stream->fmt.i_cat == VIDEO_ES )
3108     {
3109         if (!p_stream->b_hasiframes && (p_currentblock->i_flags & BLOCK_FLAG_TYPE_I))
3110             p_stream->b_hasiframes = true;
3111
3112         if (!p_stream->b_hasbframes && p_currentblock->i_dts > VLC_TS_INVALID &&
3113             p_currentblock->i_pts > p_currentblock->i_dts)
3114             p_stream->b_hasbframes = true;
3115     }
3116
3117     /* Update the global fragment/media duration */
3118     mtime_t i_min_read_duration = p_stream->i_read_duration;
3119     mtime_t i_min_written_duration = p_stream->i_written_duration;
3120     for (unsigned int i=0; i<p_sys->i_nb_streams; i++)
3121     {
3122         const mp4_stream_t *p_s = p_sys->pp_streams[i];
3123         if (p_s->fmt.i_cat != VIDEO_ES && p_s->fmt.i_cat != AUDIO_ES)
3124             continue;
3125         if (p_s->i_read_duration < i_min_read_duration)
3126             i_min_read_duration = p_s->i_read_duration;
3127
3128         if (p_s->i_written_duration < i_min_written_duration)
3129             i_min_written_duration = p_s->i_written_duration;
3130     }
3131     p_sys->i_read_duration = i_min_read_duration;
3132     p_sys->i_written_duration = i_min_written_duration;
3133
3134     /* we have prerolled enough to know all streams, and have enough date to create a fragment */
3135     if (p_stream->read.p_first && p_sys->i_read_duration - p_sys->i_written_duration >= FRAGMENT_LENGTH)
3136         WriteFragments(p_mux, false);
3137
3138     return VLC_SUCCESS;
3139 }