libmp4mux.c 58.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************
 * libmp4mux.c: mp4/mov muxer
 *****************************************************************************
 * Copyright (C) 2001, 2002, 2003, 2006, 20115 VLC authors and VideoLAN
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
 *          Gildas Bazin <gbazin at videolan dot org>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/
23 24 25 26
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

27 28
#include "libmp4mux.h"
#include "../demux/mp4/libmp4.h" /* flags */
29
#include "../packetizer/hevc_nal.h"
30
#include "../packetizer/h264_nal.h" /* h264_AnnexB_get_spspps */
31
#include "../packetizer/hxxx_nal.h"
32 33 34

#include <vlc_es.h>
#include <vlc_iso_lang.h>
35
#include <vlc_bits.h>
36
#include <vlc_text_style.h>
37
#include <assert.h>
38
#include <time.h>
39

40 41
bool mp4mux_trackinfo_Init(mp4mux_trackinfo_t *p_stream, unsigned i_id,
                           uint32_t i_timescale)
42
{
43 44
    memset(p_stream, 0, sizeof(*p_stream));
    p_stream->i_track_id = i_id;
45

46
    p_stream->i_timescale   = i_timescale;
47 48
    p_stream->i_entry_count = 0;
    p_stream->i_entry_max   = 1000;
49

50 51 52 53 54 55 56 57 58 59 60 61 62
    p_stream->entry         = calloc(p_stream->i_entry_max, sizeof(mp4mux_entry_t));
    if(!p_stream->entry)
        return false;

    return true;
}

void mp4mux_trackinfo_Clear(mp4mux_trackinfo_t *p_stream)
{
    es_format_Clean(&p_stream->fmt);
    if (p_stream->a52_frame)
        block_Release(p_stream->a52_frame);
    free(p_stream->entry);
63
    free(p_stream->p_edits);
64 65 66 67 68 69 70 71 72
}


bo_t *box_new(const char *fcc)
{
    bo_t *box = malloc(sizeof(*box));
    if (!box)
        return NULL;

73 74 75 76 77
    if(!bo_init(box, 1024))
    {
        bo_free(box);
        return NULL;
    }
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105

    bo_add_32be  (box, 0);
    bo_add_fourcc(box, fcc);

    return box;
}

bo_t *box_full_new(const char *fcc, uint8_t v, uint32_t f)
{
    bo_t *box = box_new(fcc);
    if (!box)
        return NULL;

    bo_add_8     (box, v);
    bo_add_24be  (box, f);

    return box;
}

void box_fix(bo_t *box, uint32_t i_size)
{
    bo_set_32be(box, 0, i_size);
}

void box_gather (bo_t *box, bo_t *box2)
{
    if(box2 && box2->b && box && box->b)
    {
106 107
        box_fix(box2, bo_size( box2 ));
        size_t i_offset = bo_size( box );
108
        box->b = block_Realloc(box->b, 0, box->b->i_buffer + box2->b->i_buffer);
109 110
        if(likely(box->b))
            memcpy(&box->b->p_buffer[i_offset], box2->b->p_buffer, box2->b->i_buffer);
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    }
    bo_free(box2);
}

static inline void bo_add_mp4_tag_descr(bo_t *box, uint8_t tag, uint32_t size)
{
    bo_add_8(box, tag);
    for (int i = 3; i>0; i--)
        bo_add_8(box, (size>>(7*i)) | 0x80);
    bo_add_8(box, size & 0x7F);
}

static int64_t get_timestamp(void)
{
    int64_t i_timestamp = time(NULL);

    i_timestamp += 2082844800; // MOV/MP4 start date is 1/1/1904
    // 208284480 is (((1970 - 1904) * 365) + 17) * 24 * 60 * 60

    return i_timestamp;
}

/****************************************************************************/

static void matrix_apply_rotation(es_format_t *fmt, uint32_t mvhd_matrix[9])
{
    enum video_orientation_t orientation = ORIENT_NORMAL;
    if (fmt->i_cat == VIDEO_ES)
        orientation = fmt->video.orientation;

141 142 143 144
#define ATAN(a, b) \
    do { \
        mvhd_matrix[1] = ((uint32_t)(a)) << 16; \
        mvhd_matrix[0] = ((uint32_t)(b)) << 16; \
145 146 147 148 149
    } while(0)

    switch (orientation) {
    case ORIENT_ROTATED_90:  ATAN( 1,  0); break;
    case ORIENT_ROTATED_180: ATAN( 0, -1); break;
150
    case ORIENT_ROTATED_270: ATAN(-1,  0); break;
151 152 153 154 155 156 157
    default:                 ATAN( 0,  1); break;
    }

    mvhd_matrix[3] = mvhd_matrix[0] ? 0 : 0x10000;
    mvhd_matrix[4] = mvhd_matrix[1] ? 0 : 0x10000;
}

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
static void AddEdit(bo_t *elst,
                    int64_t i_movie_scaled_duration,
                    int64_t i_media_scaled_time,
                    bool b_64_ext)
{
    if(b_64_ext)
    {
        bo_add_64be(elst, i_movie_scaled_duration);
        bo_add_64be(elst, i_media_scaled_time);
    }
    else
    {
        bo_add_32be(elst, i_movie_scaled_duration);
        bo_add_32be(elst, i_media_scaled_time);
    }
    bo_add_16be(elst, 1);
    bo_add_16be(elst, 0);
}

static bo_t *GetEDTS( mp4mux_trackinfo_t *p_track, uint32_t i_movietimescale, bool b_64_ext)
{
    if(p_track->i_edits_count == 0)
        return NULL;

    bo_t *edts = box_new("edts");
    bo_t *elst = box_full_new("elst", b_64_ext ? 1 : 0, 0);
    if(!elst || !edts)
    {
        bo_free(elst);
        bo_free(edts);
        return NULL;
    }

    uint32_t i_total_edits = p_track->i_edits_count;
    for(unsigned i=0; i<p_track->i_edits_count; i++)
    {
        /* !WARN! media time must start sample time 0, we need a -1 edit for start offsets */
        if(p_track->p_edits[i].i_start_offset)
            i_total_edits++;
    }

    bo_add_32be(elst, i_total_edits);

    for(unsigned i=0; i<p_track->i_edits_count; i++)
    {
        if(p_track->p_edits[i].i_start_offset)
        {
            AddEdit(elst,
                    p_track->p_edits[i].i_start_offset * i_movietimescale / CLOCK_FREQ,
                    -1,
                    b_64_ext);
        }

        /* !WARN AGAIN! Uses different Timescales ! */
        AddEdit(elst,
                p_track->p_edits[i].i_duration * i_movietimescale / CLOCK_FREQ,
                p_track->p_edits[i].i_start_time * p_track->i_timescale / CLOCK_FREQ,
                b_64_ext);
    }

    box_gather(edts, elst);
    return edts;
}

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
static bo_t *GetESDS(mp4mux_trackinfo_t *p_track)
{
    bo_t *esds;

    /* */
    int i_decoder_specific_info_size = (p_track->fmt.i_extra > 0) ? 5 + p_track->fmt.i_extra : 0;

    esds = box_full_new("esds", 0, 0);
    if(!esds)
        return NULL;

    /* Compute Max bitrate */
    int64_t i_bitrate_avg = 0;
    int64_t i_bitrate_max = 0;
    /* Compute avg/max bitrate */
    for (unsigned i = 0; i < p_track->i_entry_count; i++) {
        i_bitrate_avg += p_track->entry[i].i_size;
        if (p_track->entry[i].i_length > 0) {
            int64_t i_bitrate = INT64_C(8000000) * p_track->entry[i].i_size / p_track->entry[i].i_length;
            if (i_bitrate > i_bitrate_max)
                i_bitrate_max = i_bitrate;
        }
    }

    if (p_track->i_read_duration > 0)
247
        i_bitrate_avg = CLOCK_FREQ * 8 * i_bitrate_avg / p_track->i_read_duration;
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    else
        i_bitrate_avg = 0;
    if (i_bitrate_max <= 1)
        i_bitrate_max = 0x7fffffff;

    /* ES_Descr */
    bo_add_mp4_tag_descr(esds, 0x03, 3 + 5 + 13 + i_decoder_specific_info_size + 5 + 1);
    bo_add_16be(esds, p_track->i_track_id);
    bo_add_8   (esds, 0x1f);      // flags=0|streamPriority=0x1f

    /* DecoderConfigDescr */
    bo_add_mp4_tag_descr(esds, 0x04, 13 + i_decoder_specific_info_size);

    int  i_object_type_indication;
    switch(p_track->fmt.i_codec)
    {
    case VLC_CODEC_MP4V:
        i_object_type_indication = 0x20;
        break;
    case VLC_CODEC_MPGV:
        if(p_track->fmt.i_original_fourcc == VLC_CODEC_MP1V)
        {
            i_object_type_indication = 0x6b;
            break;
        }
273
        /* fallthrough */
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    case VLC_CODEC_MP2V:
        /* MPEG-I=0x6b, MPEG-II = 0x60 -> 0x65 */
        i_object_type_indication = 0x65;
        break;
    case VLC_CODEC_MP1V:
        /* MPEG-I=0x6b, MPEG-II = 0x60 -> 0x65 */
        i_object_type_indication = 0x6b;
        break;
    case VLC_CODEC_MP4A:
        /* FIXME for mpeg2-aac == 0x66->0x68 */
        i_object_type_indication = 0x40;
        break;
    case VLC_CODEC_MPGA:
        i_object_type_indication =
            p_track->fmt.audio.i_rate < 32000 ? 0x69 : 0x6b;
        break;
    case VLC_CODEC_DTS:
        i_object_type_indication = 0xa9;
        break;
    default:
294
        i_object_type_indication = 0xFE; /* No profile specified */
295 296
        break;
    }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

    uint8_t i_stream_type;
    switch(p_track->fmt.i_cat)
    {
        case VIDEO_ES:
            i_stream_type = 0x04;
            break;
        case AUDIO_ES:
            i_stream_type = 0x05;
            break;
        case SPU_ES:
            i_stream_type = 0x0D;
            break;
        default:
            i_stream_type = 0x20; /* Private */
            break;
    }
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

    bo_add_8   (esds, i_object_type_indication);
    bo_add_8   (esds, (i_stream_type << 2) | 1);
    bo_add_24be(esds, 1024 * 1024);       // bufferSizeDB
    bo_add_32be(esds, i_bitrate_max);     // maxBitrate
    bo_add_32be(esds, i_bitrate_avg);     // avgBitrate

    if (p_track->fmt.i_extra > 0) {
        /* DecoderSpecificInfo */
        bo_add_mp4_tag_descr(esds, 0x05, p_track->fmt.i_extra);

        for (int i = 0; i < p_track->fmt.i_extra; i++)
            bo_add_8(esds, ((uint8_t*)p_track->fmt.p_extra)[i]);
    }

    /* SL_Descr mandatory */
    bo_add_mp4_tag_descr(esds, 0x06, 1);
    bo_add_8    (esds, 0x02);  // sl_predefined

    return esds;
}

static bo_t *GetWaveTag(mp4mux_trackinfo_t *p_track)
{
    bo_t *wave;
    bo_t *box;

    wave = box_new("wave");
    if(wave)
    {
        box = box_new("frma");
        if(box)
        {
            bo_add_fourcc(box, "mp4a");
            box_gather(wave, box);
        }

        box = box_new("mp4a");
        if(box)
        {
            bo_add_32be(box, 0);
            box_gather(wave, box);
        }

        box = GetESDS(p_track);
        box_gather(wave, box);

        box = box_new("srcq");
        if(box)
        {
            bo_add_32be(box, 0x40);
            box_gather(wave, box);
        }

        /* wazza ? */
        bo_add_32be(wave, 8); /* new empty box */
        bo_add_32be(wave, 0); /* box label */
    }
    return wave;
}

static bo_t *GetDec3Tag(es_format_t *p_fmt, block_t *a52_frame)
{
    if (!a52_frame)
        return NULL;

    bs_t s;
381
    bs_write_init(&s, a52_frame->p_buffer, sizeof(a52_frame->i_buffer));
382 383 384 385 386 387 388 389
    bs_skip(&s, 16); // syncword

    uint8_t fscod, bsid, bsmod, acmod, lfeon, strmtyp;

    bsmod = 0;

    strmtyp = bs_read(&s, 2);

390
    if (strmtyp & 0x1) // dependent or reserved stream
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
        return NULL;

    if (bs_read(&s, 3) != 0x0) // substreamid: we don't support more than 1 stream
        return NULL;

    int numblkscod;
    bs_skip(&s, 11); // frmsizecod
    fscod = bs_read(&s, 2);
    if (fscod == 0x03) {
        bs_skip(&s, 2); // fscod2
        numblkscod = 3;
    } else {
        numblkscod = bs_read(&s, 2);
    }

    acmod = bs_read(&s, 3);
    lfeon = bs_read1(&s);

    bsid = bs_read(&s, 5);

    bs_skip(&s, 5); // dialnorm
    if (bs_read1(&s)) // compre
        bs_skip(&s, 5); // compr

    if (acmod == 0) {
        bs_skip(&s, 5); // dialnorm2
        if (bs_read1(&s)) // compr2e
            bs_skip(&s, 8); // compr2
    }

421
    if (strmtyp == 0x1) // dependent stream XXX: unsupported
422 423 424 425 426 427 428 429 430 431 432 433 434 435
        if (bs_read1(&s)) // chanmape
            bs_skip(&s, 16); // chanmap

    /* we have to skip mixing info to read bsmod */
    if (bs_read1(&s)) { // mixmdate
        if (acmod > 0x2) // 2+ channels
            bs_skip(&s, 2); // dmixmod
        if ((acmod & 0x1) && (acmod > 0x2)) // 3 front channels
            bs_skip(&s, 3 + 3); // ltrtcmixlev + lorocmixlev
        if (acmod & 0x4) // surround channel
            bs_skip(&s, 3 + 3); // ltrsurmixlev + lorosurmixlev
        if (lfeon)
            if (bs_read1(&s))
                bs_skip(&s, 5); // lfemixlevcod
436
        if (strmtyp == 0) { // independent stream
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
            if (bs_read1(&s)) // pgmscle
                bs_skip(&s, 6); // pgmscl
            if (acmod == 0x0) // dual mono
                if (bs_read1(&s)) // pgmscl2e
                    bs_skip(&s, 6); // pgmscl2
            if (bs_read1(&s)) // extpgmscle
                bs_skip(&s, 6); // extpgmscl
            uint8_t mixdef = bs_read(&s, 2);
            if (mixdef == 0x1)
                bs_skip(&s, 5);
            else if (mixdef == 0x2)
                bs_skip(&s, 12);
            else if (mixdef == 0x3) {
                uint8_t mixdeflen = bs_read(&s, 5);
                bs_skip(&s, 8 * (mixdeflen + 2));
            }
            if (acmod < 0x2) { // mono or dual mono
                if (bs_read1(&s)) // paninfoe
                    bs_skip(&s, 14); // paninfo
                if (acmod == 0) // dual mono
                    if (bs_read1(&s)) // paninfo2e
                        bs_skip(&s, 14); // paninfo2
            }
            if (bs_read1(&s)) { // frmmixcfginfoe
                static const int blocks[4] = { 1, 2, 3, 6 };
                int number_of_blocks = blocks[numblkscod];
                if (number_of_blocks == 1)
                    bs_skip(&s, 5); // blkmixcfginfo[0]
                else for (int i = 0; i < number_of_blocks; i++)
                    if (bs_read1(&s)) // blkmixcfginfoe
                        bs_skip(&s, 5); // blkmixcfginfo[i]
            }
        }
    }

    if (bs_read1(&s)) // infomdate
        bsmod = bs_read(&s, 3);

    uint8_t mp4_eac3_header[5] = {0};
    bs_init(&s, mp4_eac3_header, sizeof(mp4_eac3_header));

    int data_rate = p_fmt->i_bitrate / 1000;
    bs_write(&s, 13, data_rate);
    bs_write(&s, 3, 0); // num_ind_sub - 1
    bs_write(&s, 2, fscod);
    bs_write(&s, 5, bsid);
    bs_write(&s, 5, bsmod);
    bs_write(&s, 3, acmod);
    bs_write(&s, 1, lfeon);
    bs_write(&s, 3, 0); // reserved
    bs_write(&s, 4, 0); // num_dep_sub
    bs_write(&s, 1, 0); // reserved

    bo_t *dec3 = box_new("dec3");
    if(dec3)
        bo_add_mem(dec3, sizeof(mp4_eac3_header), mp4_eac3_header);

    return dec3;
}

static bo_t *GetDac3Tag(block_t *a52_frame)
{
    if (!a52_frame)
        return NULL;

    bo_t *dac3 = box_new("dac3");
    if(!dac3)
        return NULL;

    bs_t s;
    bs_init(&s, a52_frame->p_buffer, sizeof(a52_frame->i_buffer));

    uint8_t fscod, bsid, bsmod, acmod, lfeon, frmsizecod;

    bs_skip(&s, 16 + 16); // syncword + crc

    fscod = bs_read(&s, 2);
    frmsizecod = bs_read(&s, 6);
    bsid = bs_read(&s, 5);
    bsmod = bs_read(&s, 3);
    acmod = bs_read(&s, 3);
    if (acmod == 2)
        bs_skip(&s, 2); // dsurmod
    else {
        if ((acmod & 1) && acmod != 1)
            bs_skip(&s, 2); // cmixlev
        if (acmod & 4)
            bs_skip(&s, 2); // surmixlev
    }

    lfeon = bs_read1(&s);

    uint8_t mp4_a52_header[3];
    bs_init(&s, mp4_a52_header, sizeof(mp4_a52_header));

    bs_write(&s, 2, fscod);
    bs_write(&s, 5, bsid);
    bs_write(&s, 3, bsmod);
    bs_write(&s, 3, acmod);
    bs_write(&s, 1, lfeon);
    bs_write(&s, 5, frmsizecod >> 1); // bit_rate_code
    bs_write(&s, 5, 0); // reserved

    bo_add_mem(dac3, sizeof(mp4_a52_header), mp4_a52_header);

    return dac3;
}

static bo_t *GetDamrTag(es_format_t *p_fmt)
{
    bo_t *damr = box_new("damr");
    if(!damr)
        return NULL;

    bo_add_fourcc(damr, "REFC");
    bo_add_8(damr, 0);

    if (p_fmt->i_codec == VLC_CODEC_AMR_NB)
        bo_add_16be(damr, 0x81ff); /* Mode set (all modes for AMR_NB) */
    else
        bo_add_16be(damr, 0x83ff); /* Mode set (all modes for AMR_WB) */
    bo_add_16be(damr, 0x1); /* Mode change period (no restriction) */

    return damr;
}

static bo_t *GetD263Tag(void)
{
    bo_t *d263 = box_new("d263");
    if(!d263)
        return NULL;

    bo_add_fourcc(d263, "VLC ");
    bo_add_16be(d263, 0xa);
    bo_add_8(d263, 0);

    return d263;
}

576
static bo_t *GetHvcCTag(es_format_t *p_fmt, bool b_completeness)
577 578 579 580 581 582
{
    /* Generate hvcC box matching iso/iec 14496-15 3rd edition */
    bo_t *hvcC = box_new("hvcC");
    if(!hvcC || !p_fmt->i_extra)
        return hvcC;

583
    /* Extradata is already an HEVCDecoderConfigurationRecord */
584
    if(hevc_ishvcC(p_fmt->p_extra, p_fmt->i_extra))
585
    {
586
        (void) bo_add_mem(hvcC, p_fmt->i_extra, p_fmt->p_extra);
587 588 589
        return hvcC;
    }

590
    struct hevc_dcr_params params = { 0 };
591 592
    const uint8_t *p_nal;
    size_t i_nal;
593 594

    hxxx_iterator_ctx_t it;
595 596 597 598 599 600 601 602 603 604 605 606
    hxxx_iterator_init(&it, p_fmt->p_extra, p_fmt->i_extra, 0);
    while(hxxx_annexb_iterate_next(&it, &p_nal, &i_nal))
    {
        switch (hevc_getNALType(p_nal))
        {
            case HEVC_NAL_VPS:
                if(params.i_vps_count != HEVC_DCR_VPS_COUNT)
                {
                    params.p_vps[params.i_vps_count] = p_nal;
                    params.rgi_vps[params.i_vps_count] = i_nal;
                    params.i_vps_count++;
                }
607
                break;
608 609 610 611 612 613 614
            case HEVC_NAL_SPS:
                if(params.i_sps_count != HEVC_DCR_SPS_COUNT)
                {
                    params.p_sps[params.i_sps_count] = p_nal;
                    params.rgi_sps[params.i_sps_count] = i_nal;
                    params.i_sps_count++;
                }
615
                break;
616 617 618 619 620 621 622
            case HEVC_NAL_PPS:
                if(params.i_pps_count != HEVC_DCR_PPS_COUNT)
                {
                    params.p_pps[params.i_pps_count] = p_nal;
                    params.rgi_pps[params.i_pps_count] = i_nal;
                    params.i_pps_count++;
                }
623
                break;
624
            case HEVC_NAL_PREF_SEI:
625
                if(params.i_seipref_count != HEVC_DCR_SEI_COUNT)
626
                {
627 628 629
                    params.p_seipref[params.i_seipref_count] = p_nal;
                    params.rgi_seipref[params.i_seipref_count] = i_nal;
                    params.i_seipref_count++;
630 631
                }
                break;
632 633 634 635 636 637 638 639 640
            case HEVC_NAL_SUFF_SEI:
                if(params.i_seisuff_count != HEVC_DCR_SEI_COUNT)
                {
                    params.p_seisuff[params.i_seisuff_count] = p_nal;
                    params.rgi_seisuff[params.i_seisuff_count] = i_nal;
                    params.i_seisuff_count++;
                }
                break;

641
            default:
642 643 644 645
                break;
        }
    }

646 647 648 649 650 651
    size_t i_dcr;
    uint8_t *p_dcr = hevc_create_dcr(&params, 4, b_completeness, &i_dcr);
    if(!p_dcr)
    {
        bo_free(hvcC);
        return NULL;
652 653
    }

654 655
    bo_add_mem(hvcC, i_dcr, p_dcr);
    free(p_dcr);
656 657 658 659

    return hvcC;
}

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
static bo_t *GetWaveFormatExTag(es_format_t *p_fmt, const char *tag)
{
    bo_t *box = box_new(tag);
    if(!box)
        return NULL;

    uint16_t wFormatTag;
    fourcc_to_wf_tag(p_fmt->i_codec, &wFormatTag);
    bo_add_16le(box, wFormatTag); //wFormatTag
    bo_add_16le(box, p_fmt->audio.i_channels); //nChannels
    bo_add_32le(box, p_fmt->audio.i_rate); //nSamplesPerSec
    bo_add_32le(box, p_fmt->i_bitrate / 8); //nAvgBytesPerSec
    bo_add_16le(box, p_fmt->audio.i_blockalign); //nBlockAlign
    bo_add_16le(box, p_fmt->audio.i_bitspersample);  //wBitsPerSample
    bo_add_16le(box, p_fmt->i_extra); //cbSize

    bo_add_mem(box, p_fmt->i_extra, p_fmt->p_extra);

    return box;
}

681 682 683 684 685 686 687 688 689
static bo_t *GetxxxxTag(es_format_t *p_fmt, const char *tag)
{
    bo_t *box = box_new(tag);
    if(!box)
        return NULL;
    bo_add_mem(box, p_fmt->i_extra, p_fmt->p_extra);
    return box;
}

690 691 692 693 694
static bo_t *GetAvcCTag(es_format_t *p_fmt)
{
    bo_t    *avcC = box_new("avcC");/* FIXME use better value */
    if(!avcC)
        return NULL;
695
    const uint8_t *p_sps, *p_pps, *p_ext;
696
    size_t i_sps_size, i_pps_size, i_ext_size;
697

698
    if(! h264_AnnexB_get_spspps(p_fmt->p_extra, p_fmt->i_extra,
699 700
                        &p_sps, &i_sps_size,
                        &p_pps, &i_pps_size,
701
                        &p_ext, &i_ext_size ) )
702
    {
703 704
        p_sps = p_pps = p_ext = NULL;
        i_sps_size = i_pps_size = i_ext_size = 0;
705 706 707
    }

    bo_add_8(avcC, 1);      /* configuration version */
708 709 710
    bo_add_8(avcC, i_sps_size > 3 ? p_sps[1] : PROFILE_H264_MAIN);
    bo_add_8(avcC, i_sps_size > 3 ? p_sps[2] : 64);
    bo_add_8(avcC, i_sps_size > 3 ? p_sps[3] : 30);       /* level, 5.1 */
711 712 713 714 715 716 717 718 719 720 721 722 723 724
    bo_add_8(avcC, 0xff);   /* 0b11111100 | lengthsize = 0x11 */

    bo_add_8(avcC, 0xe0 | (i_sps_size > 0 ? 1 : 0));   /* 0b11100000 | sps_count */
    if (i_sps_size > 0) {
        bo_add_16be(avcC, i_sps_size);
        bo_add_mem(avcC, i_sps_size, p_sps);
    }

    bo_add_8(avcC, (i_pps_size > 0 ? 1 : 0));   /* pps_count */
    if (i_pps_size > 0) {
        bo_add_16be(avcC, i_pps_size);
        bo_add_mem(avcC, i_pps_size, p_pps);
    }

725 726
    if( i_sps_size > 3 &&
       (p_sps[1] == PROFILE_H264_HIGH ||
727 728 729
        p_sps[1] == PROFILE_H264_HIGH_10 ||
        p_sps[1] == PROFILE_H264_HIGH_422 ||
        p_sps[1] == PROFILE_H264_HIGH_444 ||
730
        p_sps[1] == PROFILE_H264_HIGH_444_PREDICTIVE) )
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    {
        h264_sequence_parameter_set_t *p_spsdata = h264_decode_sps( p_sps, i_sps_size, true );
        if( p_spsdata )
        {
            uint8_t data[3];
            if( h264_get_chroma_luma( p_spsdata, &data[0], &data[1], &data[2]) )
            {
                bo_add_8(avcC, 0xFC | data[0]);
                bo_add_8(avcC, 0xF8 | (data[1] - 8));
                bo_add_8(avcC, 0xF8 | (data[2] - 8));
                bo_add_8(avcC, (i_ext_size > 0 ? 1 : 0));
                if (i_ext_size > 0) {
                    bo_add_16be(avcC, i_ext_size);
                    bo_add_mem(avcC, i_ext_size, p_ext);
                }
            }
            h264_release_sps( p_spsdata );
        }
    }

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    return avcC;
}

/* TODO: No idea about these values */
static bo_t *GetSVQ3Tag(es_format_t *p_fmt)
{
    bo_t *smi = box_new("SMI ");
    if(!smi)
        return NULL;

    if (p_fmt->i_extra > 0x4e) {
        uint8_t *p_end = &((uint8_t*)p_fmt->p_extra)[p_fmt->i_extra];
        uint8_t *p     = &((uint8_t*)p_fmt->p_extra)[0x46];

        while (p + 8 < p_end) {
            int i_size = GetDWBE(p);
            if (i_size <= 1) /* FIXME handle 1 as long size */
                break;
            if (!strncmp((const char *)&p[4], "SMI ", 4)) {
                bo_add_mem(smi, p_end - p - 8, &p[8]);
                return smi;
            }
            p += i_size;
        }
    }

    /* Create a dummy one in fallback */
    bo_add_fourcc(smi, "SEQH");
    bo_add_32be(smi, 0x5);
    bo_add_32be(smi, 0xe2c0211d);
    bo_add_8(smi, 0xc0);

    return smi;
}

static bo_t *GetUdtaTag(mp4mux_trackinfo_t **pp_tracks, unsigned int i_tracks)
{
    bo_t *udta = box_new("udta");
    if (!udta)
        return NULL;

    /* Requirements */
    for (unsigned int i = 0; i < i_tracks; i++) {
        mp4mux_trackinfo_t *p_stream = pp_tracks[i];
        vlc_fourcc_t codec = p_stream->fmt.i_codec;

        if (codec == VLC_CODEC_MP4V || codec == VLC_CODEC_MP4A) {
            bo_t *box = box_new("\251req");
            if(!box)
                break;
            /* String length */
            bo_add_16be(box, sizeof("QuickTime 6.0 or greater") - 1);
            bo_add_16be(box, 0);
            bo_add_mem(box, sizeof("QuickTime 6.0 or greater") - 1,
                        (uint8_t *)"QuickTime 6.0 or greater");
            box_gather(udta, box);
            break;
        }
    }

    /* Encoder */
    {
        bo_t *box = box_new("\251enc");
        if(box)
        {
            /* String length */
            bo_add_16be(box, sizeof(PACKAGE_STRING " stream output") - 1);
            bo_add_16be(box, 0);
            bo_add_mem(box, sizeof(PACKAGE_STRING " stream output") - 1,
                        (uint8_t*)PACKAGE_STRING " stream output");
            box_gather(udta, box);
        }
    }
#if 0
    /* Misc atoms */
    vlc_meta_t *p_meta = p_mux->p_sout->p_meta;
    if (p_meta) {
#define ADD_META_BOX(type, box_string) { \
        bo_t *box = NULL;  \
        if (vlc_meta_Get(p_meta, vlc_meta_##type)) \
            box = box_new("\251" box_string); \
        if (box) { \
            bo_add_16be(box, strlen(vlc_meta_Get(p_meta, vlc_meta_##type))); \
            bo_add_16be(box, 0); \
            bo_add_mem(box, strlen(vlc_meta_Get(p_meta, vlc_meta_##type)), \
                        (uint8_t*)(vlc_meta_Get(p_meta, vlc_meta_##type))); \
            box_gather(udta, box); \
        } }

        ADD_META_BOX(Title, "nam");
        ADD_META_BOX(Artist, "ART");
        ADD_META_BOX(Genre, "gen");
        ADD_META_BOX(Copyright, "cpy");
        ADD_META_BOX(Description, "des");
        ADD_META_BOX(Date, "day");
        ADD_META_BOX(URL, "url");
#undef ADD_META_BOX
    }
#endif
    return udta;
}

static bo_t *GetSounBox(vlc_object_t *p_obj, mp4mux_trackinfo_t *p_track, bool b_mov)
{
    VLC_UNUSED(p_obj);

    bool b_descr = true;
    vlc_fourcc_t codec = p_track->fmt.i_codec;
    char fcc[4];

    if (codec == VLC_CODEC_MPGA) {
        if (b_mov) {
            b_descr = false;
            memcpy(fcc, ".mp3", 4);
        } else
            memcpy(fcc, "mp4a", 4);
    } else if (codec == VLC_CODEC_A52) {
        memcpy(fcc, "ac-3", 4);
    } else if (codec == VLC_CODEC_EAC3) {
        memcpy(fcc, "ec-3", 4);
    } else if (codec == VLC_CODEC_DTS) {
        memcpy(fcc, "DTS ", 4);
873 874
    } else if (codec == VLC_CODEC_WMAP) {
        memcpy(fcc, "wma ", 4);
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    } else
        vlc_fourcc_to_char(codec, fcc);

    bo_t *soun = box_new(fcc);
    if(!soun)
        return NULL;
    for (int i = 0; i < 6; i++)
        bo_add_8(soun, 0);        // reserved;
    bo_add_16be(soun, 1);         // data-reference-index

    /* SoundDescription */
    if (b_mov && codec == VLC_CODEC_MP4A)
        bo_add_16be(soun, 1);     // version 1;
    else
        bo_add_16be(soun, 0);     // version 0;
    bo_add_16be(soun, 0);         // revision level (0)
    bo_add_32be(soun, 0);         // vendor
    // channel-count
    bo_add_16be(soun, p_track->fmt.audio.i_channels);
    // sample size
    bo_add_16be(soun, p_track->fmt.audio.i_bitspersample ?
                 p_track->fmt.audio.i_bitspersample : 16);
    bo_add_16be(soun, -2);        // compression id
    bo_add_16be(soun, 0);         // packet size (0)
    bo_add_16be(soun, p_track->fmt.audio.i_rate); // sampleratehi
    bo_add_16be(soun, 0);                             // sampleratelo

    /* Extended data for SoundDescription V1 */
    if (b_mov && p_track->fmt.i_codec == VLC_CODEC_MP4A) {
        /* samples per packet */
        bo_add_32be(soun, p_track->fmt.audio.i_frame_length);
        bo_add_32be(soun, 1536); /* bytes per packet */
        bo_add_32be(soun, 2);    /* bytes per frame */
        /* bytes per sample */
        bo_add_32be(soun, 2 /*p_fmt->audio.i_bitspersample/8 */);
    }

    /* Add an ES Descriptor */
    if (b_descr) {
        bo_t *box;

        if (b_mov && codec == VLC_CODEC_MP4A)
            box = GetWaveTag(p_track);
        else if (codec == VLC_CODEC_AMR_NB)
            box = GetDamrTag(&p_track->fmt);
        else if (codec == VLC_CODEC_A52)
            box = GetDac3Tag(p_track->a52_frame);
        else if (codec == VLC_CODEC_EAC3)
            box = GetDec3Tag(&p_track->fmt, p_track->a52_frame);
924 925
        else if (codec == VLC_CODEC_WMAP)
            box = GetWaveFormatExTag(&p_track->fmt, "wfex");
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
        else
            box = GetESDS(p_track);

        if (box)
            box_gather(soun, box);
    }

    return soun;
}

static bo_t *GetVideBox(vlc_object_t *p_obj, mp4mux_trackinfo_t *p_track, bool b_mov)
{
    VLC_UNUSED(p_obj);
    VLC_UNUSED(b_mov);

    char fcc[4];

    switch(p_track->fmt.i_codec)
    {
    case VLC_CODEC_MP4V:
    case VLC_CODEC_MPGV: memcpy(fcc, "mp4v", 4); break;
    case VLC_CODEC_MJPG: memcpy(fcc, "mjpa", 4); break;
    case VLC_CODEC_SVQ1: memcpy(fcc, "SVQ1", 4); break;
    case VLC_CODEC_SVQ3: memcpy(fcc, "SVQ3", 4); break;
    case VLC_CODEC_H263: memcpy(fcc, "s263", 4); break;
    case VLC_CODEC_H264: memcpy(fcc, "avc1", 4); break;
952
    case VLC_CODEC_VC1 : memcpy(fcc, "vc-1", 4); break;
953 954 955
    /* FIXME: find a way to know if no non-VCL units are in the stream (->hvc1)
     * see 14496-15 8.4.1.1.1 */
    case VLC_CODEC_HEVC: memcpy(fcc, "hev1", 4); break;
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    case VLC_CODEC_YV12: memcpy(fcc, "yv12", 4); break;
    case VLC_CODEC_YUYV: memcpy(fcc, "yuy2", 4); break;
    default:
        vlc_fourcc_to_char(p_track->fmt.i_codec, fcc);
        break;
    }

    bo_t *vide = box_new(fcc);
    if(!vide)
        return NULL;
    for (int i = 0; i < 6; i++)
        bo_add_8(vide, 0);        // reserved;
    bo_add_16be(vide, 1);         // data-reference-index

    bo_add_16be(vide, 0);         // predefined;
    bo_add_16be(vide, 0);         // reserved;
    for (int i = 0; i < 3; i++)
        bo_add_32be(vide, 0);     // predefined;

    bo_add_16be(vide, p_track->fmt.video.i_width);  // i_width
    bo_add_16be(vide, p_track->fmt.video.i_height); // i_height

    bo_add_32be(vide, 0x00480000);                // h 72dpi
    bo_add_32be(vide, 0x00480000);                // v 72dpi

    bo_add_32be(vide, 0);         // data size, always 0
    bo_add_16be(vide, 1);         // frames count per sample

    // compressor name;
    for (int i = 0; i < 32; i++)
        bo_add_8(vide, 0);

    bo_add_16be(vide, 0x18);      // depth
    bo_add_16be(vide, 0xffff);    // predefined

    /* add an ES Descriptor */
    switch(p_track->fmt.i_codec)
    {
    case VLC_CODEC_MP4V:
    case VLC_CODEC_MPGV:
        box_gather(vide, GetESDS(p_track));
        break;

    case VLC_CODEC_H263:
        box_gather(vide, GetD263Tag());
        break;

    case VLC_CODEC_SVQ3:
        box_gather(vide, GetSVQ3Tag(&p_track->fmt));
        break;

    case VLC_CODEC_H264:
        box_gather(vide, GetAvcCTag(&p_track->fmt));
        break;

1011 1012 1013 1014
    case VLC_CODEC_VC1:
        box_gather(vide, GetxxxxTag(&p_track->fmt, "dvc1"));
            break;

1015
    case VLC_CODEC_HEVC:
1016 1017
        /* Write HvcC without forcing VPS/SPS/PPS/SEI array_completeness */
        box_gather(vide, GetHvcCTag(&p_track->fmt, false));
1018 1019 1020 1021 1022 1023
        break;
    }

    return vide;
}

1024
static bo_t *GetTextBox(vlc_object_t *p_obj, mp4mux_trackinfo_t *p_track, bool b_mov)
1025
{
1026
    VLC_UNUSED(p_obj);
1027
    if(p_track->fmt.i_codec == VLC_CODEC_QTXT)
1028
    {
1029
        bo_t *text = box_new("text");
1030 1031
        if(!text)
            return NULL;
1032

1033 1034 1035 1036 1037
        /* Sample Entry Header */
        for (int i = 0; i < 6; i++)
            bo_add_8(text, 0);        // reserved;
        bo_add_16be(text, 1);         // data-reference-index

1038
        if(p_track->fmt.i_extra >= 44)
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
        {
            /* Copy the original sample description format */
            bo_add_mem(text, p_track->fmt.i_extra, p_track->fmt.p_extra);
        }
        else
        {
            for (int i = 0; i < 6; i++)
                bo_add_8(text, 0);        // reserved;
            bo_add_16be(text, 1);         // data-reference-index

            bo_add_32be(text, 0);         // display flags
            bo_add_32be(text, 0);         // justification
            for (int i = 0; i < 3; i++)
1052
                bo_add_16be(text, 0);     // background color
1053

1054
            bo_add_64be(text, 0);         // box text
1055
            bo_add_64be(text, 0);         // reserved
1056 1057 1058 1059 1060 1061

            bo_add_16be(text, 0);         // font-number
            bo_add_16be(text, 0);         // font-face
            bo_add_8(text, 0);            // reserved
            bo_add_16be(text, 0);         // reserved

1062 1063 1064
            for (int i = 0; i < 3; i++)
                bo_add_16be(text, 0xff);  // foreground color

1065 1066
            bo_add_8(text, 5);
            bo_add_mem(text, 5,  (void*)"Serif");
1067
        }
1068 1069
        return text;
    }
1070 1071 1072 1073 1074 1075 1076
    else if(p_track->fmt.i_codec == VLC_CODEC_SPU ||
            p_track->fmt.i_codec == VLC_CODEC_TX3G)
    {
        bo_t *tx3g = box_new("tx3g");
        if(!tx3g)
            return NULL;

1077 1078 1079 1080 1081
        /* Sample Entry Header */
        for (int i = 0; i < 6; i++)
            bo_add_8(tx3g, 0);        // reserved;
        bo_add_16be(tx3g, 1);         // data-reference-index

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
        if(p_track->fmt.i_codec == VLC_CODEC_TX3G &&
           p_track->fmt.i_extra >= 32)
        {
            /* Copy the original sample description format */
            bo_add_mem(tx3g, p_track->fmt.i_extra, p_track->fmt.p_extra);
        }
        else /* Build TTXT(tx3g) sample desc */
        {
            /* tx3g sample description */
            bo_add_32be(tx3g, 0);         // display flags
            bo_add_16be(tx3g, 0);         // justification

            bo_add_32be(tx3g, 0);         // background color

            /* BoxRecord */
            bo_add_64be(tx3g, 0);

            /* StyleRecord*/
            bo_add_16be(tx3g, 0);         // startChar
            bo_add_16be(tx3g, 0);         // endChar
            bo_add_16be(tx3g, 0);         // default font ID
            bo_add_8(tx3g, 0);            // face style flags
            bo_add_8(tx3g, STYLE_DEFAULT_FONT_SIZE);  // font size
            bo_add_32be(tx3g, 0xFFFFFFFFU);// foreground color

            /* FontTableBox */
            bo_t *ftab = box_new("ftab");
            if(ftab)
            {
                bo_add_16be(ftab, b_mov ? 2 : 3); // Entry Count
                /* Font Record */
                bo_add_8(ftab, 5);
                bo_add_mem(ftab, 5,  (void*)"Serif");
                bo_add_8(ftab, 10);
                bo_add_mem(ftab, 10, (void*) (b_mov ? "Sans-Serif" : "Sans-serif"));
                if(!b_mov) /* qt only allows "Serif" and "Sans-Serif" */
                {
                    bo_add_8(ftab, 9);
                    bo_add_mem(ftab, 9,  (void*)"Monospace");
                }

                box_gather(tx3g, ftab);
            }
        }

        return tx3g;
    }
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    else if(p_track->fmt.i_codec == VLC_CODEC_WEBVTT)
    {
        bo_t *wvtt = box_new("wvtt");
        if(!wvtt)
            return NULL;

        /* Sample Entry Header */
        for (int i = 0; i < 6; i++)
            bo_add_8(wvtt, 0);        // reserved;
        bo_add_16be(wvtt, 1);         // data-reference-index

        bo_t *ftab = box_new("vttc");
        box_gather(wvtt, ftab);

        return wvtt;
    }
François Cartegnie's avatar
François Cartegnie committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
    else if(p_track->fmt.i_codec == VLC_CODEC_TTML)
    {
        bo_t *stpp = box_new("stpp");
        if(!stpp)
            return NULL;

        /* Sample Entry Header */
        for (int i = 0; i < 6; i++)
            bo_add_8(stpp, 0);        // reserved;
        bo_add_16be(stpp, 1);         // data-reference-index

        return stpp;
    }
1158 1159

    return NULL;
1160 1161
}

1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
static int64_t GetScaledEntryDuration( const mp4mux_entry_t *p_entry, uint32_t i_timescale,
                                       mtime_t *pi_total_mtime, int64_t *pi_total_scaled )
{
    const mtime_t i_totalscaledtototalmtime = *pi_total_scaled * CLOCK_FREQ / i_timescale;
    const mtime_t i_diff = *pi_total_mtime - i_totalscaledtototalmtime;

    /* Ensure to compensate the drift due to loss from time, and from scale, conversions */
    int64_t i_scaled = (p_entry->i_length + i_diff) * i_timescale / CLOCK_FREQ;
    *pi_total_mtime += p_entry->i_length;
    *pi_total_scaled += i_scaled;

    return i_scaled;
}

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
static bo_t *GetStblBox(vlc_object_t *p_obj, mp4mux_trackinfo_t *p_track, bool b_mov, bool b_stco64)
{
    /* sample description */
    bo_t *stsd = box_full_new("stsd", 0, 0);
    if(!stsd)
        return NULL;
    bo_add_32be(stsd, 1);
    if (p_track->fmt.i_cat == AUDIO_ES)
        box_gather(stsd, GetSounBox(p_obj, p_track, b_mov));
    else if (p_track->fmt.i_cat == VIDEO_ES)
        box_gather(stsd, GetVideBox(p_obj, p_track, b_mov));
    else if (p_track->fmt.i_cat == SPU_ES)
1188
        box_gather(stsd, GetTextBox(p_obj, p_track, b_mov));
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208

    /* chunk offset table */
    bo_t *stco;

    if (b_stco64) {
        /* 64 bits version */
        stco = box_full_new("co64", 0, 0);
    } else {
        /* 32 bits version */
        stco = box_full_new("stco", 0, 0);
    }
    if(!stco)
    {
        bo_free(stsd);
        return NULL;
    }
    bo_add_32be(stco, 0);     // entry-count (fixed latter)

    /* sample to chunk table */
    bo_t *stsc = box_full_new("stsc", 0, 0);
1209 1210 1211 1212 1213 1214
    if(!stsc)
    {
        bo_free(stco);
        bo_free(stsd);
        return NULL;
    }
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
    bo_add_32be(stsc, 0);     // entry-count (fixed latter)

    unsigned i_chunk = 0;
    unsigned i_stsc_last_val = 0, i_stsc_entries = 0;
    for (unsigned i = 0; i < p_track->i_entry_count; i_chunk++) {
        mp4mux_entry_t *entry = p_track->entry;
        int i_first = i;

        if (b_stco64)
            bo_add_64be(stco, entry[i].i_pos);
        else
            bo_add_32be(stco, entry[i].i_pos);

        for (; i < p_track->i_entry_count; i++)
            if (i >= p_track->i_entry_count - 1 ||
                    entry[i].i_pos + entry[i].i_size != entry[i+1].i_pos) {
                i++;
                break;
            }

        /* Add entry to the stsc table */
        if (i_stsc_last_val != i - i_first) {
            bo_add_32be(stsc, 1 + i_chunk);   // first-chunk
            bo_add_32be(stsc, i - i_first) ;  // samples-per-chunk
            bo_add_32be(stsc, 1);             // sample-descr-index
            i_stsc_last_val = i - i_first;
            i_stsc_entries++;
        }
    }

    /* Fix stco entry count */
    bo_swap_32be(stco, 12, i_chunk);
    if(p_obj)
        msg_Dbg(p_obj, "created %d chunks (stco)", i_chunk);

    /* Fix stsc entry count */
    bo_swap_32be(stsc, 12, i_stsc_entries );

    /* add stts */
    bo_t *stts = box_full_new("stts", 0, 0);
    if(!stts)
    {
        bo_free(stsd);
        bo_free(stco);
1259
        bo_free(stsc);
1260 1261 1262 1263
        return NULL;
    }
    bo_add_32be(stts, 0);     // entry-count (fixed latter)

1264 1265
    mtime_t i_total_mtime = 0;
    int64_t i_total_scaled = 0;
1266 1267 1268 1269
    unsigned i_index = 0;
    for (unsigned i = 0; i < p_track->i_entry_count; i_index++) {
        int     i_first = i;

1270 1271 1272 1273 1274 1275 1276 1277 1278
        int64_t i_scaled = GetScaledEntryDuration(&p_track->entry[i], p_track->i_timescale,
                                                  &i_total_mtime, &i_total_scaled);
        for (unsigned j=i+1; j < p_track->i_entry_count; j++)
        {
            mtime_t i_total_mtime_next = i_total_mtime;
            int64_t i_total_scaled_next = i_total_scaled;
            int64_t i_scalednext = GetScaledEntryDuration(&p_track->entry[j], p_track->i_timescale,
                                                          &i_total_mtime_next, &i_total_scaled_next);
            if( i_scalednext != i_scaled )
1279 1280
                break;

1281 1282 1283 1284 1285 1286 1287
            i_total_mtime = i_total_mtime_next;
            i_total_scaled = i_total_scaled_next;
            i = j;
        }

        bo_add_32be(stts, ++i - i_first); // sample-count
        bo_add_32be(stts, i_scaled); // sample-delta
1288 1289 1290
    }
    bo_swap_32be(stts, 12, i_index);

1291 1292 1293
    //msg_Dbg(p_obj, "total sout duration %"PRId64" reconverted from scaled %"PRId64,
    //                i_total_mtime, i_total_scaled * CLOCK_FREQ / p_track->i_timescale );

1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
    /* composition time handling */
    bo_t *ctts = NULL;
    if ( p_track->b_hasbframes && (ctts = box_full_new("ctts", 0, 0)) )
    {
        bo_add_32be(ctts, 0);
        i_index = 0;
        for (unsigned i = 0; i < p_track->i_entry_count; i_index++)
        {
            int     i_first = i;
            mtime_t i_offset = p_track->entry[i].i_pts_dts;

            for (; i < p_track->i_entry_count; ++i)
                if (i == p_track->i_entry_count || p_track->entry[i].i_pts_dts != i_offset)
                    break;

            bo_add_32be(ctts, i - i_first); // sample-count
            bo_add_32be(ctts, i_offset * p_track->i_timescale / CLOCK_FREQ ); // sample-offset
        }
        bo_swap_32be(ctts, 12, i_index);
    }

    bo_t *stsz = box_full_new("stsz", 0, 0);
    if(!stsz)
    {
        bo_free(stsd);
        bo_free(stco);
        bo_free(stts);
        return NULL;
    }
    int i_size = 0;
    for (unsigned i = 0; i < p_track->i_entry_count; i++)
    {
        if ( i == 0 )
            i_size = p_track->entry[i].i_size;
        else if ( p_track->entry[i].i_size != i_size )
        {
            i_size = 0;
            break;
        }
    }
    bo_add_32be(stsz, i_size);                         // sample-size
    bo_add_32be(stsz, p_track->i_entry_count);       // sample-count
    if ( i_size == 0 ) // all samples have different size
    {
        for (unsigned i = 0; i < p_track->i_entry_count; i++)
            bo_add_32be(stsz, p_track->entry[i].i_size); // sample-size
    }

    /* create stss table */
    bo_t *stss = NULL;
    i_index = 0;
    if ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES )
    {
        mtime_t i_interval = -1;
        for (unsigned i = 0; i < p_track->i_entry_count; i++)
        {
            if ( i_interval != -1 )
            {
                i_interval += p_track->entry[i].i_length + p_track->entry[i].i_pts_dts;
                if ( i_interval < CLOCK_FREQ * 2 )
                    continue;
            }

            if (p_track->entry[i].i_flags & BLOCK_FLAG_TYPE_I) {
                if (stss == NULL) {
                    stss = box_full_new("stss", 0, 0);
                    if(!stss)
                        break;
                    bo_add_32be(stss, 0); /* fixed later */
                }
                bo_add_32be(stss, 1 + i);
                i_index++;
                i_interval = 0;
            }
        }
    }

    if (stss)
        bo_swap_32be(stss, 12, i_index);

    /* Now gather all boxes into stbl */
    bo_t *stbl = box_new("stbl");
    if(!stbl)
    {
        bo_free(stsd);
        bo_free(stco);
        bo_free(stts);
        bo_free(stsz);
        bo_free(stss);
1383
        bo_free(ctts);
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
        return NULL;
    }
    box_gather(stbl, stsd);
    box_gather(stbl, stts);
    if (stss)
        box_gather(stbl, stss);
    if (ctts)
        box_gather(stbl, ctts);
    box_gather(stbl, stsc);
    box_gather(stbl, stsz);
1394
    p_track->i_stco_pos = bo_size(stbl) + 16;
1395 1396 1397 1398 1399
    box_gather(stbl, stco);

    return stbl;
}

1400
bo_t * mp4mux_GetMoovBox(vlc_object_t *p_obj, mp4mux_trackinfo_t **pp_tracks, unsigned int i_tracks,
1401
                         mtime_t i_duration,
1402
                         bool b_fragmented, bool b_mov, bool b_64_ext, bool b_stco64 )
1403 1404 1405 1406 1407 1408
{
    bo_t            *moov, *mvhd;

    uint32_t        i_movie_timescale = 90000;
    int64_t         i_timestamp = get_timestamp();

1409 1410 1411 1412 1413
    /* Important for smooth streaming where its (not muxed here) media time offsets
     * are in timescale == track timescale */
    if( i_tracks == 1 )
        i_movie_timescale = pp_tracks[0]->i_timescale;

1414 1415 1416 1417
    moov = box_new("moov");
    if(!moov)
        return NULL;
    /* Create general info */
1418
    if( i_duration == 0 && !b_fragmented )
1419 1420 1421
    {
        for (unsigned int i = 0; i < i_tracks; i++) {
            mp4mux_trackinfo_t *p_stream = pp_tracks[i];
1422
            i_duration = __MAX(i_duration, p_stream->i_read_duration);
1423 1424
        }
        if(p_obj)
1425
            msg_Dbg(p_obj, "movie duration %"PRId64"s", i_duration / CLOCK_FREQ);
1426
    }
1427
    int64_t i_movie_duration = i_duration * i_movie_timescale / CLOCK_FREQ;
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566

    /* *** add /moov/mvhd *** */
    if (!b_64_ext) {
        mvhd = box_full_new("mvhd", 0, 0);
        if(!mvhd)
        {
            bo_free(moov);
            return NULL;
        }
        bo_add_32be(mvhd, i_timestamp);   // creation time
        bo_add_32be(mvhd, i_timestamp);   // modification time
        bo_add_32be(mvhd, i_movie_timescale);  // timescale
        bo_add_32be(mvhd, i_movie_duration);  // duration
    } else {
        mvhd = box_full_new("mvhd", 1, 0);
        if(!mvhd)
        {
            bo_free(moov);
            return NULL;
        }
        bo_add_64be(mvhd, i_timestamp);   // creation time
        bo_add_64be(mvhd, i_timestamp);   // modification time
        bo_add_32be(mvhd, i_movie_timescale);  // timescale
        bo_add_64be(mvhd, i_movie_duration);  // duration
    }
    bo_add_32be(mvhd, 0x10000);           // rate
    bo_add_16be(mvhd, 0x100);             // volume
    bo_add_16be(mvhd, 0);                 // reserved
    for (int i = 0; i < 2; i++)
        bo_add_32be(mvhd, 0);             // reserved

    uint32_t mvhd_matrix[9] = { 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000 };

    for (int i = 0; i < 9; i++)
        bo_add_32be(mvhd, mvhd_matrix[i]);// matrix
    for (int i = 0; i < 6; i++)
        bo_add_32be(mvhd, 0);             // pre-defined

    /* Next available track id */
    bo_add_32be(mvhd, (i_tracks) ? pp_tracks[i_tracks -1]->i_track_id + 1: 1); // next-track-id

    box_gather(moov, mvhd);

    for (unsigned int i_trak = 0; i_trak < i_tracks; i_trak++) {
        mp4mux_trackinfo_t *p_stream = pp_tracks[i_trak];

        mtime_t i_stream_duration;
        if ( !b_fragmented )
            i_stream_duration = p_stream->i_read_duration * i_movie_timescale / CLOCK_FREQ;
        else
            i_stream_duration = 0;

        /* *** add /moov/trak *** */
        bo_t *trak = box_new("trak");
        if(!trak)
            continue;

        /* *** add /moov/trak/tkhd *** */
        bo_t *tkhd;
        if (!b_64_ext) {
            if (b_mov)
                tkhd = box_full_new("tkhd", 0, 0x0f);
            else
                tkhd = box_full_new("tkhd", 0, 1);
            if(!tkhd)
            {
                bo_free(trak);
                continue;
            }
            bo_add_32be(tkhd, i_timestamp);       // creation time
            bo_add_32be(tkhd, i_timestamp);       // modification time
            bo_add_32be(tkhd, p_stream->i_track_id);
            bo_add_32be(tkhd, 0);                     // reserved 0
            bo_add_32be(tkhd, i_stream_duration); // duration
        } else {
            if (b_mov)
                tkhd = box_full_new("tkhd", 1, 0x0f);
            else
                tkhd = box_full_new("tkhd", 1, 1);
            if(!tkhd)
            {
                bo_free(trak);
                continue;
            }
            bo_add_64be(tkhd, i_timestamp);       // creation time
            bo_add_64be(tkhd, i_timestamp);       // modification time
            bo_add_32be(tkhd, p_stream->i_track_id);
            bo_add_32be(tkhd, 0);                     // reserved 0
            bo_add_64be(tkhd, i_stream_duration); // duration
        }

        for (int i = 0; i < 2; i++)
            bo_add_32be(tkhd, 0);                 // reserved
        bo_add_16be(tkhd, 0);                     // layer
        bo_add_16be(tkhd, 0);                     // pre-defined
        // volume
        bo_add_16be(tkhd, p_stream->fmt.i_cat == AUDIO_ES ? 0x100 : 0);
        bo_add_16be(tkhd, 0);                     // reserved
        matrix_apply_rotation(&p_stream->fmt, mvhd_matrix);
        for (int i = 0; i < 9; i++)
            bo_add_32be(tkhd, mvhd_matrix[i]);    // matrix
        if (p_stream->fmt.i_cat == AUDIO_ES) {
            bo_add_32be(tkhd, 0);                 // width (presentation)
            bo_add_32be(tkhd, 0);                 // height(presentation)
        } else if (p_stream->fmt.i_cat == VIDEO_ES) {
            int i_width = p_stream->fmt.video.i_width << 16;
            if (p_stream->fmt.video.i_sar_num > 0 && p_stream->fmt.video.i_sar_den > 0) {
                i_width = (int64_t)p_stream->fmt.video.i_sar_num *
                          ((int64_t)p_stream->fmt.video.i_width << 16) /
                          p_stream->fmt.video.i_sar_den;
            }
            // width (presentation)
            bo_add_32be(tkhd, i_width);
            // height(presentation)
            bo_add_32be(tkhd, p_stream->fmt.video.i_height << 16);
        } else {
            int i_width = 320 << 16;
            int i_height = 200;
            for (unsigned int i = 0; i < i_tracks; i++) {
                mp4mux_trackinfo_t *tk = pp_tracks[i];
                if (tk->fmt.i_cat == VIDEO_ES) {
                    if (tk->fmt.video.i_sar_num > 0 &&
                        tk->fmt.video.i_sar_den > 0)
                        i_width = (int64_t)tk->fmt.video.i_sar_num *
                                  ((int64_t)tk->fmt.video.i_width << 16) /
                                  tk->fmt.video.i_sar_den;
                    else
                        i_width = tk->fmt.video.i_width << 16;
                    i_height = tk->fmt.video.i_height;
                    break;
                }
            }
            bo_add_32be(tkhd, i_width);     // width (presentation)
            bo_add_32be(tkhd, i_height << 16);    // height(presentation)
        }

        box_gather(trak, tkhd);

        /* *** add /moov/trak/edts and elst */
1567 1568 1569
        bo_t *edts = GetEDTS(p_stream, i_movie_timescale, b_64_ext);
        if(edts)
            box_gather(trak, edts);
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648

        /* *** add /moov/trak/mdia *** */
        bo_t *mdia = box_new("mdia");
        if(!mdia)
        {
            bo_free(trak);
            continue;
        }

        /* media header */
        bo_t *mdhd;
        if (!b_64_ext) {
            mdhd = box_full_new("mdhd", 0, 0);
            if(!mdhd)
            {
                bo_free(mdia);
                bo_free(trak);
                continue;
            }
            bo_add_32be(mdhd, i_timestamp);   // creation time
            bo_add_32be(mdhd, i_timestamp);   // modification time
            bo_add_32be(mdhd, p_stream->i_timescale); // timescale
            bo_add_32be(mdhd, i_stream_duration * p_stream->i_timescale / i_movie_timescale);  // duration
        } else {
            mdhd = box_full_new("mdhd", 1, 0);
            if(!mdhd)
            {
                bo_free(mdia);
                bo_free(trak);
                continue;
            }
            bo_add_64be(mdhd, i_timestamp);   // creation time
            bo_add_64be(mdhd, i_timestamp);   // modification time
            bo_add_32be(mdhd, p_stream->i_timescale); // timescale
            bo_add_64be(mdhd, i_stream_duration * p_stream->i_timescale / i_movie_timescale);  // duration
        }

        if (p_stream->fmt.psz_language) {
            char *psz = p_stream->fmt.psz_language;
            const iso639_lang_t *pl = NULL;
            uint16_t lang = 0x0;

            if (strlen(psz) == 2)
                pl = GetLang_1(psz);
            else if (strlen(psz) == 3) {
                pl = GetLang_2B(psz);
                if (!strcmp(pl->psz_iso639_1, "??"))
                    pl = GetLang_2T(psz);
            }

            if (pl && strcmp(pl->psz_iso639_1, "??"))
                lang = ((pl->psz_iso639_2T[0] - 0x60) << 10) |
                       ((pl->psz_iso639_2T[1] - 0x60) <<  5) |
                       ((pl->psz_iso639_2T[2] - 0x60));
            bo_add_16be(mdhd, lang);          // language
        } else
            bo_add_16be(mdhd, 0   );          // language
        bo_add_16be(mdhd, 0   );              // predefined
        box_gather(mdia, mdhd);

        /* handler reference */
        bo_t *hdlr = box_full_new("hdlr", 0, 0);
        if(!hdlr)
        {
            bo_free(mdia);
            bo_free(trak);
            continue;
        }

        if (b_mov)
            bo_add_fourcc(hdlr, "mhlr");         // media handler
        else
            bo_add_32be(hdlr, 0);

        if (p_stream->fmt.i_cat == AUDIO_ES)
            bo_add_fourcc(hdlr, "soun");
        else if (p_stream->fmt.i_cat == VIDEO_ES)
            bo_add_fourcc(hdlr, "vide");
        else if (p_stream->fmt.i_cat == SPU_ES)
1649
        {
1650 1651
            /* text/tx3g 3GPP */
            /* sbtl/tx3g Apple subs */
1652
            /* text/text Apple textmedia */
1653
            if(p_stream->fmt.i_codec == VLC_CODEC_TX3G)
1654
                bo_add_fourcc(hdlr, (b_mov) ? "sbtl" : "text");
François Cartegnie's avatar
François Cartegnie committed
1655 1656
            else if(p_stream->fmt.i_codec == VLC_CODEC_TTML)
                bo_add_fourcc(hdlr, "sbtl");
1657 1658
            else
                bo_add_fourcc(hdlr, "text");
1659
        }
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708

        bo_add_32be(hdlr, 0);         // reserved
        bo_add_32be(hdlr, 0);         // reserved
        bo_add_32be(hdlr, 0);         // reserved

        if (b_mov)
            bo_add_8(hdlr, 12);   /* Pascal string for .mov */

        if (p_stream->fmt.i_cat == AUDIO_ES)
            bo_add_mem(hdlr, 12, (uint8_t*)"SoundHandler");
        else if (p_stream->fmt.i_cat == VIDEO_ES)
            bo_add_mem(hdlr, 12, (uint8_t*)"VideoHandler");
        else
            bo_add_mem(hdlr, 12, (uint8_t*)"Text Handler");

        if (!b_mov)
            bo_add_8(hdlr, 0);   /* asciiz string for .mp4, yes that's BRAIN DAMAGED F**K MP4 */

        box_gather(mdia, hdlr);

        /* minf*/
        bo_t *minf = box_new("minf");
        if(!minf)
        {
            bo_free(mdia);
            bo_free(trak);
            continue;
        }

        /* add smhd|vmhd */
        if (p_stream->fmt.i_cat == AUDIO_ES) {
            bo_t *smhd = box_full_new("smhd", 0, 0);
            if(smhd)
            {
                bo_add_16be(smhd, 0);     // balance
                bo_add_16be(smhd, 0);     // reserved

                box_gather(minf, smhd);
            }
        } else if (p_stream->fmt.i_cat == VIDEO_ES) {
            bo_t *vmhd = box_full_new("vmhd", 0, 1);
            if(vmhd)
            {
                bo_add_16be(vmhd, 0);     // graphicsmode
                for (int i = 0; i < 3; i++)
                    bo_add_16be(vmhd, 0); // opcolor
                box_gather(minf, vmhd);
            }
        } else if (p_stream->fmt.i_cat == SPU_ES) {
1709 1710
            if(b_mov &&
               (p_stream->fmt.i_codec == VLC_CODEC_SUBT||
1711 1712
                p_stream->fmt.i_codec == VLC_CODEC_TX3G||
                p_stream->fmt.i_codec == VLC_CODEC_QTXT))
1713
            {
1714 1715
                bo_t *gmin = box_full_new("gmin", 0, 1);
                if(gmin)
1716
                {
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
                    bo_add_16be(gmin, 0);     // graphicsmode
                    for (int i = 0; i < 3; i++)
                        bo_add_16be(gmin, 0); // opcolor
                    bo_add_16be(gmin, 0);     // balance
                    bo_add_16be(gmin, 0);     // reserved

                    bo_t *gmhd = box_new("gmhd");
                    if(gmhd)
                    {
                        box_gather(gmhd, gmin);
                        box_gather(minf, gmhd);
                    }
                    else bo_free(gmin);
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
                }
            }
        }

        /* dinf */
        bo_t *dref = box_full_new("dref", 0, 0);
        if(dref)
        {
            bo_add_32be(dref, 1);

            bo_t *url = box_full_new("url ", 0, 0x01);
            if(url)
                box_gather(dref, url);

            bo_t *dinf = box_new("dinf");
            if(dinf)
            {
                box_gather(dinf, dref);

                /* append dinf to mdia */
                box_gather(minf, dinf);
            }
1752
            else bo_free(dref);
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
        }

        /* add stbl */
        bo_t *stbl;
        if ( b_fragmented )
        {
            uint32_t i_backup = p_stream->i_entry_count;
            p_stream->i_entry_count = 0;
            stbl = GetStblBox(p_obj, p_stream, b_mov, b_stco64);
            p_stream->i_entry_count = i_backup;
        }
        else
            stbl = GetStblBox(p_obj, p_stream, b_mov, b_stco64);

        /* append stbl to minf */
1768
        p_stream->i_stco_pos += bo_size(minf);
1769 1770 1771
        box_gather(minf, stbl);

        /* append minf to mdia */
1772
        p_stream->i_stco_pos += bo_size(mdia);
1773 1774 1775
        box_gather(mdia, minf);

        /* append mdia to trak */
1776
        p_stream->i_stco_pos += bo_size(trak);
1777 1778 1779
        box_gather(trak, mdia);

        /* append trak to moov */
1780
        p_stream->i_stco_pos += bo_size(moov);
1781 1782 1783 1784 1785 1786 1787 1788 1789
        box_gather(moov, trak);
    }

    /* Add user data tags */
    box_gather(moov, GetUdtaTag(pp_tracks, i_tracks));

    if ( b_fragmented )
    {
        bo_t *mvex = box_new("mvex");
1790
        if( mvex )
1791
        {
1792
            if( i_movie_duration )
1793
            {
1794 1795 1796 1797
                bo_t *mehd = box_full_new("mehd", b_64_ext ? 1 : 0, 0);
                if(mehd)
                {
                    if(b_64_ext)
1798
                        bo_add_64be(mehd, i_movie_duration);
1799
                    else
1800
                        bo_add_32be(mehd, i_movie_duration);
1801 1802
                    box_gather(mvex, mehd);
                }
1803
            }
1804 1805 1806
            for (unsigned int i_trak = 0; mvex && i_trak < i_tracks; i_trak++)
            {
                mp4mux_trackinfo_t *p_stream = pp_tracks[i_trak];
1807

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
                /* Try to find some defaults */
                if ( p_stream->i_entry_count )
                {
                    // FIXME: find highest occurence
                    p_stream->i_trex_default_length = p_stream->entry[0].i_length;
                    p_stream->i_trex_default_size = p_stream->entry[0].i_size;
                }

                /* *** add /mvex/trex *** */
                bo_t *trex = box_full_new("trex", 0, 0);
                bo_add_32be(trex, p_stream->i_track_id);
                bo_add_32be(trex, 1); // sample desc index
                bo_add_32be(trex, (uint64_t)p_stream->i_trex_default_length * p_stream->i_timescale / CLOCK_FREQ); // sample duration
                bo_add_32be(trex, p_stream->i_trex_default_size); // sample size
                bo_add_32be(trex, 0); // sample flags
                box_gather(mvex, trex);
            }
            box_gather(moov, mvex);
1826 1827 1828 1829
        }
    }

    if(moov->b)
1830
        box_fix(moov, bo_size(moov));
1831 1832 1833
    return moov;
}

1834
bo_t *mp4mux_GetFtyp(vlc_fourcc_t major, uint32_t minor, vlc_fourcc_t extra[], size_t i_fourcc)
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
{
    bo_t *box = box_new("ftyp");
    if(box)
    {
        bo_add_fourcc(box, &major);
        bo_add_32be  (box, minor);
        for(size_t i=0; i<i_fourcc; i++)
            bo_add_fourcc(box, &extra[i]);
        if(!box->b)
        {
            free(box);
            return NULL;
        }
1848
        box_fix(box, bo_size(box));
1849 1850 1851
    }
    return box;
}
1852

1853
bool mp4mux_CanMux(vlc_object_t *p_obj, const es_format_t *p_fmt,
1854
                   vlc_fourcc_t i_brand, bool b_fragmented)
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
{
    switch(p_fmt->i_codec)
    {
    case VLC_CODEC_A52:
    case VLC_CODEC_DTS:
    case VLC_CODEC_EAC3:
    case VLC_CODEC_MP4A:
    case VLC_CODEC_MP4V:
    case VLC_CODEC_MPGA:
    case VLC_CODEC_MP3:
    case VLC_CODEC_MPGV:
    case VLC_CODEC_MP2V:
    case VLC_CODEC_MP1V:
    case VLC_CODEC_MJPG:
    case VLC_CODEC_MJPGB:
    case VLC_CODEC_SVQ1:
    case VLC_CODEC_SVQ3:
    case VLC_CODEC_H263:
    case VLC_CODEC_AMR_NB:
    case VLC_CODEC_AMR_WB:
    case VLC_CODEC_YV12:
    case VLC_CODEC_YUYV:
    case VLC_CODEC_VC1:
    case VLC_CODEC_WMAP:
        break;
    case VLC_CODEC_H264:
        if(!p_fmt->i_extra && p_obj)
            msg_Warn(p_obj, "H264 muxing from AnnexB source will set an incorrect default profile");
        break;
    case VLC_CODEC_HEVC:
        if(!p_fmt->i_extra && p_obj)
1886
        {
1887
            msg_Err(p_obj, "HEVC muxing from AnnexB source is unsupported");
1888 1889 1890
            return false;
        }
        break;
1891 1892 1893
    case VLC_CODEC_SUBT:
        if(p_obj)
            msg_Warn(p_obj, "subtitle track added like in .mov (even when creating .mp4)");
1894
        return !b_fragmented;
François Cartegnie's avatar
François Cartegnie committed
1895 1896 1897 1898
    case VLC_CODEC_TTML:
        /* Special case with smooth headers where we need to force frag TTML */
        /* TTML currently not supported in sout, until we can keep original timestamps */
            return i_brand == VLC_FOURCC('s', 'm', 'o', 'o');
1899
    case VLC_CODEC_QTXT:
1900
    case VLC_CODEC_TX3G:
1901
    case VLC_CODEC_WEBVTT:
1902
        return !b_fragmented;
1903 1904 1905 1906 1907
    default:
        return false;
    }
    return true;
}