ogg.c 61 KB
Newer Older
1
/*****************************************************************************
2
 * ogg.c: ogg muxer module for vlc
3
 *****************************************************************************
4
 * Copyright (C) 2001, 2002, 2006 VLC authors and VideoLAN
5
 * $Id$
6 7
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8
 *          Gildas Bazin <gbazin@videolan.org>
9
 *
10 11 12
 * 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
13 14 15 16
 * (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
17 18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
19
 *
20 21 22
 * 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 27
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
28

29 30 31
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
32

33
#include <vlc_common.h>
34
#include <vlc_plugin.h>
35 36 37
#include <vlc_sout.h>
#include <vlc_block.h>
#include <vlc_codecs.h>
38 39
#include <limits.h>
#include <vlc_rand.h>
40
#include "../demux/xiph.h"
41 42 43 44

#include <ogg/ogg.h>

/*****************************************************************************
45
 * Module descriptor
46
 *****************************************************************************/
47 48 49 50 51 52 53
#define INDEXINTVL_TEXT N_("Index interval")
#define INDEXINTVL_LONGTEXT N_("Minimal index interval, in microseconds. " \
    "Set to 0 to disable index creation.")
#define INDEXRATIO_TEXT N_("Index size ratio")
#define INDEXRATIO_LONGTEXT N_(\
    "Set index size ratio. Alters default (60min content) or estimated size." )

54 55
static int  Open   ( vlc_object_t * );
static void Close  ( vlc_object_t * );
56

57 58
#define SOUT_CFG_PREFIX "sout-ogg-"

59 60 61 62 63
vlc_module_begin ()
    set_description( N_("Ogg/OGM muxer") )
    set_capability( "sout mux", 10 )
    set_category( CAT_SOUT )
    set_subcategory( SUBCAT_SOUT_MUX )
64
    add_shortcut( "ogg", "ogm" )
65 66 67 68
    add_integer_with_range( SOUT_CFG_PREFIX "indexintvl", 1000, 0, INT_MAX,
                            INDEXINTVL_TEXT, INDEXINTVL_LONGTEXT, true )
    add_float_with_range( SOUT_CFG_PREFIX "indexratio", 1.0, 1.0, 1000,
                          INDEXRATIO_TEXT, INDEXRATIO_LONGTEXT, true )
69 70
    set_callbacks( Open, Close )
vlc_module_end ()
71

72 73 74 75

/*****************************************************************************
 * Exported prototypes
 *****************************************************************************/
76
static int Control  ( sout_mux_t *, int, va_list );
77
static int AddStream( sout_mux_t *, sout_input_t * );
78
static void DelStream( sout_mux_t *, sout_input_t * );
79
static int Mux      ( sout_mux_t * );
80
static int MuxBlock ( sout_mux_t *, sout_input_t * );
81

82 83
static bool OggCreateHeaders( sout_mux_t * );
static void OggFillSkeletonFishead( uint8_t *p_buffer, sout_mux_t *p_mux );
84

85
/*****************************************************************************
86
 * Misc declarations
87 88
 *****************************************************************************/

89 90 91
/* Skeleton */
#define FISBONE_BASE_SIZE 52
#define FISBONE_BASE_OFFSET 44
92
#define INDEX_BASE_SIZE 42
93

94 95
/* Structures used for OggDS headers used in ogm files */

96 97
#define PACKET_TYPE_HEADER   0x01
#define PACKET_TYPE_COMMENT  0x03
98
#define PACKET_IS_SYNCPOINT  0x08
99

100
typedef struct
101 102 103
{
    int32_t i_width;
    int32_t i_height;
104
} oggds_header_video_t;
105

106
typedef struct
107 108 109 110
{
    int16_t i_channels;
    int16_t i_block_align;
    int32_t i_avgbytespersec;
111
} oggds_header_audio_t;
112

113
typedef struct
114 115 116 117 118 119 120 121 122 123 124 125 126 127
{
    uint8_t i_packet_type;

    char stream_type[8];
    char sub_type[4];

    int32_t i_size;

    int64_t i_time_unit;
    int64_t i_samples_per_unit;
    int32_t i_default_len;

    int32_t i_buffer_size;
    int16_t i_bits_per_sample;
128 129 130

    int16_t i_padding_0; /* Because the original is using MSVC packing style */

131 132
    union
    {
133 134
        oggds_header_video_t video;
        oggds_header_audio_t audio;
135 136
    } header;

137 138
    int32_t i_padding_1; /* Because the original is using MSVC packing style */

139
} oggds_header_t;
140

141
/*****************************************************************************
142
 * Definitions of structures and functions used by this plugins
143 144 145 146
 *****************************************************************************/
typedef struct
{
    int i_cat;
147
    vlc_fourcc_t i_fourcc;
148 149 150 151 152 153

    int b_new;

    mtime_t i_dts;
    mtime_t i_length;
    int     i_packet_no;
154
    int     i_serial_no;
155
    int     i_keyframe_granule_shift; /* Theora and Daala only */
ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
156 157
    int     i_last_keyframe; /* dirac and theora */
    int     i_num_frames; /* Theora only */
158
    uint64_t u_last_granulepos; /* Used for correct EOS page */
ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
159
    int64_t i_num_keyframes;
160 161
    ogg_stream_state os;

162
    oggds_header_t *p_oggds_header;
163 164
    bool b_started;
    bool b_finished;
165

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    struct
    {
         bool b_fisbone_done;
         bool b_index_done;
         /* Skeleton index storage */
         unsigned char *p_index;
         uint64_t i_index_size;
         uint64_t i_index_payload; /* real index size */
         uint64_t i_index_count;
         /* backup values for rewriting index page later */
         uint64_t i_index_offset;  /* sout offset of the index page */
         int64_t i_index_packetno;  /* index packet no */
         int i_index_pageno;
         /* index creation tracking values */
         uint64_t i_last_keyframe_pos;
         uint64_t i_last_keyframe_time;
    } skeleton;
183 184 185 186 187

    int             i_dirac_last_pt;
    int             i_dirac_last_dt;
    mtime_t         i_baseptsdelay;

188 189 190 191 192 193 194
} ogg_stream_t;

struct sout_mux_sys_t
{
    int     i_streams;

    mtime_t i_start_dts;
195
    int     i_next_serial_no;
196 197 198

    /* number of logical streams pending to be added */
    int i_add_streams;
199
    bool b_can_add_streams;
200 201 202 203

    /* logical streams pending to be deleted */
    int i_del_streams;
    ogg_stream_t **pp_del_streams;
204 205 206 207 208 209 210 211 212

    /* Skeleton */
    struct
    {
        bool b_create;
        int i_serial_no;
        int i_packet_no;
        ogg_stream_state os;
        bool b_head_done;
213 214 215 216
        /* backup values for rewriting fishead page later */
        uint64_t i_fishead_offset;  /* sout offset of the fishead page */
        int i_index_intvl;
        float i_index_ratio;
217
    } skeleton;
218 219 220 221 222

    /* access position */
    ssize_t i_pos;
    ssize_t i_data_start;
    ssize_t i_segment_start;
223 224
};

225
static void OggSetDate( block_t *, mtime_t , mtime_t  );
226
static block_t *OggStreamFlush( sout_mux_t *, ogg_stream_state *, mtime_t );
227 228 229
static void OggCreateStreamFooter( sout_mux_t *p_mux, ogg_stream_t *p_stream );
static void OggRewriteFisheadPage( sout_mux_t *p_mux );
static bool AllocateIndex( sout_mux_t *p_mux, sout_input_t *p_input );
230 231

/*****************************************************************************
232
 * Open: Open muxer
233 234 235
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
236 237
    sout_mux_t      *p_mux = (sout_mux_t*)p_this;
    sout_mux_sys_t  *p_sys;
238

239
    msg_Info( p_mux, "Open" );
240

241
    p_sys                 = malloc( sizeof( sout_mux_sys_t ) );
242 243
    if( !p_sys )
        return VLC_ENOMEM;
244
    p_sys->i_streams      = 0;
245
    p_sys->i_add_streams  = 0;
246
    p_sys->b_can_add_streams = true;
247 248
    p_sys->i_del_streams  = 0;
    p_sys->pp_del_streams = 0;
249
    p_sys->i_pos = 0;
250 251
    p_sys->skeleton.b_create = false;
    p_sys->skeleton.b_head_done = false;
252 253 254 255
    p_sys->skeleton.i_index_intvl =
            var_InheritInteger( p_this, SOUT_CFG_PREFIX "indexintvl" );
    p_sys->skeleton.i_index_ratio =
            var_InheritFloat( p_this, SOUT_CFG_PREFIX "indexratio" );
256 257
    p_sys->i_data_start = 0;
    p_sys->i_segment_start = 0;
258
    p_mux->p_sys        = p_sys;
259
    p_mux->pf_control   = Control;
260 261 262
    p_mux->pf_addstream = AddStream;
    p_mux->pf_delstream = DelStream;
    p_mux->pf_mux       = Mux;
263

264 265 266
    /* First serial number is random.
     * (Done like this because on win32 you need to seed the random number
     *  generator once per thread). */
267 268 269
    uint32_t r;
    vlc_rand_bytes(&r, sizeof(r));
    p_sys->i_next_serial_no = r & INT_MAX;
270

271 272 273 274
    return VLC_SUCCESS;
}

/*****************************************************************************
275
 * Close: Finalize ogg bitstream and close muxer
276 277 278
 *****************************************************************************/
static void Close( vlc_object_t * p_this )
{
279 280
    sout_mux_t     *p_mux = (sout_mux_t*)p_this;
    sout_mux_sys_t *p_sys = p_mux->p_sys;
281
    ogg_stream_t *p_stream;
282

283
    msg_Info( p_mux, "Close" );
284

285 286 287
    if( p_sys->i_del_streams )
    {
        /* Close the current ogg stream */
288
        msg_Dbg( p_mux, "writing footers" );
289 290 291

        for(int i = 0; i < p_mux->i_nb_inputs; i++ )
        {
292 293 294
            p_stream = (ogg_stream_t *) p_mux->pp_inputs[i]->p_sys;
            OggCreateStreamFooter( p_mux, p_stream );
            free( p_stream->skeleton.p_index );
295
        }
296 297

        /* Remove deleted logical streams */
298
        for(int i = 0; i < p_sys->i_del_streams; i++ )
299
        {
300 301 302
            OggCreateStreamFooter( p_mux, p_sys->pp_del_streams[i] );
            free( p_sys->pp_del_streams[i]->p_oggds_header );
            free( p_sys->pp_del_streams[i]->skeleton.p_index );
303
            free( p_sys->pp_del_streams[i] );
304
        }
305
        free( p_sys->pp_del_streams );
306
        p_sys->i_streams -= p_sys->i_del_streams;
307
    }
308

309 310 311 312
    /* rewrite fishead with final values */
    if ( p_sys->skeleton.b_create && p_sys->skeleton.b_head_done )
    {
        OggRewriteFisheadPage( p_mux );
313 314
    }

315
    free( p_sys );
316 317
}

318 319 320 321
/*****************************************************************************
 * Control:
 *****************************************************************************/
static int Control( sout_mux_t *p_mux, int i_query, va_list args )
322
{
323
    VLC_UNUSED(p_mux);
324
    bool *pb_bool;
325 326
    char **ppsz;

327 328
   switch( i_query )
   {
329
       case MUX_CAN_ADD_STREAM_WHILE_MUXING:
330 331
           pb_bool = (bool*)va_arg( args, bool * );
           *pb_bool = true;
332 333 334
           return VLC_SUCCESS;

       case MUX_GET_ADD_STREAM_WAIT:
335 336
           pb_bool = (bool*)va_arg( args, bool * );
           *pb_bool = true;
337 338 339 340 341 342 343
           return VLC_SUCCESS;

       case MUX_GET_MIME:
           ppsz = (char**)va_arg( args, char ** );
           *ppsz = strdup( "application/ogg" );
           return VLC_SUCCESS;

344
        default:
345
            return VLC_EGENERIC;
346 347
   }
}
348 349 350
/*****************************************************************************
 * AddStream: Add an elementary stream to the muxed stream
 *****************************************************************************/
351
static int AddStream( sout_mux_t *p_mux, sout_input_t *p_input )
352
{
353 354
    sout_mux_sys_t *p_sys = p_mux->p_sys;
    ogg_stream_t   *p_stream;
355
    uint16_t i_tag;
356

357
    msg_Dbg( p_mux, "adding input" );
358

359
    p_input->p_sys = p_stream = calloc( 1, sizeof( ogg_stream_t ) );
360 361
    if( !p_stream )
        return VLC_ENOMEM;
362

363
    p_stream->i_cat       = p_input->p_fmt->i_cat;
364
    p_stream->i_fourcc    = p_input->p_fmt->i_codec;
365
    p_stream->i_serial_no = p_sys->i_next_serial_no++;
366
    p_stream->i_packet_no = 0;
ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
367 368 369
    p_stream->i_last_keyframe = 0;
    p_stream->i_num_keyframes = 0;
    p_stream->i_num_frames = 0;
370

371
    p_stream->p_oggds_header = 0;
372

373 374 375 376
    p_stream->i_baseptsdelay = -1;
    p_stream->i_dirac_last_pt = -1;
    p_stream->i_dirac_last_dt = -1;

377
    switch( p_input->p_fmt->i_cat )
378
    {
379
    case VIDEO_ES:
380 381 382 383
        if( !p_input->p_fmt->video.i_frame_rate ||
            !p_input->p_fmt->video.i_frame_rate_base )
        {
            msg_Warn( p_mux, "Missing frame rate, assuming 25fps" );
384 385 386
            assert(p_input->p_fmt == &p_input->fmt);
            p_input->fmt.video.i_frame_rate = 25;
            p_input->fmt.video.i_frame_rate_base = 1;
387 388
        }

389
        switch( p_stream->i_fourcc )
390
        {
391 392
        case VLC_CODEC_MP4V:
        case VLC_CODEC_MPGV:
Ilkka Ollakka's avatar
Ilkka Ollakka committed
393 394
        case VLC_CODEC_MP1V:
        case VLC_CODEC_MP2V:
395 396 397 398 399
        case VLC_CODEC_DIV3:
        case VLC_CODEC_MJPG:
        case VLC_CODEC_WMV1:
        case VLC_CODEC_WMV2:
        case VLC_CODEC_WMV3:
400
            p_stream->p_oggds_header = calloc( 1, sizeof(oggds_header_t) );
401 402 403 404 405
            if( !p_stream->p_oggds_header )
            {
                free( p_stream );
                return VLC_ENOMEM;
            }
406 407 408
            p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;

            memcpy( p_stream->p_oggds_header->stream_type, "video", 5 );
409
            if( p_stream->i_fourcc == VLC_CODEC_MP4V )
410
            {
411
                memcpy( p_stream->p_oggds_header->sub_type, "XVID", 4 );
412
            }
413
            else if( p_stream->i_fourcc == VLC_CODEC_DIV3 )
414
            {
415
                memcpy( p_stream->p_oggds_header->sub_type, "DIV3", 4 );
416
            }
417 418
            else
            {
419 420
                memcpy( p_stream->p_oggds_header->sub_type,
                        &p_stream->i_fourcc, 4 );
421
            }
422 423
            p_stream->p_oggds_header->i_size = 0 ;
            p_stream->p_oggds_header->i_time_unit =
424
                     INT64_C(10000000) * p_input->p_fmt->video.i_frame_rate_base /
425 426 427 428 429 430 431
                     (int64_t)p_input->p_fmt->video.i_frame_rate;
            p_stream->p_oggds_header->i_samples_per_unit = 1;
            p_stream->p_oggds_header->i_default_len = 1 ; /* ??? */
            p_stream->p_oggds_header->i_buffer_size = 1024*1024;
            p_stream->p_oggds_header->i_bits_per_sample = 0;
            p_stream->p_oggds_header->header.video.i_width = p_input->p_fmt->video.i_width;
            p_stream->p_oggds_header->header.video.i_height = p_input->p_fmt->video.i_height;
432
            msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
433
            break;
434

435
        case VLC_CODEC_DIRAC:
436 437 438
            msg_Dbg( p_mux, "dirac stream" );
            break;

439
        case VLC_CODEC_THEORA:
440 441
            msg_Dbg( p_mux, "theora stream" );
            break;
442

443 444 445 446
        case VLC_CODEC_DAALA:
            msg_Dbg( p_mux, "daala stream" );
            break;

447 448 449 450
        case VLC_CODEC_VP8:
            msg_Dbg( p_mux, "VP8 stream" );
            break;

451
        default:
452
            FREENULL( p_input->p_sys );
453
            return VLC_EGENERIC;
454 455
        }
        break;
456

457
    case AUDIO_ES:
458
        switch( p_stream->i_fourcc )
459
        {
Tristan Matthews's avatar
Tristan Matthews committed
460 461 462 463
        case VLC_CODEC_OPUS:
            msg_Dbg( p_mux, "opus stream" );
            break;

464
        case VLC_CODEC_VORBIS:
465 466
            msg_Dbg( p_mux, "vorbis stream" );
            break;
467

468
        case VLC_CODEC_SPEEX:
469 470 471
            msg_Dbg( p_mux, "speex stream" );
            break;

472
        case VLC_CODEC_FLAC:
473 474 475
            msg_Dbg( p_mux, "flac stream" );
            break;

476
        default:
477 478 479
            fourcc_to_wf_tag( p_stream->i_fourcc, &i_tag );
            if( i_tag == WAVE_FORMAT_UNKNOWN )
            {
480
                FREENULL( p_input->p_sys );
481 482 483 484 485
                return VLC_EGENERIC;
            }

            p_stream->p_oggds_header =
                malloc( sizeof(oggds_header_t) + p_input->p_fmt->i_extra );
486 487 488 489 490
            if( !p_stream->p_oggds_header )
            {
                free( p_stream );
                return VLC_ENOMEM;
            }
491 492 493
            memset( p_stream->p_oggds_header, 0, sizeof(oggds_header_t) );
            p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;

494
            p_stream->p_oggds_header->i_size = p_input->p_fmt->i_extra;
495 496 497 498

            if( p_input->p_fmt->i_extra )
            {
                memcpy( &p_stream->p_oggds_header[1],
499
                        p_input->p_fmt->p_extra, p_input->p_fmt->i_extra );
500 501 502 503 504
            }

            memcpy( p_stream->p_oggds_header->stream_type, "audio", 5 );

            memset( p_stream->p_oggds_header->sub_type, 0, 4 );
505 506 507
            char buf[5];
            snprintf( buf, sizeof(buf), "%"PRIx16, i_tag );
            strncpy( p_stream->p_oggds_header->sub_type, buf, 4 );
508

509 510 511 512 513 514 515 516
            p_stream->p_oggds_header->i_time_unit = INT64_C(10000000);
            p_stream->p_oggds_header->i_default_len = 1;
            p_stream->p_oggds_header->i_buffer_size = 30*1024 ;
            p_stream->p_oggds_header->i_samples_per_unit = p_input->p_fmt->audio.i_rate;
            p_stream->p_oggds_header->i_bits_per_sample = p_input->p_fmt->audio.i_bitspersample;
            p_stream->p_oggds_header->header.audio.i_channels = p_input->p_fmt->audio.i_channels;
            p_stream->p_oggds_header->header.audio.i_block_align =  p_input->p_fmt->audio.i_blockalign;
            p_stream->p_oggds_header->header.audio.i_avgbytespersec =  p_input->p_fmt->i_bitrate / 8;
517 518
            msg_Dbg( p_mux, "%4.4s stream", (char *)&p_stream->i_fourcc );
            break;
519 520 521
        }
        break;

522 523 524
    case SPU_ES:
        switch( p_stream->i_fourcc )
        {
525
        case VLC_CODEC_SUBT:
526
            p_stream->p_oggds_header = calloc( 1, sizeof(oggds_header_t) );
527 528 529 530 531
            if( !p_stream->p_oggds_header )
            {
                free( p_stream );
                return VLC_ENOMEM;
            }
532 533 534
            p_stream->p_oggds_header->i_packet_type = PACKET_TYPE_HEADER;

            memcpy( p_stream->p_oggds_header->stream_type, "text", 4 );
535
            msg_Dbg( p_mux, "subtitles stream" );
536 537 538
            break;

        default:
539
            FREENULL( p_input->p_sys );
540
            return VLC_EGENERIC;
541 542
        }
        break;
543
    default:
544
        FREENULL( p_input->p_sys );
545
        return VLC_EGENERIC;
546 547
    }

548
    p_stream->b_new = true;
549 550

    p_sys->i_add_streams++;
551

552
    return VLC_SUCCESS;
553 554
}

555 556 557
/*****************************************************************************
 * DelStream: Delete an elementary stream from the muxed stream
 *****************************************************************************/
558
static void DelStream( sout_mux_t *p_mux, sout_input_t *p_input )
559
{
560 561
    sout_mux_sys_t *p_sys  = p_mux->p_sys;
    ogg_stream_t   *p_stream = (ogg_stream_t*)p_input->p_sys;
562
    block_t *p_og;
563

564
    msg_Dbg( p_mux, "removing input" );
565 566

    /* flush all remaining data */
567
    if( p_input->p_sys )
568
    {
569 570
        if( !p_stream->b_new )
        {
571 572
            while( block_FifoCount( p_input->p_fifo ) )
                MuxBlock( p_mux, p_input );
573 574
        }

575 576
        if( !p_stream->b_new &&
            ( p_og = OggStreamFlush( p_mux, &p_stream->os, 0 ) ) )
577 578
        {
            OggSetDate( p_og, p_stream->i_dts, p_stream->i_length );
579
            p_mux->p_sys->i_pos += sout_AccessOutWrite( p_mux->p_access, p_og );
580
        }
581

582 583
        /* move input in delete queue */
        if( !p_stream->b_new )
584
        {
585
            p_sys->pp_del_streams = xrealloc( p_sys->pp_del_streams,
586
                        (p_sys->i_del_streams + 1) * sizeof(ogg_stream_t *) );
587
            p_sys->pp_del_streams[p_sys->i_del_streams++] = p_stream;
588 589 590
        }
        else
        {
591
            /* wasn't already added so get rid of it */
592 593
            FREENULL( p_stream->p_oggds_header );
            FREENULL( p_stream );
594
            p_sys->i_add_streams--;
595 596
        }
    }
597 598

    p_input->p_sys = NULL;
599 600
}

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
/*****************************************************************************
 * Ogg Skeleton helpers
 *****************************************************************************/
static int WriteQWVariableLE( uint64_t i_64, uint64_t i_offset,
                              uint8_t *p_buffer, int i_buffer_size )
{
    uint8_t *p_dest = p_buffer + i_offset;
    int i_written = 0;

    for(;;)
    {
        if ( p_dest - p_buffer >= i_buffer_size ) return -1;

        *p_dest = (uint8_t) ( i_64 & 0x7F );
        i_64 >>= 7;
        i_written++;

        if ( i_64 == 0 )
        {
            *p_dest |= 0x80;
            return i_written;
        }

        p_dest++;
    }
}

static bool AddIndexEntry( sout_mux_t *p_mux, uint64_t i_time, sout_input_t *p_input )
{
    sout_mux_sys_t *p_sys = p_mux->p_sys;
    ogg_stream_t *p_stream = (ogg_stream_t *) p_input->p_sys;
    uint64_t i_posdelta;
    uint64_t i_timedelta;
    if ( !p_sys->skeleton.b_create || p_mux->p_sys->skeleton.i_index_intvl == 0
         || !p_stream->skeleton.p_index )
        return false;

    if ( p_stream->skeleton.i_last_keyframe_pos == 0 )
        p_stream->skeleton.i_last_keyframe_pos = p_sys->i_segment_start;
    i_posdelta = p_sys->i_pos - p_stream->skeleton.i_last_keyframe_pos;
    i_timedelta = i_time - p_stream->skeleton.i_last_keyframe_time;

643
    if ( i_timedelta <= ( (uint64_t) p_mux->p_sys->skeleton.i_index_intvl * 1000 )
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
         || i_posdelta <= 0xFFFF )
        return false;

    /* do inserts */
    int i_ret;
    if ( !p_stream->skeleton.p_index ) return false;
    uint64_t i_offset = p_stream->skeleton.i_index_payload;
    i_ret = WriteQWVariableLE( i_posdelta, i_offset, p_stream->skeleton.p_index,
                               p_stream->skeleton.i_index_size );
    if ( i_ret == -1 ) return false;
    i_offset += i_ret;
    i_ret = WriteQWVariableLE( i_timedelta, i_offset, p_stream->skeleton.p_index,
                               p_stream->skeleton.i_index_size );
    if ( i_ret == -1 ) return false;
    p_stream->skeleton.i_index_payload = i_offset + i_ret;
    p_stream->skeleton.i_index_count++;

    /* update diff points */
    p_stream->skeleton.i_last_keyframe_pos = p_sys->i_pos;
    p_stream->skeleton.i_last_keyframe_time = i_time;
664
    msg_Dbg( p_mux, "Added index on stream %d entry %zd %"PRIu64,
665 666 667 668 669
             p_stream->i_serial_no, p_sys->i_pos - p_sys->i_segment_start, i_time );

    return true;
}

670 671 672
/*****************************************************************************
 * Ogg bitstream manipulation routines
 *****************************************************************************/
ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
673 674 675
static block_t *OggStreamGetPage( sout_mux_t *p_mux,
                                  ogg_stream_state *p_os, mtime_t i_pts,
                                  bool flush )
676
{
677
    (void)p_mux;
678
    block_t *p_og, *p_og_first = NULL;
679
    ogg_page og;
ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
680
    int (*pager)( ogg_stream_state*, ogg_page* ) = flush ? ogg_stream_flush : ogg_stream_pageout;
681

ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
682
    while( pager( p_os, &og ) )
683
    {
684
        /* Flush all data */
685
        p_og = block_Alloc( og.header_len + og.body_len );
686

687 688
        memcpy( p_og->p_buffer, og.header, og.header_len );
        memcpy( p_og->p_buffer + og.header_len, og.body, og.body_len );
689 690 691 692
        p_og->i_dts     = 0;
        p_og->i_pts     = i_pts;
        p_og->i_length  = 0;

693
        i_pts = 0; // write it only once
694

695
        block_ChainAppend( &p_og_first, p_og );
696 697
    }

698
    return p_og_first;
699
}
700

ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
701 702 703 704 705 706
static block_t *OggStreamFlush( sout_mux_t *p_mux,
                                ogg_stream_state *p_os, mtime_t i_pts )
{
    return OggStreamGetPage( p_mux, p_os, i_pts, true );
}

707
static block_t *OggStreamPageOut( sout_mux_t *p_mux,
708
                                  ogg_stream_state *p_os, mtime_t i_pts )
709
{
ogg.k.ogg.k's avatar
ogg.k.ogg.k committed
710
    return OggStreamGetPage( p_mux, p_os, i_pts, false );
711
}
712

713 714
static void OggGetSkeletonIndex( uint8_t **pp_buffer, long *pi_size, ogg_stream_t *p_stream )
{
715
    uint8_t *p_buffer = calloc( INDEX_BASE_SIZE + p_stream->skeleton.i_index_size, sizeof(uint8_t) );
716 717 718 719 720 721 722 723 724 725 726 727
    if ( !p_buffer ) return;
    *pp_buffer = p_buffer;

    memcpy( p_buffer, "index", 6 );
    SetDWLE( &p_buffer[6], p_stream->i_serial_no );
    SetQWLE( &p_buffer[10], p_stream->skeleton.i_index_count ); /* num keypoints */
    SetQWLE( &p_buffer[18], 1000000 );
    SetQWLE( &p_buffer[34], p_stream->i_length );
    memcpy( p_buffer + INDEX_BASE_SIZE, p_stream->skeleton.p_index, p_stream->skeleton.i_index_payload );
    *pi_size = INDEX_BASE_SIZE + p_stream->skeleton.i_index_size;
}

728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
static void OggGetSkeletonFisbone( uint8_t **pp_buffer, long *pi_size,
                                   sout_input_t *p_input, sout_mux_t *p_mux )
{
    uint8_t *psz_header;
    uint8_t *p_buffer;
    const char *psz_value = NULL;
    ogg_stream_t *p_stream = (ogg_stream_t *) p_input->p_sys;
    struct
    {
        char *psz_content_type;
        char *psz_role;
        long int i_size;
        unsigned int i_count;
    } headers = { NULL, NULL, 0, 0 };
    *pi_size = 0;

    switch( p_stream->i_fourcc )
    {
        case VLC_CODEC_VORBIS:
            psz_value = "audio/vorbis";
            break;
        case VLC_CODEC_THEORA:
            psz_value = "video/theora";
            break;
752 753 754
        case VLC_CODEC_DAALA:
            psz_value = "video/daala";
            break;
755 756 757 758 759 760 761 762 763 764 765 766
        case VLC_CODEC_SPEEX:
            psz_value = "audio/speex";
            break;
        case VLC_CODEC_FLAC:
            psz_value = "audio/flac";
            break;
        case VLC_CODEC_CMML:
            psz_value = "text/cmml";
            break;
        case VLC_CODEC_KATE:
            psz_value = "application/kate";
            break;
767 768 769
        case VLC_CODEC_VP8:
            psz_value = "video/x-vp8";
            break;
770 771
        default:
            psz_value = "application/octet-stream";
Tristan Matthews's avatar
Tristan Matthews committed
772
            msg_Warn( p_mux, "Unknown fourcc for stream %s, setting Content-Type to %s",
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
                  vlc_fourcc_GetDescription( p_stream->i_cat, p_stream->i_fourcc ),
                  psz_value );
    }

    /* Content Type Header */
    if ( asprintf( &headers.psz_content_type, "Content-Type: %s\r\n", psz_value ) != -1 )
    {
        headers.i_size += strlen( headers.psz_content_type );
        headers.i_count++;
    }

    /* Set Role Header */
    if ( p_input->p_fmt->i_priority > ES_PRIORITY_NOT_SELECTABLE )
    {
        int i_max_prio = ES_PRIORITY_MIN;
        for ( int i=0; i< p_mux->i_nb_inputs; i++ )
        {
            if ( p_mux->pp_inputs[i]->p_fmt->i_cat != p_input->p_fmt->i_cat ) continue;
            i_max_prio = __MAX( p_mux->pp_inputs[i]->p_fmt->i_priority, i_max_prio );
        }

        psz_value = NULL;
        if ( p_input->p_fmt->i_cat == AUDIO_ES || p_input->p_fmt->i_cat == VIDEO_ES )
        {
            if ( p_input->p_fmt->i_priority == i_max_prio && i_max_prio >= ES_PRIORITY_SELECTABLE_MIN )
                psz_value = ( p_input->p_fmt->i_cat == VIDEO_ES ) ?
                            "video/main" : "audio/main";
            else
                psz_value = ( p_input->p_fmt->i_cat == VIDEO_ES ) ?
                            "video/alternate" : "audio/alternate";
        }
        else if ( p_input->p_fmt->i_cat == SPU_ES )
        {
            psz_value = ( p_input->p_fmt->i_codec == VLC_CODEC_KATE ) ?
                        "text/karaoke" : "text/subtitle";
        }

        if ( psz_value && asprintf( &headers.psz_role, "Role: %s\r\n", psz_value ) != -1 )
        {
            headers.i_size += strlen( headers.psz_role );
            headers.i_count++;
        }
    }

    *pp_buffer = calloc( FISBONE_BASE_SIZE + headers.i_size, sizeof(uint8_t) );
    if ( !*pp_buffer ) return;
    p_buffer = *pp_buffer;

    memcpy( p_buffer, "fisbone", 8 );
    SetDWLE( &p_buffer[8], FISBONE_BASE_OFFSET ); /* offset to message headers */
    SetDWLE( &p_buffer[12], p_stream->i_serial_no );
    SetDWLE( &p_buffer[16], headers.i_count );

    /* granulerate den */
    switch ( p_input->p_fmt->i_cat )
    {
        case VIDEO_ES:
            SetQWLE( &(*pp_buffer)[20], p_input->p_fmt->video.i_frame_rate );
            SetQWLE( &(*pp_buffer)[28], p_input->p_fmt->video.i_frame_rate_base );
        break;
        case AUDIO_ES:
            SetQWLE( &(*pp_buffer)[20], p_input->p_fmt->audio.i_rate );
            SetQWLE( &(*pp_buffer)[28], 1 );
        break;
        default:
            SetQWLE( &(*pp_buffer)[20], 1000 );
            SetQWLE( &(*pp_buffer)[28], 1 );
    }

    /* preroll */
    if ( p_input->p_fmt->p_extra )
844
        SetDWLE( &(*pp_buffer)[44], xiph_CountHeaders( p_input->p_fmt->p_extra, p_input->p_fmt->i_extra ) );
845

846 847 848 849 850 851 852 853
    if ( headers.i_size > 0 )
    {
        psz_header = *pp_buffer + FISBONE_BASE_SIZE;
        memcpy( psz_header, headers.psz_content_type, strlen( headers.psz_content_type ) );
        psz_header += strlen( headers.psz_content_type );
        if ( headers.psz_role )
            memcpy( psz_header, headers.psz_role, strlen( headers.psz_role ) );
    }
854 855 856 857 858 859 860 861 862 863 864 865 866
    *pi_size = FISBONE_BASE_SIZE + headers.i_size;

    free( headers.psz_content_type );
    free( headers.psz_role );
}

static void OggFillSkeletonFishead( uint8_t *p_buffer, sout_mux_t *p_mux )
{
    memcpy( p_buffer, "fishead", 8 );
    SetWLE( &p_buffer[8], 4 );
    SetWLE( &p_buffer[10], 0 );
    SetQWLE( &p_buffer[20], 1000 );
    SetQWLE( &p_buffer[36], 1000 );
867 868
    SetQWLE( &p_buffer[64], p_mux->p_sys->i_pos - p_mux->p_sys->i_segment_start ); /* segment length */
    SetQWLE( &p_buffer[72], p_mux->p_sys->i_data_start - p_mux->p_sys->i_segment_start ); /* data start offset */
869 870
}

871 872 873 874 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
static int32_t OggFillDsHeader( uint8_t *p_buffer, oggds_header_t *p_oggds_header, int i_cat )
{
    int index = 0;
    p_buffer[index] = p_oggds_header->i_packet_type;
    index++;
    memcpy( &p_buffer[index], p_oggds_header->stream_type, sizeof(p_oggds_header->stream_type) );
    index += sizeof(p_oggds_header->stream_type);
    memcpy(&p_buffer[index], p_oggds_header->sub_type, sizeof(p_oggds_header->sub_type) );
    index += sizeof(p_oggds_header->sub_type);

    /* The size is filled at the end */
    uint8_t *p_isize = &p_buffer[index];
    index += 4;

    SetQWLE( &p_buffer[index], p_oggds_header->i_time_unit );
    index += 8;
    SetQWLE( &p_buffer[index], p_oggds_header->i_samples_per_unit );
    index += 8;
    SetDWLE( &p_buffer[index], p_oggds_header->i_default_len );
    index += 4;
    SetDWLE( &p_buffer[index], p_oggds_header->i_buffer_size );
    index += 4;
    SetWLE( &p_buffer[index], p_oggds_header->i_bits_per_sample );
    index += 2;
    SetWLE( &p_buffer[index], p_oggds_header->i_padding_0 );
    index += 2;
    /* audio or video */
    switch( i_cat )
    {
    case VIDEO_ES:
        SetDWLE( &p_buffer[index], p_oggds_header->header.video.i_width );
        SetDWLE( &p_buffer[index+4], p_oggds_header->header.video.i_height );
        break;
    case AUDIO_ES:
        SetWLE( &p_buffer[index], p_oggds_header->header.audio.i_channels );
        SetWLE( &p_buffer[index+2], p_oggds_header->header.audio.i_block_align );
        SetDWLE( &p_buffer[index+4], p_oggds_header->header.audio.i_avgbytespersec );
        break;
    }
    index += 8;
    SetDWLE( &p_buffer[index], p_oggds_header->i_padding_1 );
    index += 4;

    /* extra header */
    if( p_oggds_header->i_size > 0 )
    {
917
        memcpy( &p_buffer[index], (uint8_t *) p_oggds_header + sizeof(*p_oggds_header), p_oggds_header->i_size );
918 919 920 921 922 923 924
        index += p_oggds_header->i_size;
    }

    SetDWLE( p_isize, index-1 );
    return index;
}

925 926 927 928 929 930 931 932 933 934 935
static void OggFillVP8Header( uint8_t *p_buffer, sout_input_t *p_input )
{
    memcpy( p_buffer, "OVP80\x01\x01\x00", 8 );
    SetWBE( &p_buffer[8], p_input->p_fmt->video.i_width );
    SetDWBE( &p_buffer[14], p_input->p_fmt->video.i_sar_den );/* 24 bits, 15~ */
    SetDWBE( &p_buffer[11], p_input->p_fmt->video.i_sar_num );/* 24 bits, 12~ */
    SetWBE( &p_buffer[10], p_input->p_fmt->video.i_height );
    SetDWBE( &p_buffer[18], p_input->p_fmt->video.i_frame_rate );
    SetDWBE( &p_buffer[22], p_input->p_fmt->video.i_frame_rate_base );
}

936
static bool OggCreateHeaders( sout_mux_t *p_mux )
937
{
938
    block_t *p_hdr = NULL;
939 940
    block_t *p_og = NULL;
    ogg_packet op;
941 942
    ogg_stream_t *p_stream;
    sout_mux_sys_t *p_sys = p_mux->p_sys;
943
    int i;
944 945 946 947 948 949 950 951 952

    if( sout_AccessOutControl( p_mux->p_access,
                               ACCESS_OUT_CAN_SEEK,
                               &p_sys->skeleton.b_create ) )
    {
        p_sys->skeleton.b_create = false;
    }

    p_sys->skeleton.b_create &= !! p_mux->i_nb_inputs;
953 954 955 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

    /* no skeleton for solo vorbis/speex/opus tracks */
    if ( p_mux->i_nb_inputs == 1 && p_mux->pp_inputs[0]->p_fmt->i_cat == AUDIO_ES )
    {
        p_sys->skeleton.b_create = false;
    }
    else
    {
        for ( int i=0; i< p_mux->i_nb_inputs; i++ )
        {
            p_stream = (ogg_stream_t*) p_mux->pp_inputs[i]->p_sys;
            if ( p_stream->p_oggds_header )
            {
                /* We don't want skeleton for OggDS */
                p_sys->skeleton.b_create = false;
                break;
            }
        }
    }

    /* Skeleton's Fishead must be the first page of the stream */
    if ( p_sys->skeleton.b_create && !p_sys->skeleton.b_head_done )
    {
        msg_Dbg( p_mux, "creating header for skeleton" );
        p_sys->skeleton.i_serial_no = p_sys->i_next_serial_no++;
        ogg_stream_init( &p_sys->skeleton.os, p_sys->skeleton.i_serial_no );
        op.bytes = 80;
        op.packet = calloc( 1, op.bytes );
981
        if ( op.packet == NULL ) return false;
982 983 984 985 986 987 988 989 990
        op.b_o_s = 1;
        op.e_o_s = 0;
        op.granulepos = 0;
        op.packetno = 0;
        OggFillSkeletonFishead( op.packet, p_mux );
        ogg_stream_packetin( &p_sys->skeleton.os, &op );
        p_og = OggStreamFlush( p_mux, &p_sys->skeleton.os, 0 );
        block_ChainAppend( &p_hdr, p_og );
        p_sys->skeleton.b_head_done = true;
991
        p_sys->skeleton.i_fishead_offset = p_sys->i_pos;
992
    }
993

994 995
    /* Write header for each stream. All b_o_s (beginning of stream) packets
     * must appear first in the ogg stream so we take care of them first. */
996
    for( int pass = 0; pass < 2; pass++ )
997
    {
998 999 1000
        for( i = 0; i < p_mux->i_nb_inputs; i++ )
        {
            sout_input_t *p_input = p_mux->pp_inputs[i];
1001
            p_stream = (ogg_stream_t*)p_input->p_sys;
1002

1003 1004 1005
            bool video = ( p_stream->i_fourcc == VLC_CODEC_THEORA ||
                           p_stream->i_fourcc == VLC_CODEC_DIRAC ||
                           p_stream->i_fourcc == VLC_CODEC_DAALA );
1006 1007
            if( ( ( pass == 0 && !video ) || ( pass == 1 && video ) ) )
                continue;
1008

1009 1010
            msg_Dbg( p_mux, "creating header for %4.4s",
                     (char *)&p_stream->i_fourcc );
1011

1012 1013 1014
            ogg_stream_init( &p_stream->os, p_stream->i_serial_no );
            p_stream->b_new = false;
            p_stream->i_packet_no = 0;
1015
            p_stream->b_started = true;
1016 1017 1018

            if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
                p_stream->i_fourcc == VLC_CODEC_SPEEX ||
Tristan Matthews's avatar
Tristan Matthews committed
1019
                p_stream->i_fourcc == VLC_CODEC_OPUS ||
1020 1021
                p_stream->i_fourcc == VLC_CODEC_THEORA ||
                p_stream->i_fourcc == VLC_CODEC_DAALA )
1022
            {
1023
                /* First packet in order: vorbis/speex/opus/theora/daala info */
1024 1025 1026 1027 1028
                unsigned pi_size[XIPH_MAX_HEADER_COUNT];
                void     *pp_data[XIPH_MAX_HEADER_COUNT];
                unsigned i_count;
                if( xiph_SplitHeaders( pi_size, pp_data, &i_count,
                                       p_input->p_fmt->i_extra, p_input->p_fmt->p_extra ) )
1029
                {
1030 1031 1032
                    i_count = 0;
                    pi_size[0] = 0;
                    pp_data[0] = NULL;
1033 1034
                }

1035 1036 1037 1038 1039
                op.bytes  = pi_size[0];
                op.packet = pp_data[0];
                if( pi_size[0] <= 0 )
                    msg_Err( p_mux, "header data corrupted");

1040 1041 1042 1043 1044 1045 1046
                op.b_o_s  = 1;
                op.e_o_s  = 0;
                op.granulepos = 0;
                op.packetno = p_stream->i_packet_no++;
                ogg_stream_packetin( &p_stream->os, &op );
                p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );

1047 1048 1049
                /* Get keyframe_granule_shift for theora or daala granulepos calculation */
                if( p_stream->i_fourcc == VLC_CODEC_THEORA ||
                    p_stream->i_fourcc == VLC_CODEC_DAALA )
1050 1051 1052 1053
                {
                    p_stream->i_keyframe_granule_shift =
                        ( (op.packet[40] & 0x03) << 3 ) | ( (op.packet[41] & 0xe0) >> 5 );
                }
1054
            }
1055
            else if( p_stream->i_fourcc == VLC_CODEC_DIRAC )
1056
            {
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
                op.packet = p_input->p_fmt->p_extra;
                op.bytes  = p_input->p_fmt->i_extra;
                op.b_o_s  = 1;
                op.e_o_s  = 0;
                op.granulepos = ~0;
                op.packetno = p_stream->i_packet_no++;
                ogg_stream_packetin( &p_stream->os, &op );
                p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
            }
            else if( p_stream->i_fourcc == VLC_CODEC_FLAC )
            {
                /* flac stream marker (yeah, only that in the 1st packet) */
                op.packet = (unsigned char *)"fLaC";
                op.bytes  = 4;
                op.b_o_s  = 1;
                op.e_o_s  = 0;
                op.granulepos = 0;
                op.packetno = p_stream->i_packet_no++;
                ogg_stream_packetin( &p_stream->os, &op );
                p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
            }
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
            else if( p_stream->i_fourcc == VLC_CODEC_VP8 )
            {
                /* VP8 Header */
                op.packet = malloc( 26 );
                if( !op.packet )
                    return false;
                op.bytes = 26;
                OggFillVP8Header( op.packet, p_input );
                op.b_o_s = 1;
                op.e_o_s = 0;
                op.granulepos = 0;
                op.packetno = p_stream->i_packet_no++;
                ogg_stream_packetin( &p_stream->os, &op );
                p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
                free( op.packet );
            }
1094 1095 1096
            else if( p_stream->p_oggds_header )
            {
                /* ds header */
1097 1098
                op.packet = malloc( sizeof(*p_stream->p_oggds_header) + p_stream->p_oggds_header->i_size );
                if( !op.packet )
1099
                    return false;
1100
                op.bytes  = OggFillDsHeader( op.packet, p_stream->p_oggds_header, p_stream->i_cat );
1101 1102 1103 1104 1105 1106
                op.b_o_s  = 1;
                op.e_o_s  = 0;
                op.granulepos = 0;
                op.packetno = p_stream->i_packet_no++;
                ogg_stream_packetin( &p_stream->os, &op );
                p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
1107
                free( op.packet );
1108
            }
1109

1110 1111
            block_ChainAppend( &p_hdr, p_og );
        }
1112 1113
    }

1114 1115 1116 1117 1118 1119 1120
    /* Create fisbones if any */
    if ( p_sys->skeleton.b_create )
    {
        for( i = 0; i < p_mux->i_nb_inputs; i++ )
        {
            sout_input_t *p_input = p_mux->pp_inputs[i];
            ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
1121
            if ( p_stream->skeleton.b_fisbone_done ) continue;
1122
            OggGetSkeletonFisbone( &op.packet, &op.bytes, p_input, p_mux );
1123
            if ( op.packet == NULL ) return false;
1124 1125 1126 1127 1128 1129 1130
            op.b_o_s = 0;
            op.e_o_s = 0;
            op.granulepos = 0;
            op.packetno = p_sys->skeleton.i_packet_no++;
            ogg_stream_packetin( &p_sys->skeleton.os, &op );
            p_og = OggStreamFlush( p_mux, &p_sys->skeleton.os, 0 );
            block_ChainAppend( &p_hdr, p_og );
1131 1132 1133 1134 1135
            p_stream->skeleton.b_fisbone_done = true;
        }
    }

    /* Write previous headers */
1136 1137 1138 1139 1140
    for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
    {
        /* flag headers to be resent for streaming clients */
        p_og->i_flags |= BLOCK_FLAG_HEADER;
    }
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
    p_mux->p_sys->i_pos += sout_AccessOutWrite( p_mux->p_access, p_hdr );
    p_hdr = NULL;

    /* Create indexes if any */
    for( i = 0; i < p_mux->i_nb_inputs; i++ )
    {
        sout_input_t *p_input = p_mux->pp_inputs[i];
        ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
        /* flush stream && save offset */
        if ( p_sys->skeleton.b_create && !p_stream->skeleton.b_index_done )
        {
            if ( !p_stream->skeleton.p_index ) AllocateIndex( p_mux, p_input );
            if ( p_stream->skeleton.p_index )
            {
                msg_Dbg( p_mux, "Creating index for stream %d", p_stream->i_serial_no );
                OggGetSkeletonIndex( &op.packet, &op.bytes, p_stream );
                if ( op.packet == NULL ) return false;
                op.b_o_s = 0;
                op.e_o_s = 0;
                op.granulepos = 0;
                op.packetno = p_sys->skeleton.i_packet_no++;

                /* backup some values */
                p_stream->skeleton.i_index_offset = p_mux->p_sys->i_pos;
                p_stream->skeleton.i_index_packetno = p_sys->skeleton.os.packetno;
                p_stream->skeleton.i_index_pageno = p_sys->skeleton.os.pageno;

                ogg_stream_packetin( &p_sys->skeleton.os, &op );
                p_og = OggStreamFlush( p_mux, &p_sys->skeleton.os, 0 );
                p_mux->p_sys->i_pos += sout_AccessOutWrite( p_mux->p_access, p_og );
            }
            p_stream->skeleton.b_index_done = true;
1173 1174 1175
        }
    }

1176 1177 1178
    /* Take care of the non b_o_s headers */
    for( i = 0; i < p_mux->i_nb_inputs; i++ )
    {
1179 1180
        sout_input_t *p_input = p_mux->pp_inputs[i];
        ogg_stream_t *p_stream = (ogg_stream_t*)p_input->p_sys;
1181

1182 1183
        if( p_stream->i_fourcc == VLC_CODEC_VORBIS ||
            p_stream->i_fourcc == VLC_CODEC_SPEEX ||
Tristan Matthews's avatar
Tristan Matthews committed
1184
            p_stream->i_fourcc == VLC_CODEC_OPUS ||
1185 1186
            p_stream->i_fourcc == VLC_CODEC_THEORA ||
            p_stream->i_fourcc == VLC_CODEC_DAALA )
1187
        {
1188 1189 1190 1191 1192 1193 1194
            unsigned pi_size[XIPH_MAX_HEADER_COUNT];
            void     *pp_data[XIPH_MAX_HEADER_COUNT];
            unsigned i_count;
            if( xiph_SplitHeaders( pi_size, pp_data, &i_count,
                                   p_input->p_fmt->i_extra, p_input->p_fmt->p_extra ) )
                i_count = 0;

1195 1196
            /* Special case, headers are already there in the incoming stream.
             * We need to gather them an mark them as headers. */
1197
            for( unsigned i = 1; i < i_count; i++ )
1198
            {
1199 1200 1201
                op.bytes  = pi_size[i];
                op.packet = pp_data[i];
                if( pi_size[i] <= 0 )
1202
                    msg_Err( p_mux, "header data corrupted");
1203

1204 1205 1206 1207 1208
                op.b_o_s  = 0;
                op.e_o_s  = 0;
                op.granulepos = 0;
                op.packetno = p_stream->i_packet_no++;
                ogg_stream_packetin( &p_stream->os, &op );
1209
                msg_Dbg( p_mux, "adding non bos, secondary header" );
1210
                if( i == i_count - 1 )
1211 1212 1213 1214 1215
                    p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
                else
                    p_og = OggStreamPageOut( p_mux, &p_stream->os, 0 );
                if( p_og )
                    block_ChainAppend( &p_hdr, p_og );
1216 1217
            }
        }
1218 1219
        else if( p_stream->i_fourcc != VLC_CODEC_FLAC &&
                 p_stream->i_fourcc != VLC_CODEC_DIRAC )
1220 1221 1222 1223
        {
            uint8_t com[128];
            int     i_com;

1224 1225
            /* comment */
            com[0] = PACKET_TYPE_COMMENT;
Antoine Cellerier's avatar
Antoine Cellerier committed
1226 1227
            i_com = snprintf( (char *)(com+1), 127,
                              PACKAGE_VERSION" stream output" )
Sam Hocevar's avatar
Sam Hocevar committed
1228
                     + 1;
1229 1230 1231 1232 1233 1234 1235
            op.packet = com;
            op.bytes  = i_com;
            op.b_o_s  = 0;
            op.e_o_s  = 0;
            op.granulepos = 0;
            op.packetno = p_stream->i_packet_no++;
            ogg_stream_packetin( &p_stream->os, &op );
1236
            p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
1237
            block_ChainAppend( &p_hdr, p_og );
1238
        }
1239

1240
        /* Special case for mp4v and flac */
1241 1242
        if( ( p_stream->i_fourcc == VLC_CODEC_MP4V ||
              p_stream->i_fourcc == VLC_CODEC_FLAC ) &&
1243
            p_input->p_fmt->i_extra )
1244
        {
1245 1246 1247
            /* Send a packet with the VOL data for mp4v
             * or STREAMINFO for flac */
            msg_Dbg( p_mux, "writing extra data" );
1248 1249
            op.bytes  = p_input->p_fmt->i_extra;
            op.packet = p_input->p_fmt->p_extra;
1250
            uint8_t flac_streaminfo[34 + 4];
1251
            if( p_stream->i_fourcc == VLC_CODEC_FLAC )
1252
            {
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
                if (op.bytes == 42 && !memcmp(op.packet, "fLaC", 4)) {
                    op.bytes -= 4;
                    memcpy(flac_streaminfo, op.packet + 4, 38);
                    op.packet = flac_streaminfo;
                } else if (op.bytes == 34) {
                    op.bytes += 4;
                    memcpy(flac_streaminfo + 4, op.packet, 34);
                    flac_streaminfo[0] = 0x80; /* last block, streaminfo */
                    flac_streaminfo[1] = 0;
                    flac_streaminfo[2] = 0;
                    flac_streaminfo[3] = 34; /* block size */
                    op.packet = flac_streaminfo;
                } else {
1266 1267
                    msg_Err(p_mux, "Invalid FLAC streaminfo (%ld bytes)",
                            op.bytes);
1268
                }
1269
            }
1270 1271 1272 1273 1274 1275
            op.b_o_s  = 0;
            op.e_o_s  = 0;
            op.granulepos = 0;
            op.packetno = p_stream->i_packet_no++;
            ogg_stream_packetin( &p_stream->os, &op );
            p_og = OggStreamFlush( p_mux, &p_stream->os, 0 );
1276
            block_ChainAppend( &p_hdr, p_og );
1277
        }
1278 1279
    }

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    if ( p_sys->skeleton.b_create )
    {
        msg_Dbg( p_mux, "ending skeleton" );
        op.packet = NULL;
        op.bytes = 0;
        op.b_o_s = 0;
        op.e_o_s = 1;
        op.granulepos = 0;
        op.packetno = p_sys->skeleton.i_packet_no++;
        ogg_stream_packetin( &p_sys->skeleton.os, &op );
        p_og = OggStreamFlush( p_mux, &p_sys->skeleton.os, 0 );
        block_ChainAppend( &p_hdr, p_og );
    }

1294
    /* set HEADER flag */
1295
    /* flag headers to be resent for streaming clients */
1296 1297
    for( p_og = p_hdr; p_og != NULL; p_og = p_og->p_next )
    {
1298
        p_og->i_flags |= BLOCK_FLAG_HEADER;
1299
    }
1300 1301 1302 1303 1304

    /* Write previous headers */
    p_mux->p_sys->i_pos += sout_AccessOutWrite( p_mux->p_access, p_hdr );

    return true;
1305 1306
}

1307
static void OggCreateStreamFooter( sout_mux_t *p_mux, ogg_stream_t *p_stream )
1308
{
1309
    block_t *p_og;
1310
    ogg_packet op;
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
    sout_mux_sys_t *p_sys = p_mux->p_sys;

    /* as stream is finished, overwrite the index, if there was any */
    if ( p_sys->skeleton.b_create && p_stream->skeleton.p_index
         && p_stream->skeleton.i_index_payload )
    {
        sout_AccessOutSeek( p_mux->p_access, p_stream->skeleton.i_index_offset );
        OggGetSkeletonIndex( &op.packet, &op.bytes, p_stream );
        if ( op.