transcode.c 102 KB
Newer Older
1
/*****************************************************************************
Gildas Bazin's avatar
 
Gildas Bazin committed
2
 * transcode.c: transcoding stream output module
3
 *****************************************************************************
4
 * Copyright (C) 2003-2008 the VideoLAN team
5
 * $Id$
6 7
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8
 *          Gildas Bazin <gbazin@videolan.org>
9
 *          Jean-Paul Saman <jpsaman #_at_# m2x dot nl>
10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
Antoine Cellerier's avatar
Antoine Cellerier committed
23
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 25 26 27 28
 *****************************************************************************/

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

33
#include <vlc/vlc.h>
34
#include <vlc_plugin.h>
Clément Stenac's avatar
Clément Stenac committed
35 36 37 38 39 40
#include <vlc_input.h>
#include <vlc_sout.h>
#include <vlc_aout.h>
#include <vlc_vout.h>
#include <vlc_codec.h>
#include <vlc_block.h>
41 42
#include <vlc_filter.h>
#include <vlc_osd.h>
43

44 45
#include <math.h>

46 47
#define MASTER_SYNC_MAX_DRIFT 100000

48
/*****************************************************************************
49
 * Module descriptor
50
 *****************************************************************************/
51 52
#define VENC_TEXT N_("Video encoder")
#define VENC_LONGTEXT N_( \
53 54
    "This is the video encoder module that will be used (and its associated "\
    "options).")
55 56
#define VCODEC_TEXT N_("Destination video codec")
#define VCODEC_LONGTEXT N_( \
57
    "This is the video codec that will be used.")
58 59
#define VB_TEXT N_("Video bitrate")
#define VB_LONGTEXT N_( \
60
    "Target bitrate of the transcoded video stream." )
61 62
#define SCALE_TEXT N_("Video scaling")
#define SCALE_LONGTEXT N_( \
63
    "Scale factor to apply to the video while transcoding (eg: 0.25)")
64 65
#define FPS_TEXT N_("Video frame-rate")
#define FPS_LONGTEXT N_( \
66
    "Target output frame rate for the video stream." )
67 68
#define DEINTERLACE_TEXT N_("Deinterlace video")
#define DEINTERLACE_LONGTEXT N_( \
69
    "Deinterlace the video before encoding." )
70 71
#define DEINTERLACE_MODULE_TEXT N_("Deinterlace module")
#define DEINTERLACE_MODULE_LONGTEXT N_( \
72
    "Specify the deinterlace module to use." )
73 74
#define WIDTH_TEXT N_("Video width")
#define WIDTH_LONGTEXT N_( \
75
    "Output video width." )
76 77
#define HEIGHT_TEXT N_("Video height")
#define HEIGHT_LONGTEXT N_( \
78
    "Output video height." )
79 80
#define MAXWIDTH_TEXT N_("Maximum video width")
#define MAXWIDTH_LONGTEXT N_( \
81
    "Maximum output video width." )
82 83
#define MAXHEIGHT_TEXT N_("Maximum video height")
#define MAXHEIGHT_LONGTEXT N_( \
84
    "Maximum output video height." )
85 86
#define VFILTER_TEXT N_("Video filter")
#define VFILTER_LONGTEXT N_( \
87 88
    "Video filters will be applied to the video streams (after overlays " \
    "are applied). You must enter a comma-separated list of filters." )
89

90
#define CROPTOP_TEXT N_("Video crop (top)")
91
#define CROPTOP_LONGTEXT N_( \
92 93
    "Number of pixels to crop at the top of the video." )
#define CROPLEFT_TEXT N_("Video crop (left)")
94
#define CROPLEFT_LONGTEXT N_( \
95 96
    "Number of pixels to crop at the left of the video." )
#define CROPBOTTOM_TEXT N_("Video crop (bottom)")
97
#define CROPBOTTOM_LONGTEXT N_( \
98 99
    "Number of pixels to crop at the bottom of the video." )
#define CROPRIGHT_TEXT N_("Video crop (right)")
100
#define CROPRIGHT_LONGTEXT N_( \
101
    "Number of pixels to crop at the right of the video." )
102

103
#define PADDTOP_TEXT N_("Video padding (top)")
104
#define PADDTOP_LONGTEXT N_( \
105 106
    "Size of the black border to add at the top of the video." )
#define PADDLEFT_TEXT N_("Video padding (left)")
107
#define PADDLEFT_LONGTEXT N_( \
108 109
    "Size of the black border to add at the left of the video." )
#define PADDBOTTOM_TEXT N_("Video padding (bottom)")
110
#define PADDBOTTOM_LONGTEXT N_( \
111 112
    "Size of the black border to add at the bottom of the video." )
#define PADDRIGHT_TEXT N_("Video padding (right)")
113
#define PADDRIGHT_LONGTEXT N_( \
114
    "Size of the black border to add at the right of the video." )
115 116 117

#define CANVAS_WIDTH_TEXT N_("Video canvas width")
#define CANVAS_WIDTH_LONGTEXT N_( \
118
    "This will automatically crod and pad the video to a specified width." )
119 120
#define CANVAS_HEIGHT_TEXT N_("Video canvas height")
#define CANVAS_HEIGHT_LONGTEXT N_( \
121
    "This will automatically crod and pad the video to a specified height." )
122 123
#define CANVAS_ASPECT_TEXT N_("Video canvas aspect ratio")
#define CANVAS_ASPECT_LONGTEXT N_( \
124 125
    "This sets aspect (like 4:3) of the video canvas and letterbox the video "\
    "accordingly." )
126

127 128
#define AENC_TEXT N_("Audio encoder")
#define AENC_LONGTEXT N_( \
129 130
    "This is the audio encoder module that will be used (and its associated "\
    "options).")
131 132
#define ACODEC_TEXT N_("Destination audio codec")
#define ACODEC_LONGTEXT N_( \
133
    "This is the audio codec that will be used.")
134 135
#define AB_TEXT N_("Audio bitrate")
#define AB_LONGTEXT N_( \
136
    "Target bitrate of the transcoded audio stream." )
137 138
#define ARATE_TEXT N_("Audio sample rate")
#define ARATE_LONGTEXT N_( \
139
 "Sample rate of the transcoded audio stream (11250, 22500, 44100 or 48000).")
140 141
#define ACHANS_TEXT N_("Audio channels")
#define ACHANS_LONGTEXT N_( \
142
    "Number of audio channels in the transcoded streams." )
143 144 145 146
#define AFILTER_TEXT N_("Audio filter")
#define AFILTER_LONGTEXT N_( \
    "Audio filters will be applied to the audio streams (after conversion " \
    "filters are applied). You must enter a comma-separated list of filters." )
147

148 149
#define SENC_TEXT N_("Subtitles encoder")
#define SENC_LONGTEXT N_( \
150 151
    "This is the subtitles encoder module that will be used (and its " \
    "associated options)." )
152 153
#define SCODEC_TEXT N_("Destination subtitles codec")
#define SCODEC_LONGTEXT N_( \
Clément Stenac's avatar
Clément Stenac committed
154
    "This is the subtitles codec that will be used." )
155 156

#define SFILTER_TEXT N_("Overlays")
157
#define SFILTER_LONGTEXT N_( \
158 159 160 161
    "This allows you to add overlays (also known as \"subpictures\" on the "\
    "transcoded video stream. The subpictures produced by the filters will "\
    "be overlayed directly onto the video. You must specify a comma-separated "\
    "list of subpicture modules" )
162

163 164
#define OSD_TEXT N_("OSD menu")
#define OSD_LONGTEXT N_(\
165
    "Stream the On Screen Display menu (using the osdmenu subpicture module)." )
166

167 168
#define THREADS_TEXT N_("Number of threads")
#define THREADS_LONGTEXT N_( \
169
    "Number of threads used for the transcoding." )
170 171 172 173
#define HP_TEXT N_("High priority")
#define HP_LONGTEXT N_( \
    "Runs the optional encoder thread at the OUTPUT priority instead of " \
    "VIDEO." )
174

175 176 177 178 179
#define ASYNC_TEXT N_("Synchronise on audio track")
#define ASYNC_LONGTEXT N_( \
    "This option will drop/duplicate video frames to synchronise the video " \
    "track on the audio track." )

180
#define HURRYUP_TEXT N_( "Hurry up" )
181 182
#define HURRYUP_LONGTEXT N_( "The transcoder will drop frames if your CPU " \
                "can't keep up with the encoding rate." )
183

184
static const char *ppsz_deinterlace_type[] =
185 186 187 188
{
    "deinterlace", "ffmpeg-deinterlace"
};

189 190 191
static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );

192 193
#define SOUT_CFG_PREFIX "sout-transcode-"

194
vlc_module_begin();
195 196
    set_shortname( N_("Transcode"));
    set_description( N_("Transcode stream output") );
197 198 199
    set_capability( "sout stream", 50 );
    add_shortcut( "transcode" );
    set_callbacks( Open, Close );
200 201
    set_category( CAT_SOUT );
    set_subcategory( SUBCAT_SOUT_STREAM );
202
    set_section( N_("Video"), NULL );
203
    add_string( SOUT_CFG_PREFIX "venc", NULL, NULL, VENC_TEXT,
204
                VENC_LONGTEXT, false );
205
    add_string( SOUT_CFG_PREFIX "vcodec", NULL, NULL, VCODEC_TEXT,
206
                VCODEC_LONGTEXT, false );
207
    add_integer( SOUT_CFG_PREFIX "vb", 800 * 1000, NULL, VB_TEXT,
208
                 VB_LONGTEXT, false );
209
    add_float( SOUT_CFG_PREFIX "scale", 1, NULL, SCALE_TEXT,
210
               SCALE_LONGTEXT, false );
211
    add_float( SOUT_CFG_PREFIX "fps", 0, NULL, FPS_TEXT,
212 213 214
               FPS_LONGTEXT, false );
    add_bool( SOUT_CFG_PREFIX "hurry-up", true, NULL, HURRYUP_TEXT,
               HURRYUP_LONGTEXT, false );
215
    add_bool( SOUT_CFG_PREFIX "deinterlace", 0, NULL, DEINTERLACE_TEXT,
216
              DEINTERLACE_LONGTEXT, false );
217 218
    add_string( SOUT_CFG_PREFIX "deinterlace-module", "deinterlace", NULL,
                DEINTERLACE_MODULE_TEXT, DEINTERLACE_MODULE_LONGTEXT,
219
                false );
220
        change_string_list( ppsz_deinterlace_type, 0, 0 );
221
    add_integer( SOUT_CFG_PREFIX "width", 0, NULL, WIDTH_TEXT,
222
                 WIDTH_LONGTEXT, true );
223
    add_integer( SOUT_CFG_PREFIX "height", 0, NULL, HEIGHT_TEXT,
224
                 HEIGHT_LONGTEXT, true );
225
    add_integer( SOUT_CFG_PREFIX "maxwidth", 0, NULL, MAXWIDTH_TEXT,
226
                 MAXWIDTH_LONGTEXT, true );
227
    add_integer( SOUT_CFG_PREFIX "maxheight", 0, NULL, MAXHEIGHT_TEXT,
228
                 MAXHEIGHT_LONGTEXT, true );
229
    add_module_list( SOUT_CFG_PREFIX "vfilter", "video filter2",
230
                     NULL, NULL,
231
                     VFILTER_TEXT, VFILTER_LONGTEXT, false );
232 233

    add_integer( SOUT_CFG_PREFIX "croptop", 0, NULL, CROPTOP_TEXT,
234
                 CROPTOP_LONGTEXT, true );
235
    add_integer( SOUT_CFG_PREFIX "cropleft", 0, NULL, CROPLEFT_TEXT,
236
                 CROPLEFT_LONGTEXT, true );
237
    add_integer( SOUT_CFG_PREFIX "cropbottom", 0, NULL, CROPBOTTOM_TEXT,
238
                 CROPBOTTOM_LONGTEXT, true );
239
    add_integer( SOUT_CFG_PREFIX "cropright", 0, NULL, CROPRIGHT_TEXT,
240
                 CROPRIGHT_LONGTEXT, true );
241

242
    add_integer( SOUT_CFG_PREFIX "paddtop", 0, NULL, PADDTOP_TEXT,
243
                 PADDTOP_LONGTEXT, true );
244
    add_integer( SOUT_CFG_PREFIX "paddleft", 0, NULL, PADDLEFT_TEXT,
245
                 PADDLEFT_LONGTEXT, true );
246
    add_integer( SOUT_CFG_PREFIX "paddbottom", 0, NULL, PADDBOTTOM_TEXT,
247
                 PADDBOTTOM_LONGTEXT, true );
248
    add_integer( SOUT_CFG_PREFIX "paddright", 0, NULL, PADDRIGHT_TEXT,
249
                 PADDRIGHT_LONGTEXT, true );
250 251

    add_integer( SOUT_CFG_PREFIX "canvas-width", 0, NULL, CANVAS_WIDTH_TEXT,
252
                 CANVAS_WIDTH_LONGTEXT, true );
253
    add_integer( SOUT_CFG_PREFIX "canvas-height", 0, NULL, CANVAS_HEIGHT_TEXT,
254
                 CANVAS_HEIGHT_LONGTEXT, true );
255
    add_string( SOUT_CFG_PREFIX "canvas-aspect", NULL, NULL, CANVAS_ASPECT_TEXT,
256
                CANVAS_ASPECT_LONGTEXT, false );
257

258
    set_section( N_("Audio"), NULL );
259
    add_string( SOUT_CFG_PREFIX "aenc", NULL, NULL, AENC_TEXT,
260
                AENC_LONGTEXT, false );
261
    add_string( SOUT_CFG_PREFIX "acodec", NULL, NULL, ACODEC_TEXT,
262
                ACODEC_LONGTEXT, false );
263
    add_integer( SOUT_CFG_PREFIX "ab", 0, NULL, AB_TEXT,
264
                 AB_LONGTEXT, false );
265
    add_integer( SOUT_CFG_PREFIX "channels", 0, NULL, ACHANS_TEXT,
266
                 ACHANS_LONGTEXT, false );
267
    add_integer( SOUT_CFG_PREFIX "samplerate", 0, NULL, ARATE_TEXT,
268
                 ARATE_LONGTEXT, true );
269
    add_bool( SOUT_CFG_PREFIX "audio-sync", 0, NULL, ASYNC_TEXT,
270
              ASYNC_LONGTEXT, false );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
271
    add_module_list( SOUT_CFG_PREFIX "afilter",  "audio filter2",
272
                     NULL, NULL,
273
                     AFILTER_TEXT, AFILTER_LONGTEXT, false );
274

275
    set_section( N_("Overlays/Subtitles"), NULL );
276
    add_string( SOUT_CFG_PREFIX "senc", NULL, NULL, SENC_TEXT,
277
                SENC_LONGTEXT, false );
278
    add_string( SOUT_CFG_PREFIX "scodec", NULL, NULL, SCODEC_TEXT,
279
                SCODEC_LONGTEXT, false );
280
    add_bool( SOUT_CFG_PREFIX "soverlay", 0, NULL, SCODEC_TEXT,
281
               SCODEC_LONGTEXT, false );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
282
    add_module_list( SOUT_CFG_PREFIX "sfilter", "video filter",
283
                     NULL, NULL,
284
                     SFILTER_TEXT, SFILTER_LONGTEXT, false );
285

286 287
    set_section( N_("On Screen Display"), NULL );
    add_bool( SOUT_CFG_PREFIX "osd", 0, NULL, OSD_TEXT,
288
              OSD_LONGTEXT, false );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
289

290
    set_section( N_("Miscellaneous"), NULL );
291
    add_integer( SOUT_CFG_PREFIX "threads", 0, NULL, THREADS_TEXT,
292
                 THREADS_LONGTEXT, true );
293
    add_bool( SOUT_CFG_PREFIX "high-priority", 0, NULL, HP_TEXT, HP_LONGTEXT,
294
              true );
295

296
vlc_module_end();
297

298 299
static const char *ppsz_sout_options[] = {
    "venc", "vcodec", "vb", "croptop", "cropbottom", "cropleft", "cropright",
Antoine Cellerier's avatar
Antoine Cellerier committed
300 301
    "paddtop", "paddbottom", "paddleft", "paddright",
    "canvas-width", "canvas-height", "canvas-aspect",
302 303
    "scale", "fps", "width", "height", "vfilter", "deinterlace",
    "deinterlace-module", "threads", "hurry-up", "aenc", "acodec", "ab",
304 305 306
    "afilter", "samplerate", "channels", "senc", "scodec", "soverlay",
    "sfilter", "osd", "audio-sync", "high-priority", "maxwidth", "maxheight",
    NULL
307 308
};

309 310 311
/*****************************************************************************
 * Exported prototypes
 *****************************************************************************/
312
static sout_stream_id_t *Add ( sout_stream_t *, es_format_t * );
313
static int               Del ( sout_stream_t *, sout_stream_id_t * );
314
static int               Send( sout_stream_t *, sout_stream_id_t *, block_t* );
315

316
static int  transcode_audio_new    ( sout_stream_t *, sout_stream_id_t * );
Rafaël Carré's avatar
Rafaël Carré committed
317
static void transcode_audio_close  ( sout_stream_id_t * );
318 319 320
static int  transcode_audio_process( sout_stream_t *, sout_stream_id_t *,
                                     block_t *, block_t ** );

321 322 323
static aout_buffer_t *audio_new_buffer( decoder_t *, int );
static void audio_del_buffer( decoder_t *, aout_buffer_t * );

324 325 326 327 328 329
static int  transcode_video_new    ( sout_stream_t *, sout_stream_id_t * );
static void transcode_video_close  ( sout_stream_t *, sout_stream_id_t * );
static int  transcode_video_encoder_open( sout_stream_t *, sout_stream_id_t *);
static int  transcode_video_process( sout_stream_t *, sout_stream_id_t *,
                                     block_t *, block_t ** );

330 331 332 333 334 335 336
static void video_del_buffer( vlc_object_t *, picture_t * );
static picture_t *video_new_buffer_decoder( decoder_t * );
static void video_del_buffer_decoder( decoder_t *, picture_t * );
static void video_link_picture_decoder( decoder_t *, picture_t * );
static void video_unlink_picture_decoder( decoder_t *, picture_t * );
static picture_t *video_new_buffer_filter( filter_t * );
static void video_del_buffer_filter( filter_t *, picture_t * );
Gildas Bazin's avatar
 
Gildas Bazin committed
337

338
static int  transcode_spu_new    ( sout_stream_t *, sout_stream_id_t * );
Rafaël Carré's avatar
Rafaël Carré committed
339
static void transcode_spu_close  ( sout_stream_id_t * );
340 341 342
static int  transcode_spu_process( sout_stream_t *, sout_stream_id_t *,
                                   block_t *, block_t ** );

343 344 345 346
static int  transcode_osd_new    ( sout_stream_t *, sout_stream_id_t * );
static void transcode_osd_close  ( sout_stream_t *, sout_stream_id_t * );
static int  transcode_osd_process( sout_stream_t *, sout_stream_id_t *,
                                   block_t *, block_t ** );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
347

348 349
static int  EncoderThread( struct sout_stream_sys_t * p_sys );

Gildas Bazin's avatar
 
Gildas Bazin committed
350 351 352 353 354 355 356 357 358 359 360
static int pi_channels_maps[6] =
{
    0,
    AOUT_CHAN_CENTER,   AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
    AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
    AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
     | AOUT_CHAN_REARRIGHT,
    AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
     | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
};

361
#define PICTURE_RING_SIZE 64
362
#define SUBPICTURE_RING_SIZE 20
363
#define TRANSCODE_FILTERS 10
364

365 366 367
#define ENC_FRAMERATE (25 * 1000 + .5)
#define ENC_FRAMERATE_BASE 1000

368 369
struct sout_stream_sys_t
{
370 371
    VLC_COMMON_MEMBERS

372 373 374
    sout_stream_t   *p_out;
    sout_stream_id_t *id_video;
    block_t         *p_buffers;
375 376 377 378
    vlc_mutex_t     lock_out;
    vlc_cond_t      cond;
    picture_t *     pp_pics[PICTURE_RING_SIZE];
    int             i_first_pic, i_last_pic;
379

380
    /* Audio */
381
    vlc_fourcc_t    i_acodec;   /* codec audio (0 if not transcode) */
382
    char            *psz_aenc;
383
    config_chain_t  *p_audio_cfg;
384 385
    uint32_t        i_sample_rate;
    uint32_t        i_channels;
386
    int             i_abitrate;
387
    char            *psz_afilters[TRANSCODE_FILTERS];
388
    config_chain_t  *p_afilters_cfg[TRANSCODE_FILTERS];
389
    int             i_afilters;
390

391 392
    /* Video */
    vlc_fourcc_t    i_vcodec;   /* codec video (0 if not transcode) */
393
    char            *psz_venc;
394
    config_chain_t  *p_video_cfg;
395
    int             i_vbitrate;
396
    double          f_scale;
397
    double          f_fps;
398 399
    unsigned int    i_width, i_maxwidth;
    unsigned int    i_height, i_maxheight;
400
    bool      b_deinterlace;
401
    char            *psz_deinterlace;
402
    config_chain_t  *p_deinterlace_cfg;
403
    int             i_threads;
404 405
    bool      b_high_priority;
    bool      b_hurry_up;
406
    char            *psz_vfilters[TRANSCODE_FILTERS];
407
    config_chain_t  *p_vfilters_cfg[TRANSCODE_FILTERS];
408
    int             i_vfilters;
409 410 411 412 413

    int             i_crop_top;
    int             i_crop_bottom;
    int             i_crop_right;
    int             i_crop_left;
Gildas Bazin's avatar
 
Gildas Bazin committed
414

415 416 417 418 419 420 421 422
    int             i_padd_top;
    int             i_padd_bottom;
    int             i_padd_right;
    int             i_padd_left;

    int             i_canvas_width;
    int             i_canvas_height;
    int             i_canvas_aspect;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
423

424 425 426 427 428 429 430 431 432 433 434
    /* Video, calculated */
    int             i_src_x_offset;
    int             i_src_y_offset;
    int             i_crop_width;
    int             i_crop_height;

    int             i_dst_x_offset;
    int             i_dst_y_offset;
    int             i_nopadd_width;
    int             i_nopadd_height;

435 436 437
    /* SPU */
    vlc_fourcc_t    i_scodec;   /* codec spu (0 if not transcode) */
    char            *psz_senc;
438
    bool      b_soverlay;
439
    config_chain_t  *p_spu_cfg;
440
    spu_t           *p_spu;
441

442 443 444
    /* OSD Menu */
    vlc_fourcc_t    i_osdcodec; /* codec osd menu (0 if not transcode) */
    char            *psz_osdenc;
445
    config_chain_t  *p_osd_cfg;
446
    bool      b_osd;   /* true when osd es is registered */
Jean-Paul Saman's avatar
Jean-Paul Saman committed
447

448
    /* Sync */
449
    bool      b_master_sync;
450
    mtime_t         i_master_drift;
451 452
};

453 454 455
struct decoder_owner_sys_t
{
    picture_t *pp_pics[PICTURE_RING_SIZE];
456
    sout_stream_sys_t *p_sys;
457 458 459 460
};
struct filter_owner_sys_t
{
    picture_t *pp_pics[PICTURE_RING_SIZE];
461
    sout_stream_sys_t *p_sys;
462 463
};

464 465 466 467 468 469 470
/*****************************************************************************
 * Open:
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
    sout_stream_t     *p_stream = (sout_stream_t*)p_this;
    sout_stream_sys_t *p_sys;
471
    vlc_value_t       val;
472

473
    p_sys = vlc_object_create( p_this, sizeof( sout_stream_sys_t ) );
474

Laurent Aimar's avatar
Laurent Aimar committed
475
    p_sys->p_out = sout_StreamNew( p_stream->p_sout, p_stream->psz_next );
476 477 478
    if( !p_sys->p_out )
    {
        msg_Err( p_stream, "cannot create chain" );
479
        vlc_object_release( p_sys );
480 481
        return VLC_EGENERIC;
    }
482

483
    p_sys->i_master_drift = 0;
484

485
    config_ChainParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
486
                   p_stream->p_cfg );
487

488 489 490 491 492
    /* Audio transcoding parameters */
    var_Get( p_stream, SOUT_CFG_PREFIX "aenc", &val );
    p_sys->psz_aenc = NULL;
    p_sys->p_audio_cfg = NULL;
    if( val.psz_string && *val.psz_string )
493
    {
494
        char *psz_next;
495 496
        psz_next = config_ChainCreate( &p_sys->psz_aenc, &p_sys->p_audio_cfg,
                                       val.psz_string );
497
        free( psz_next );
498
    }
499
    free( val.psz_string );
500 501 502 503 504 505 506

    var_Get( p_stream, SOUT_CFG_PREFIX "acodec", &val );
    p_sys->i_acodec = 0;
    if( val.psz_string && *val.psz_string )
    {
        char fcc[4] = "    ";
        memcpy( fcc, val.psz_string, __MIN( strlen( val.psz_string ), 4 ) );
507
        p_sys->i_acodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
508
    }
509
    free( val.psz_string );
510

511 512 513 514 515 516
    var_Get( p_stream, SOUT_CFG_PREFIX "ab", &val );
    p_sys->i_abitrate = val.i_int;
    if( p_sys->i_abitrate < 4000 ) p_sys->i_abitrate *= 1000;

    var_Get( p_stream, SOUT_CFG_PREFIX "samplerate", &val );
    p_sys->i_sample_rate = val.i_int;
517

518 519 520 521 522
    var_Get( p_stream, SOUT_CFG_PREFIX "channels", &val );
    p_sys->i_channels = val.i_int;

    if( p_sys->i_acodec )
    {
523 524
        if( p_sys->i_acodec == VLC_FOURCC('m','p','3',0) &&
            p_sys->i_channels > 2 )
525 526 527 528
        {
            msg_Warn( p_stream, "%d channels invalid for mp3, forcing to 2",
                      p_sys->i_channels );
            p_sys->i_channels = 2;
529
        }
530 531 532
        msg_Dbg( p_stream, "codec audio=%4.4s %dHz %d channels %dKb/s",
                 (char *)&p_sys->i_acodec, p_sys->i_sample_rate,
                 p_sys->i_channels, p_sys->i_abitrate / 1000 );
533 534
    }

535 536 537 538 539 540 541 542 543
    var_Get( p_stream, SOUT_CFG_PREFIX "afilter", &val );
    p_sys->i_afilters = 0;
    if( val.psz_string && *val.psz_string )
    {
        char *psz_parser = val.psz_string;

        while( (psz_parser != NULL) && (*psz_parser != '\0')
                && (p_sys->i_afilters < TRANSCODE_FILTERS) )
        {
544
            psz_parser = config_ChainCreate(
545 546 547 548 549 550 551
                                   &p_sys->psz_afilters[p_sys->i_afilters],
                                   &p_sys->p_afilters_cfg[p_sys->i_afilters],
                                   psz_parser );
            p_sys->i_afilters++;
            if( (psz_parser != NULL) && (*psz_parser != '\0') ) psz_parser++;
        }
    }
552
    free( val.psz_string );
553 554 555 556 557 558
    if( p_sys->i_afilters < TRANSCODE_FILTERS-1 )
    {
        p_sys->psz_afilters[p_sys->i_afilters] = NULL;
        p_sys->p_afilters_cfg[p_sys->i_afilters] = NULL;
    }

559
    /* Video transcoding parameters */
560 561 562 563 564 565
    var_Get( p_stream, SOUT_CFG_PREFIX "venc", &val );
    p_sys->psz_venc = NULL;
    p_sys->p_video_cfg = NULL;
    if( val.psz_string && *val.psz_string )
    {
        char *psz_next;
566
        psz_next = config_ChainCreate( &p_sys->psz_venc, &p_sys->p_video_cfg,
Laurent Aimar's avatar
Laurent Aimar committed
567
                                   val.psz_string );
568
        free( psz_next );
569
    }
570
    free( val.psz_string );
571

572 573 574
    var_Get( p_stream, SOUT_CFG_PREFIX "vcodec", &val );
    p_sys->i_vcodec = 0;
    if( val.psz_string && *val.psz_string )
575 576
    {
        char fcc[4] = "    ";
577 578 579
        memcpy( fcc, val.psz_string, __MIN( strlen( val.psz_string ), 4 ) );
        p_sys->i_vcodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
    }
580
    free( val.psz_string );
581

582 583 584
    var_Get( p_stream, SOUT_CFG_PREFIX "vb", &val );
    p_sys->i_vbitrate = val.i_int;
    if( p_sys->i_vbitrate < 16000 ) p_sys->i_vbitrate *= 1000;
585

586 587
    var_Get( p_stream, SOUT_CFG_PREFIX "scale", &val );
    p_sys->f_scale = val.f_float;
588

589 590 591
    var_Get( p_stream, SOUT_CFG_PREFIX "fps", &val );
    p_sys->f_fps = val.f_float;

592 593 594
    var_Get( p_stream, SOUT_CFG_PREFIX "hurry-up", &val );
    p_sys->b_hurry_up = val.b_bool;

595 596
    var_Get( p_stream, SOUT_CFG_PREFIX "width", &val );
    p_sys->i_width = val.i_int;
597

598 599
    var_Get( p_stream, SOUT_CFG_PREFIX "height", &val );
    p_sys->i_height = val.i_int;
600

601 602 603 604 605 606
    var_Get( p_stream, SOUT_CFG_PREFIX "maxwidth", &val );
    p_sys->i_maxwidth = val.i_int;

    var_Get( p_stream, SOUT_CFG_PREFIX "maxheight", &val );
    p_sys->i_maxheight = val.i_int;

607 608 609 610 611 612
    var_Get( p_stream, SOUT_CFG_PREFIX "vfilter", &val );
    p_sys->i_vfilters = 0;
    if( val.psz_string && *val.psz_string )
    {
        char *psz_parser = val.psz_string;

613 614
        while( (psz_parser != NULL) && (*psz_parser != '\0')
                && (p_sys->i_vfilters < TRANSCODE_FILTERS) )
615
        {
616
            psz_parser = config_ChainCreate(
617 618 619 620 621 622 623
                                   &p_sys->psz_vfilters[p_sys->i_vfilters],
                                   &p_sys->p_vfilters_cfg[p_sys->i_vfilters],
                                   psz_parser );
            p_sys->i_vfilters++;
            if( psz_parser != NULL && *psz_parser != '\0' ) psz_parser++;
        }
    }
624
    free( val.psz_string );
625 626 627 628 629
    if( p_sys->i_vfilters < TRANSCODE_FILTERS-1 )
    {
        p_sys->psz_vfilters[p_sys->i_vfilters] = NULL;
        p_sys->p_vfilters_cfg[p_sys->i_vfilters] = NULL;
    }
630

631 632 633
    var_Get( p_stream, SOUT_CFG_PREFIX "deinterlace", &val );
    p_sys->b_deinterlace = val.b_bool;

634 635 636 637 638 639
    var_Get( p_stream, SOUT_CFG_PREFIX "deinterlace-module", &val );
    p_sys->psz_deinterlace = NULL;
    p_sys->p_deinterlace_cfg = NULL;
    if( val.psz_string && *val.psz_string )
    {
        char *psz_next;
640
        psz_next = config_ChainCreate( &p_sys->psz_deinterlace,
641 642
                                   &p_sys->p_deinterlace_cfg,
                                   val.psz_string );
643
        free( psz_next );
644
    }
645
    free( val.psz_string );
646

647 648 649 650 651 652 653 654 655
    var_Get( p_stream, SOUT_CFG_PREFIX "croptop", &val );
    p_sys->i_crop_top = val.i_int;
    var_Get( p_stream, SOUT_CFG_PREFIX "cropbottom", &val );
    p_sys->i_crop_bottom = val.i_int;
    var_Get( p_stream, SOUT_CFG_PREFIX "cropleft", &val );
    p_sys->i_crop_left = val.i_int;
    var_Get( p_stream, SOUT_CFG_PREFIX "cropright", &val );
    p_sys->i_crop_right = val.i_int;

656 657 658 659 660 661 662 663
    var_Get( p_stream, SOUT_CFG_PREFIX "paddtop", &val );
    p_sys->i_padd_top = val.i_int;
    var_Get( p_stream, SOUT_CFG_PREFIX "paddbottom", &val );
    p_sys->i_padd_bottom = val.i_int;
    var_Get( p_stream, SOUT_CFG_PREFIX "paddleft", &val );
    p_sys->i_padd_left = val.i_int;
    var_Get( p_stream, SOUT_CFG_PREFIX "paddright", &val );
    p_sys->i_padd_right = val.i_int;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
664

665 666 667 668
    var_Get( p_stream, SOUT_CFG_PREFIX "canvas-width", &val );
    p_sys->i_canvas_width = val.i_int;
    var_Get( p_stream, SOUT_CFG_PREFIX "canvas-height", &val );
    p_sys->i_canvas_height = val.i_int;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
669

670
    var_Get( p_stream, SOUT_CFG_PREFIX "canvas-aspect", &val );
671 672
    p_sys->i_canvas_aspect = 0;
    if( val.psz_string && *val.psz_string )
673 674 675 676 677
    {
        char *psz_parser = strchr( val.psz_string, ':' );
        if( psz_parser )
        {
            *psz_parser++ = '\0';
678 679
            p_sys->i_canvas_aspect = atoi( val.psz_string ) *
                VOUT_ASPECT_FACTOR / atoi( psz_parser );
680
        }
681
        else msg_Warn( p_stream, "bad aspect ratio %s", val.psz_string );
682 683

    }
684
    free( val.psz_string );
685

686 687
    var_Get( p_stream, SOUT_CFG_PREFIX "threads", &val );
    p_sys->i_threads = val.i_int;
688 689
    var_Get( p_stream, SOUT_CFG_PREFIX "high-priority", &val );
    p_sys->b_high_priority = val.b_bool;
690 691

    if( p_sys->i_vcodec )
692
    {
693 694 695
        msg_Dbg( p_stream, "codec video=%4.4s %dx%d scaling: %f %dkb/s",
                 (char *)&p_sys->i_vcodec, p_sys->i_width, p_sys->i_height,
                 p_sys->f_scale, p_sys->i_vbitrate / 1000 );
696
    }
697

698
    /* Subpictures transcoding parameters */
699
    p_sys->p_spu = NULL;
700 701
    p_sys->psz_senc = NULL;
    p_sys->p_spu_cfg = NULL;
702 703 704
    p_sys->i_scodec = 0;

    var_Get( p_stream, SOUT_CFG_PREFIX "senc", &val );
705 706 707
    if( val.psz_string && *val.psz_string )
    {
        char *psz_next;
708
        psz_next = config_ChainCreate( &p_sys->psz_senc, &p_sys->p_spu_cfg,
709
                                   val.psz_string );
710
        free( psz_next );
711
    }
712
    free( val.psz_string );
713 714 715 716 717 718 719 720

    var_Get( p_stream, SOUT_CFG_PREFIX "scodec", &val );
    if( val.psz_string && *val.psz_string )
    {
        char fcc[4] = "    ";
        memcpy( fcc, val.psz_string, __MIN( strlen( val.psz_string ), 4 ) );
        p_sys->i_scodec = VLC_FOURCC( fcc[0], fcc[1], fcc[2], fcc[3] );
    }
721
    free( val.psz_string );
722 723 724

    if( p_sys->i_scodec )
    {
725
        msg_Dbg( p_stream, "codec spu=%4.4s", (char *)&p_sys->i_scodec );
726 727 728 729
    }

    var_Get( p_stream, SOUT_CFG_PREFIX "soverlay", &val );
    p_sys->b_soverlay = val.b_bool;
730 731 732 733 734 735 736 737 738

    var_Get( p_stream, SOUT_CFG_PREFIX "sfilter", &val );
    if( val.psz_string && *val.psz_string )
    {
        p_sys->p_spu = spu_Create( p_stream );
        var_Create( p_sys->p_spu, "sub-filter", VLC_VAR_STRING );
        var_Set( p_sys->p_spu, "sub-filter", val );
        spu_Init( p_sys->p_spu );
    }
739
    free( val.psz_string );
740

741 742 743 744
    /* OSD menu transcoding parameters */
    p_sys->psz_osdenc = NULL;
    p_sys->p_osd_cfg  = NULL;
    p_sys->i_osdcodec = 0;
745
    p_sys->b_osd   = false;
746 747

    var_Get( p_stream, SOUT_CFG_PREFIX "osd", &val );
748
    if( val.b_bool )
749
    {
750
        vlc_value_t osd_val;
751
        char *psz_next;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
752

753
        psz_next = config_ChainCreate( &p_sys->psz_osdenc,
754
                                   &p_sys->p_osd_cfg, strdup( "dvbsub") );
755
        free( psz_next );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
756 757

        p_sys->i_osdcodec = VLC_FOURCC('Y','U','V','P' );
758 759 760 761 762

        msg_Dbg( p_stream, "codec osd=%4.4s", (char *)&p_sys->i_osdcodec );

        if( !p_sys->p_spu )
        {
763
            osd_val.psz_string = strdup("osdmenu");
764 765
            p_sys->p_spu = spu_Create( p_stream );
            var_Create( p_sys->p_spu, "sub-filter", VLC_VAR_STRING );
766
            var_Set( p_sys->p_spu, "sub-filter", osd_val );
767
            spu_Init( p_sys->p_spu );
768
            free( osd_val.psz_string );
769 770 771 772 773
        }
        else
        {
            osd_val.psz_string = strdup("osdmenu");
            var_Set( p_sys->p_spu, "sub-filter", osd_val );
774
            free( osd_val.psz_string );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
775
        }
776 777 778
    }

    /* Audio settings */
779
    var_Get( p_stream, SOUT_CFG_PREFIX "audio-sync", &val );
780
    p_sys->b_master_sync = val.b_bool;
781
    if( p_sys->f_fps > 0 ) p_sys->b_master_sync = true;
782

783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
    p_stream->pf_add    = Add;
    p_stream->pf_del    = Del;
    p_stream->pf_send   = Send;
    p_stream->p_sys     = p_sys;

    return VLC_SUCCESS;
}

/*****************************************************************************
 * Close:
 *****************************************************************************/
static void Close( vlc_object_t * p_this )
{
    sout_stream_t       *p_stream = (sout_stream_t*)p_this;
    sout_stream_sys_t   *p_sys = p_stream->p_sys;

Laurent Aimar's avatar
Laurent Aimar committed
799
    sout_StreamDelete( p_sys->p_out );
800

801 802 803
    while( p_sys->i_afilters )
    {
        p_sys->i_afilters--;
804 805
        free( p_sys->psz_afilters[p_sys->i_afilters] );
        free( p_sys->p_afilters_cfg[p_sys->i_afilters] );
806 807
    }

808 809
    while( p_sys->p_audio_cfg != NULL )
    {
810
        config_chain_t *p_next = p_sys->p_audio_cfg->p_next;
811

812 813
        free( p_sys->p_audio_cfg->psz_name );
        free( p_sys->p_audio_cfg->psz_value );
814 815 816 817
        free( p_sys->p_audio_cfg );

        p_sys->p_audio_cfg = p_next;
    }
818
    free( p_sys->psz_aenc );
819

820 821 822
    while( p_sys->i_vfilters )
    {
        p_sys->i_vfilters--;
823 824
        free( p_sys->psz_vfilters[p_sys->i_vfilters] );
        free( p_sys->p_vfilters_cfg[p_sys->i_vfilters] );
825 826
    }

827 828
    while( p_sys->p_video_cfg != NULL )
    {
829
        config_chain_t *p_next = p_sys->p_video_cfg->p_next;
830

831 832
        free( p_sys->p_video_cfg->psz_name );
        free( p_sys->p_video_cfg->psz_value );
833 834 835 836
        free( p_sys->p_video_cfg );

        p_sys->p_video_cfg = p_next;
    }
837
    free( p_sys->psz_venc );
838

839 840
    while( p_sys->p_deinterlace_cfg != NULL )
    {
841
        config_chain_t *p_next = p_sys->p_deinterlace_cfg->p_next;
842

843 844
        free( p_sys->p_deinterlace_cfg->psz_name );
        free( p_sys->p_deinterlace_cfg->psz_value );
845 846 847 848
        free( p_sys->p_deinterlace_cfg );

        p_sys->p_deinterlace_cfg = p_next;
    }
849
    free( p_sys->psz_deinterlace );
850

851 852
    while( p_sys->p_spu_cfg != NULL )
    {
853
        config_chain_t *p_next = p_sys->p_spu_cfg->p_next;
854

855 856
        free( p_sys->p_spu_cfg->psz_name );
        free( p_sys->p_spu_cfg->psz_value );
857 858 859 860
        free( p_sys->p_spu_cfg );

        p_sys->p_spu_cfg = p_next;
    }
861
    free( p_sys->psz_senc );
862

863
    if( p_sys->p_spu ) spu_Destroy( p_sys->p_spu );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
864

865 866
    while( p_sys->p_osd_cfg != NULL )
    {
867
        config_chain_t *p_next = p_sys->p_osd_cfg->p_next;
868

869 870
        free( p_sys->p_osd_cfg->psz_name );
        free( p_sys->p_osd_cfg->psz_value );
871 872 873 874
        free( p_sys->p_osd_cfg );

        p_sys->p_osd_cfg = p_next;
    }
875
    free( p_sys->psz_osdenc );
876

877
    vlc_object_release( p_sys );
878 879 880 881 882
}

struct sout_stream_id_t
{
    vlc_fourcc_t  b_transcode;
883

884 885 886
    /* id of the out stream */
    void *id;

887 888 889
    /* Decoder */
    decoder_t       *p_decoder;

890
    /* Filters */
891
    filter_t        *pp_filter[TRANSCODE_FILTERS];
892
    int             i_filter;
893 894 895
    /* User specified filters */
    filter_t        *pp_ufilter[TRANSCODE_FILTERS];
    int             i_ufilter;
896

Gildas Bazin's avatar
 
Gildas Bazin committed
897
    /* Encoder */
Gildas Bazin's avatar
 
Gildas Bazin committed
898
    encoder_t       *p_encoder;
Gildas Bazin's avatar
 
Gildas Bazin committed
899

900 901
    /* Sync */
    date_t          interpolated_pts;
902 903
};

904
static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
905
{
906 907
    sout_stream_sys_t *p_sys = p_stream->p_sys;
    sout_stream_id_t *id;
908 909

    id = malloc( sizeof( sout_stream_id_t ) );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
910 911 912 913 914
    if( !id )
    {
        msg_Err( p_stream, "out of memory" );
        goto error;
    }
915 916
    memset( id, 0, sizeof(sout_stream_id_t) );

Gildas Bazin's avatar
 
Gildas Bazin committed
917
    id->id = NULL;
918
    id->p_decoder = NULL;
Gildas Bazin's avatar
 
Gildas Bazin committed
919 920
    id->p_encoder = NULL;

921 922 923 924 925 926 927 928 929 930
    /* Create decoder object */
    id->p_decoder = vlc_object_create( p_stream, VLC_OBJECT_DECODER );
    if( !id->p_decoder )
    {
        msg_Err( p_stream, "out of memory" );
        goto error;
    }
    vlc_object_attach( id->p_decoder, p_stream );
    id->p_decoder->p_module = NULL;
    id->p_decoder->fmt_in = *p_fmt;
931
    id->p_decoder->b_pace_control = true;
932 933 934 935 936 937 938 939 940 941

    /* Create encoder object */
    id->p_encoder = vlc_object_create( p_stream, VLC_OBJECT_ENCODER );
    if( !id->p_encoder )
    {
        msg_Err( p_stream, "out of memory" );
        goto error;
    }
    vlc_object_attach( id->p_encoder, p_stream );
    id->p_encoder->p_module = NULL;
942 943

    /* Create destination format */
944 945 946 947 948
    es_format_Init( &id->p_encoder->fmt_out, p_fmt->i_cat, 0 );
    id->p_encoder->fmt_out.i_id    = p_fmt->i_id;
    id->p_encoder->fmt_out.i_group = p_fmt->i_group;
    if( p_fmt->psz_language )
        id->p_encoder->fmt_out.psz_language = strdup( p_fmt->psz_language );
949

950
    if( p_fmt->i_cat == AUDIO_ES && (p_sys->i_acodec || p_sys->psz_aenc) )
951 952 953
    {
        msg_Dbg( p_stream,
                 "creating audio transcoding from fcc=`%4.4s' to fcc=`%4.4s'",
954 955 956
                 (char*)&p_fmt->i_codec, (char*)&p_sys->i_acodec );

        /* Complete destination format */
957 958
        id->p_encoder->fmt_out.i_codec = p_sys->i_acodec;
        id->p_encoder->fmt_out.audio.i_rate = p_sys->i_sample_rate > 0 ?
959
            p_sys->i_sample_rate : p_fmt->audio.i_rate;
960 961 962
        id->p_encoder->fmt_out.i_bitrate = p_sys->i_abitrate;
        id->p_encoder->fmt_out.audio.i_bitspersample =
            p_fmt->audio.i_bitspersample;
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
        id->p_encoder->fmt_out.audio.i_channels = p_sys->i_channels > 0 ?
            p_sys->i_channels : p_fmt->audio.i_channels;
        /* Sanity check for audio channels */
        id->p_encoder->fmt_out.audio.i_channels =
            __MIN( id->p_encoder->fmt_out.audio.i_channels,
                   id->p_decoder->fmt_in.audio.i_channels );
        id->p_encoder->fmt_out.audio.i_original_channels =
            id->p_decoder->fmt_in.audio.i_physical_channels;
        if( id->p_decoder->fmt_in.audio.i_channels ==
            id->p_encoder->fmt_out.audio.i_channels )
        {
            id->p_encoder->fmt_out.audio.i_physical_channels =
                id->p_decoder->fmt_in.audio.i_physical_channels;
        }
        else
        {
            id->p_encoder->fmt_out.audio.i_physical_channels =
                pi_channels_maps[id->p_encoder->fmt_out.audio.i_channels];
        }
982 983 984

        /* Build decoder -> filter -> encoder chain */
        if( transcode_audio_new( p_stream, id ) )
985 986
        {
            msg_Err( p_stream, "cannot create audio chain" );
987
            goto error;
988 989
        }

990 991
        /* Open output stream */
        id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->p_encoder->fmt_out );
992
        id->b_transcode = true;
993

994 995
        if( !id->id )
        {
Rafaël Carré's avatar
Rafaël Carré committed
996
            transcode_audio_close( id );
997 998
            goto error;
        }
999 1000

        date_Init( &id->interpolated_pts, p_fmt->audio.i_rate, 1 );
1001
    }
1002 1003
    else if( p_fmt->i_cat == VIDEO_ES &&
             (p_sys->i_vcodec != 0 || p_sys->psz_venc) )
1004 1005 1006
    {
        msg_Dbg( p_stream,
                 "creating video transcoding from fcc=`%4.4s' to fcc=`%4.4s'",
1007
                 (char*)&p_fmt->i_codec, (char*)&p_sys->i_vcodec );
1008

1009
        /* Complete destination format */
1010
        id->p_encoder->fmt_out.i_codec = p_sys->i_vcodec;
1011 1012
        id->p_encoder->fmt_out.video.i_width  = p_sys->i_width & ~1;
        id->p_encoder->fmt_out.video.i_height = p_sys->i_height & ~1;
1013
        id->p_encoder->fmt_out.i_bitrate = p_sys->i_vbitrate;
1014

1015 1016
        /* Build decoder -> filter -> encoder chain */
        if( transcode_video_new( p_stream, id ) )
1017 1018
        {
            msg_Err( p_stream, "cannot create video chain" );
1019
            goto error;
1020
        }
1021 1022 1023

        /* Stream will be added later on because we don't know
         * all the characteristics of the decoded stream yet */
1024
        id->b_transcode = true;
1025

1026
        if( p_sys->f_fps > 0 )
1027
        {
1028
            id->p_encoder->fmt_out.video.i_frame_rate =
1029 1030 1031
                (p_sys->f_fps * 1000) + 0.5;
            id->p_encoder->fmt_out.video.i_frame_rate_base =
                ENC_FRAMERATE_BASE;
1032
        }
1033
    }
1034 1035
    else if( ( p_fmt->i_cat == SPU_ES ) &&
             ( p_sys->i_scodec || p_sys->psz_senc ) )
1036 1037 1038 1039 1040
    {
        msg_Dbg( p_stream, "creating subtitles transcoding from fcc=`%4.4s' "
                 "to fcc=`%4.4s'", (char*)&p_fmt->i_codec,
                 (char*)&p_sys->i_scodec );

1041
        /* Complete destination format */
1042
        id->p_encoder->fmt_out.i_codec = p_sys->i_scodec;
1043 1044 1045 1046 1047

        /* build decoder -> filter -> encoder */
        if( transcode_spu_new( p_stream, id ) )
        {
            msg_Err( p_stream, "cannot create subtitles chain" );
1048
            goto error;
1049 1050 1051
        }

        /* open output stream */
1052
        id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->p_encoder->fmt_out );
1053
        id->b_transcode = true;
1054

1055 1056
        if( !id->id )
        {
Rafaël Carré's avatar
Rafaël Carré committed
1057
            transcode_spu_close( id );
1058 1059
            goto error;
        }
1060 1061 1062 1063 1064 1065
    }
    else if( p_fmt->i_cat == SPU_ES && p_sys->b_soverlay )
    {
        msg_Dbg( p_stream, "subtitles (fcc=`%4.4s') overlaying",
                 (char*)&p_fmt->i_codec );

1066
        id->b_transcode = true;
1067

1068
        /* Build decoder -> filter -> overlaying chain */
1069 1070 1071
        if( transcode_spu_new( p_stream, id ) )
        {
            msg_Err( p_stream, "cannot create subtitles chain" );
1072
            goto error;
1073 1074
        }
    }
1075 1076 1077 1078 1079 1080
    else if( !p_sys->b_osd && (p_sys->i_osdcodec != 0 || p_sys->psz_osdenc) )
    {
        msg_Dbg( p_stream, "creating osd transcoding from fcc=`%4.4s' "
                 "to fcc=`%4.4s'", (char*)&p_fmt->i_codec,
                 (char*)&p_sys->i_scodec );

1081
        id->b_transcode = true;
1082 1083 1084 1085 1086 1087 1088

        /* Create a fake OSD menu elementary stream */
        if( transcode_osd_new( p_stream, id ) )
        {
            msg_Err( p_stream, "cannot create osd chain" );
            goto error;
        }
1089
        p_sys->b_osd = true;
1090
    }
1091 1092
    else
    {
1093 1094
        msg_Dbg( p_stream, "not transcoding a stream (fcc=`%4.4s')",
                 (char*)&p_fmt->i_codec );
1095
        id->id = p_sys->p_out->pf_add( p_sys->p_out, p_fmt );
1096
        id->b_transcode = false;
1097

1098
        if( !id->id ) goto error;
1099 1100 1101
    }

    return id;
1102 1103 1104 1105 1106

 error:
    if( id->p_decoder )
    {
        vlc_object_detach( id->p_decoder );
1107
        vlc_object_release( id->p_decoder );
1108
        id->p_decoder = NULL;
1109 1110 1111 1112 1113
    }

    if( id->p_encoder )
    {
        vlc_object_detach( id->p_encoder );
1114
        es_format_Clean( &id->p_encoder->fmt_out );
1115
        vlc_object_release( id->p_encoder );
1116
        id->p_encoder = NULL;
1117 1118 1119 1120
    }

    free( id );
    return NULL;
1121 1122
}

1123
static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1124
{
1125
    sout_stream_sys_t *p_sys = p_stream->p_sys;
1126 1127 1128

    if( id->b_transcode )
    {
1129
        switch( id->p_decoder->fmt_in.i_cat )
1130
        {
1131
        case AUDIO_ES:
Rafaël Carré's avatar
Rafaël Carré committed
1132
            transcode_audio_close( id );
1133 1134 1135 1136 1137
            break;
        case VIDEO_ES:
            transcode_video_close( p_stream, id );
            break;
        case SPU_ES:
1138 1139 1140
            if( p_sys->b_osd )
                transcode_osd_close( p_stream, id );
            else
Rafaël Carré's avatar
Rafaël Carré committed
1141
                transcode_spu_close( id );
1142
            break;
1143
        }
1144 1145
    }

Gildas Bazin's avatar
 
Gildas Bazin committed
1146
    if( id->id ) p_sys->p_out->pf_del( p_sys->p_out, id->id );
1147 1148 1149 1150

    if( id->p_decoder )
    {
        vlc_object_detach( id->p_decoder );
1151
        vlc_object_release( id->p_decoder );
1152
        id->p_decoder = NULL;
1153 1154 1155 1156 1157
    }

    if( id->p_encoder )
    {
        vlc_object_detach( id->p_encoder );
1158
        es_format_Clean( &id->p_encoder->fmt_out );
1159
        vlc_object_release( id->p_encoder );
1160
        id->p_encoder = NULL;
1161
    }
1162 1163 1164 1165 1166
    free( id );

    return VLC_SUCCESS;
}

Gildas Bazin's avatar
 
Gildas Bazin committed
1167
static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1168
                 block_t *p_buffer )
1169
{
1170
    sout_stream_sys_t *p_sys = p_stream->p_sys;
1171
    block_t *p_out = NULL;
1172

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
    if( !id->b_transcode && id->id )
    {
        return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_buffer );
    }
    else if( !id->b_transcode )
    {
        block_Release( p_buffer );
        return VLC_EGENERIC;
    }

    switch( id->p_decoder->fmt_in.i_cat )
1184
    {
1185 1186 1187
    case AUDIO_ES:
        transcode_audio_process( p_stream, id, p_buffer, &p_out );
        break;
1188

1189 1190 1191
    case VIDEO_ES:
        if( transcode_video_process( p_stream, id, p_buffer, &p_out )
            != VLC_SUCCESS )
1192 1193 1194
        {
            return VLC_EGENERIC;
        }
1195
        break;
1196

1197
    case SPU_ES:
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        /* Transcode OSD menu pictures. */
        if( p_sys->b_osd )
        {
            if( transcode_osd_process( p_stream, id, p_buffer, &p_out ) !=
                VLC_SUCCESS )
            {
                return VLC_EGENERIC;
            }
        }
        else if ( transcode_spu_process( p_stream, id, p_buffer, &p_out ) !=
1208
            VLC_SUCCESS )
1209
        {
1210
            return VLC_EGENERIC;
1211
        }
1212
        break;
1213

1214
    default:
1215
        p_out = NULL;
1216
        block_Release( p_buffer );
1217
        break;
1218
    }
1219 1220 1221

    if( p_out ) return p_sys->p_out->pf_send( p_sys->p_out, id->id, p_out );
    return VLC_SUCCESS;
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 1259 1260
/****************************************************************************
 * decoder helper
 ****************************************************************************/
static inline void video_timer_start( encoder_t * p_encoder )
{
    stats_TimerStart( p_encoder, "encoding video frame",
                      STATS_TIMER_VIDEO_FRAME_ENCODING );
}

static inline void video_timer_stop( encoder_t * p_encoder )
{
    stats_TimerStop( p_encoder, STATS_TIMER_VIDEO_FRAME_ENCODING );
}

static inline void video_timer_close( encoder_t * p_encoder )
{
    stats_TimerDump(  p_encoder, STATS_TIMER_VIDEO_FRAME_ENCODING );
    stats_TimerClean( p_encoder, STATS_TIMER_VIDEO_FRAME_ENCODING );
}

static inline void audio_timer_start( encoder_t * p_encoder )
{
    stats_TimerStart( p_encoder, "encoding audio frame",
                      STATS_TIMER_AUDIO_FRAME_ENCODING );
}

static inline void audio_timer_stop( encoder_t * p_encoder )
{
    stats_TimerStop( p_encoder, STATS_TIMER_AUDIO_FRAME_ENCODING );
}

static inline void audio_timer_close( encoder_t * p_encoder )
{
    stats_TimerDump(  p_encoder, STATS_TIMER_AUDIO_FRAME_ENCODING );
    stats_TimerClean( p_encoder, STATS_TIMER_AUDIO_FRAME_ENCODING );
}

1261
/****************************************************************************
1262
 * decoder reencoder part
1263
 ****************************************************************************/
1264

1265
static int audio_BitsPerSample( vlc_fourcc_t i_format )
1266
{
1267
    switch( i_format )
1268
    {
1269 1270
    case VLC_FOURCC('u','8',' ',' '):
    case VLC_FOURCC('s','8',' ',' '):
1271
        return 8;
1272 1273 1274 1275 1276

    case VLC_FOURCC('u','1','6','l'):
    case VLC_FOURCC('s','1','6','l'):
    case VLC_FOURCC('u','1','6','b'):
    case VLC_FOURCC('s','1','6','b'):
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
        return 16;

    case VLC_FOURCC('u','2','4','l'):
    case VLC_FOURCC('s','2','4','l'):
    case VLC_FOURCC('u','2','4','b'):
    case VLC_FOURCC('s','2','4','b'):
        return 24;

    case VLC_FOURCC('u','3','2','l'):
    case VLC_FOURCC('s','3','2','l'):
    case VLC_FOURCC('u','3','2','b'):
    case VLC_FOURCC('s','3','2','b'):
1289 1290
    case VLC_FOURCC('f','l','3','2'):
    case VLC_FOURCC('f','i','3','2'):
1291 1292 1293 1294
        return 32;

    case VLC_FOURCC('f','l','6','4'):
        return 64;
1295 1296 1297 1298 1299
    }

    return 0;
}

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1300 1301 1302 1303 1304
static block_t *transcode_audio_alloc (filter_t *filter, int size)
{
    return block_New (filter, size);
}

1305 1306 1307
static filter_t *transcode_audio_filter_new( sout_stream_t *p_stream,
                                             sout_stream_id_t *id,
                                             es_format_t *p_fmt_in,
1308 1309
                                             es_format_t *p_fmt_out,
                                             char *psz_name )
1310
{
1311
    sout_stream_sys_t *p_sys = p_stream->p_sys;
1312 1313 1314
    filter_t *p_filter = vlc_object_create( p_stream, VLC_OBJECT_FILTER );

    vlc_object_attach( p_filter, p_stream );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1315
    p_filter->pf_audio_buffer_new = transcode_audio_alloc;
1316 1317 1318

    p_filter->fmt_in = *p_fmt_in;
    p_filter->fmt_out = *p_fmt_out;
1319 1320
    if( psz_name )
        p_filter->p_cfg = p_sys->p_afilters_cfg[id->i_ufilter];
1321

1322
    p_filter->p_module = module_Need( p_filter, "audio filter2", psz_name,
1323
                                      true );
1324 1325
    if( p_filter->p_module )
    {
1326
        p_filter->fmt_out.audio.i_bitspersample =
1327 1328 1329 1330 1331 1332
            audio_BitsPerSample( p_filter->fmt_out.i_codec );
        *p_fmt_in = p_filter->fmt_out;
    }
    else
    {
        vlc_object_detach( p_filter );
1333
        vlc_object_release( p_filter );
1334 1335 1336 1337 1338 1339
        p_filter = 0;
    }

    return p_filter;
}

1340 1341
static int transcode_audio_new( sout_stream_t *p_stream,
                                sout_stream_id_t *id )
1342
{
1343
    sout_stream_sys_t *p_sys = p_stream->p_sys;
1344
    es_format_t fmt_last;
1345
    int i;
1346

1347 1348 1349
    /*
     * Open decoder
     */
1350

1351
    /* Initialization of decoder structures */
1352 1353 1354
    id->p_decoder->fmt_out = id->p_decoder->fmt_in;
    id->p_decoder->fmt_out.i_extra = 0;
    id->p_decoder->fmt_out.p_extra = 0;
1355
    id->p_decoder->pf_decode_audio = NULL;
1356 1357
    id->p_decoder->pf_aout_buffer_new = audio_new_buffer;
    id->p_decoder->pf_aout_buffer_del = audio_del_buffer;
1358
    /* id->p_decoder->p_cfg = p_sys->p_audio_cfg; */
1359

1360 1361 1362 1363 1364 1365
    id->p_decoder->p_module =
        module_Need( id->p_decoder, "decoder", "$codec", 0 );
    if( !id->p_decoder->p_module )
    {
        msg_Err( p_stream, "cannot find decoder" );
        return VLC_EGENERIC;
1366
    }
1367
    id->p_decoder->fmt_out.audio.i_bitspersample =
1368
        audio_BitsPerSample( id->p_decoder->fmt_out.i_codec );
1369
    fmt_last = id->p_decoder->fmt_out;
1370 1371 1372 1373 1374
    /* Fix AAC SBR changing number of channels and sampling rate */
    if( !(id->p_decoder->fmt_in.i_codec == VLC_FOURCC('m','p','4','a') &&
        fmt_last.audio.i_rate != id->p_encoder->fmt_in.audio.i_rate &&
        fmt_last.audio.i_channels != id->p_encoder->fmt_in.audio.i_channels) )
        fmt_last.audio.i_rate = id->p_decoder->fmt_in.audio.i_rate;
1375

1376 1377 1378 1379 1380 1381 1382 1383
    /*
     * Open encoder
     */

    /* Initialization of encoder format structures */
    es_format_Init( &id->p_encoder->fmt_in, id->p_decoder->fmt_in.i_cat,
                    id->p_decoder->fmt_out.i_codec );
    id->p_encoder->fmt_in.audio.i_format = id->p_decoder->fmt_out.i_codec;
Gildas Bazin's avatar
 
Gildas Bazin committed
1384

1385 1386 1387 1388 1389
    if( ( id->p_encoder->fmt_out.i_codec == VLC_FOURCC('s','a','m','r') ) ||
        ( id->p_encoder->fmt_out.i_codec == VLC_FOURCC('s','a','w','b') ) )
         id->p_encoder->fmt_in.audio.i_rate = id->p_encoder->fmt_out.audio.i_rate;
    else
        id->p_encoder->fmt_in.audio.i_rate = fmt_last.audio.i_rate;
Gildas Bazin's avatar
 
Gildas Bazin committed
1390
    id->p_encoder->fmt_in.audio.i_physical_channels =
1391
        id->p_encoder->fmt_out.audio.i_physical_channels;
1392
    id->p_encoder->fmt_in.audio.i_original_channels =
1393
        id->p_encoder->fmt_out.audio.i_original_channels;
1394
    id->p_encoder->fmt_in.audio.i_channels =
1395
        id->p_encoder->fmt_out.audio.i_channels;
1396 1397
    id->p_encoder->fmt_in.audio.i_bitspersample =
        audio_BitsPerSample( id->p_encoder->fmt_in.i_codec );
Gildas Bazin's avatar
 
Gildas Bazin committed
1398

1399
    id->p_encoder->p_cfg = p_stream->p_sys->p_audio_cfg;
Gildas Bazin's avatar
 
Gildas Bazin committed
1400
    id->p_encoder->p_module =
1401
        module_Need( id->p_encoder, "encoder", p_sys->psz_aenc, true );
Gildas Bazin's avatar
 
Gildas Bazin committed
1402
    if( !id->p_encoder->p_module )
Laurent Aimar's avatar
Laurent Aimar committed
1403
    {
1404
        msg_Err( p_stream, "cannot find encoder (%s)", p_sys->psz_aenc );
1405
        module_Unneed( id->p_decoder, id->p_decoder->p_module );
1406
        id->p_decoder->p_module = NULL;
Gildas Bazin's avatar
 
Gildas Bazin committed
1407
        return VLC_EGENERIC;
Laurent Aimar's avatar
Laurent Aimar committed
1408
    }
1409
    id->p_encoder->fmt_in.audio.i_format = id->p_encoder->fmt_in.i_codec;
1410 1411
    id->p_encoder->fmt_in.audio.i_bitspersample =
        audio_BitsPerSample( id->p_encoder->fmt_in.i_codec );
1412

1413
    /* Load conversion filters */
1414 1415 1416 1417 1418 1419 1420 1421
    if( fmt_last.audio.i_channels != id->p_encoder->fmt_in.audio.i_channels ||
        fmt_last.audio.i_rate != id->p_encoder->fmt_in.audio.i_rate )
    {
        /* We'll have to go through fl32 first */
        es_format_t fmt_out = id->p_encoder->fmt_in;
        fmt_out.i_codec = fmt_out.audio.i_format = VLC_FOURCC('f','l','3','2');

        id->pp_filter[id->i_filter] =
1422
            transcode_audio_filter_new( p_stream, id, &fmt_last, &fmt_out, NULL );
1423 1424 1425 1426

        if( id->pp_filter[id->i_filter] ) id->i_filter++;
    }

1427
    for( i = 0; i < TRANSCODE_FILTERS; i++ )
1428
    {
1429 1430 1431 1432
        if( (fmt_last.audio.i_channels !=
            id->p_encoder->fmt_in.audio.i_channels) ||
            (fmt_last.audio.i_rate != id->p_encoder->fmt_in.audio.i_rate) ||
            (fmt_last.i_codec != id->p_encoder->fmt_in.i_codec) )
1433
        {
1434 1435
            id->pp_filter[id->i_filter] =
                transcode_audio_filter_new( p_stream, id, &fmt_last,
1436
                                            &id->p_encoder->fmt_in, NULL );
1437

1438 1439 1440 1441
            if( id->pp_filter[id->i_filter] )
                id->i_filter++;
            else
                break;
1442 1443 1444
        }
    }

1445 1446
    /* Final checks to see if conversions were successful */
    if( fmt_last.i_codec != id->p_encoder->fmt_in.i_codec )
1447
    {
1448
        msg_Err( p_stream, "no audio filter found (%4.4s->%4.4s)",
1449 1450
                 (char *)&fmt_last.i_codec,
                 (char *)&id->p_encoder->fmt_in.i_codec );
Rafaël Carré's avatar
Rafaël Carré committed
1451
        transcode_audio_close( id );
1452 1453
        return VLC_EGENERIC;
    }
1454

1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
    /* Load user specified audio filters now */
    for( i = 0; (i < p_sys->i_afilters) &&
                (id->i_ufilter < TRANSCODE_FILTERS); i++ )
    {
        id->pp_ufilter[id->i_ufilter] =
            transcode_audio_filter_new( p_stream, id, &fmt_last,
                                        &id->p_encoder->fmt_in,
                                        p_sys->psz_afilters[i] );

        if( id->pp_ufilter[id->i_ufilter] )
            id->i_ufilter++;
        else
            break;
    }

1470
    if( fmt_last.audio.i_channels != id->p_encoder->fmt_in.audio.i_channels )
1471
    {
1472 1473 1474 1475 1476
#if 1
        module_Unneed( id->p_encoder, id->p_encoder->p_module );
        id->p_encoder->p_module = NULL;

        /* This might work, but only if the encoder is restarted */
1477 1478
        id->p_encoder->fmt_in.audio.i_channels = fmt_last.audio.i_channels;
        id->p_encoder->fmt_out.audio.i_channels = fmt_last.audio.i_channels;
1479

1480 1481 1482 1483 1484 1485
        id->p_encoder->fmt_in.audio.i_physical_channels =
            id->p_encoder->fmt_in.audio.i_original_channels =
                fmt_last.audio.i_physical_channels;
        id->p_encoder->fmt_out.audio.i_physical_channels =
            id->p_encoder->fmt_out.audio.i_original_channels =
                fmt_last.audio.i_physical_channels;
1486 1487 1488 1489 1490 1491 1492 1493 1494

        msg_Dbg( p_stream, "number of audio channels for mixing changed, "
                 "trying to reopen the encoder for mixing %i to %i channels",
                 fmt_last.audio.i_channels,
                 id->p_encoder->fmt_in.audio.i_channels );

        /* reload encoder */
        id->p_encoder->p_cfg = p_stream->p_sys->p_audio_cfg;
        id->p_encoder->p_module =
1495
            module_Need( id->p_encoder, "encoder", p_sys->psz_aenc, true );
1496 1497 1498
        if( !id->p_encoder->p_module )
        {
            msg_Err( p_stream, "cannot find encoder (%s)", p_sys->psz_aenc );
Rafaël Carré's avatar
Rafaël Carré committed
1499
            transcode_audio_close( id );
1500 1501 1502 1503 1504
            return VLC_EGENERIC;
        }
        id->p_encoder->fmt_in.audio.i_format = id->p_encoder->fmt_in.i_codec;
        id->p_encoder->fmt_in.audio.i_bitspersample =
            audio_BitsPerSample( id->p_encoder->fmt_in.i_codec );
1505
#else
1506 1507 1508 1509
        msg_Err( p_stream, "no audio filter found for mixing from"
                 " %i to %i channels", fmt_last.audio.i_channels,
                 id->p_encoder->fmt_in.audio.i_channels );

Rafaël Carré's avatar
Rafaël Carré committed
1510
        transcode_audio_close( id );
1511 1512
        return VLC_EGENERIC;
#endif
1513 1514 1515 1516
    }

    if( fmt_last.audio.i_rate != id->p_encoder->fmt_in.audio.i_rate )
    {
1517
        msg_Err( p_stream, "no audio filter found for resampling from"
1518 1519
                 " %iHz to %iHz", fmt_last.audio.i_rate,
                 id->p_encoder->fmt_in.audio.i_rate );
1520 1521
#if 0
        /* FIXME : this might work, but only if the encoder is restarted */
1522 1523
        id->p_encoder->fmt_in.audio.i_rate = fmt_last.audio.i_rate;
        id->p_encoder->fmt_out.audio.i_rate = fmt_last.audio.i_rate;
1524
#else
Rafaël Carré's avatar
Rafaël Carré committed
1525
        transcode_audio_close( id );
1526 1527
        return VLC_EGENERIC;
#endif
1528 1529
    }

1530 1531 1532
    /* FIXME: Hack for mp3 transcoding support */
    if( id->p_encoder->fmt_out.i_codec == VLC_FOURCC( 'm','p','3',' ' ) )
        id->p_encoder->fmt_out.i_codec = VLC_FOURCC( 'm','p','g','a' );
Gildas Bazin's avatar
 
Gildas Bazin committed
1533

1534 1535 1536
    return VLC_SUCCESS;
}

Rafaël Carré's avatar
Rafaël Carré committed
1537
static void transcode_audio_close( sout_stream_id_t *id )
1538
{
1539
    int i;
Gildas Bazin's avatar
 
Gildas Bazin committed
1540

1541 1542
    audio_timer_close( id->p_encoder );

1543 1544 1545
    /* Close decoder */
    if( id->p_decoder->p_module )
        module_Unneed( id->p_decoder, id->p_decoder->p_module );
1546
    id->p_decoder->p_module = NULL;
1547

1548 1549 1550
    /* Close encoder */
    if( id->p_encoder->p_module )
        module_Unneed( id->p_encoder, id->p_encoder->p_module );
1551
    id->p_encoder->p_module = NULL;
1552

1553 1554 1555 1556 1557 1558
    /* Close filters */
    for( i = 0; i < id->i_filter; i++ )
    {
        vlc_object_detach( id->pp_filter[i] );
        if( id->pp_filter[i]->p_module )
            module_Unneed( id->pp_filter[i], id->pp_filter[i]->p_module );
1559
        vlc_object_release( id->pp_filter[i] );
1560
    }
1561 1562
    id->i_filter = 0;

1563 1564 1565 1566 1567
    for( i = 0; i < id->i_ufilter; i++ )
    {
        vlc_object_detach( id->pp_ufilter[i] );
        if( id->pp_ufilter[i]->p_module )
            module_Unneed( id->pp_ufilter[i], id->pp_ufilter[i]->p_module );
1568
        vlc_object_release( id->pp_ufilter[i] );
1569
    }
1570
    id->i_ufilter = 0;
1571 1572
}

1573 1574 1575
static int transcode_audio_process( sout_stream_t *p_stream,
                                    sout_stream_id_t *id,
                                    block_t *in, block_t **out )
1576
{
1577
    sout_stream_sys_t *p_sys = p_stream->p_sys;
1578 1579 1580
    aout_buffer_t *p_audio_buf;
    block_t *p_block, *p_audio_block;
    int i;
1581 1582
    *out = NULL;

1583 1584
    while( (p_audio_buf = id->p_decoder->pf_decode_audio( id->p_decoder,
                                                          &in )) )
1585
    {
1586
        sout_UpdateStatistic( p_stream->p_sout, SOUT_STATISTIC_DECODED_AUDIO, 1 );
1587
        if( p_sys->b_master_sync )
1588
        {
1589
            mtime_t i_dts = date_Get( &id->interpolated_pts ) + 1;
1590 1591
            if ( p_audio_buf->start_date - i_dts > MASTER_SYNC_MAX_DRIFT
                  || p_audio_buf->start_date - i_dts < -MASTER_SYNC_MAX_DRIFT )
1592
            {
1593
                msg_Dbg( p_stream, "drift is too high, resetting master sync" );
1594 1595 1596
                date_Set( &id->interpolated_pts, p_audio_buf->start_date );
                i_dts = p_audio_buf->start_date + 1;
            }
1597 1598 1599 1600
            p_sys->i_master_drift = p_audio_buf->start_date - i_dts;
            date_Increment( &id->interpolated_pts, p_audio_buf->i_nb_samples );
            p_audio_buf->start_date -= p_sys->i_master_drift;
            p_audio_buf->end_date -= p_sys->i_master_drift;
1601
        }
1602

1603 1604 1605 1606 1607 1608 1609
        p_audio_block = p_audio_buf->p_sys;
        p_audio_block->i_buffer = p_audio_buf->i_nb_bytes;
        p_audio_block->i_dts = p_audio_block->i_pts =
            p_audio_buf->start_date;
        p_audio_block->i_length = p_audio_buf->end_date -
            p_audio_buf->start_date;
        p_audio_block->i_samples = p_audio_buf->i_nb_samples;
1610

1611 1612
        /* Run filter chain */
        for( i = 0; i < id->i_filter; i++ )
1613
        {
1614 1615 1616
            p_audio_block =
                id->pp_filter[i]->pf_audio_filter( id->pp_filter[i],
                                                   p_audio_block );
1617 1618
        }

1619 1620 1621 1622 1623 1624 1625 1626
        /* Run user specified filter chain */
        for( i = 0; i < id->i_ufilter; i++ )
        {
            p_audio_block =
                id->pp_ufilter[i]->pf_audio_filter( id->pp_ufilter[i],
                                                    p_audio_block );
        }

1627 1628
        assert( p_audio_block );

1629 1630 1631 1632 1633
        p_audio_buf->p_buffer = p_audio_block->p_buffer;
        p_audio_buf->i_nb_bytes = p_audio_block->i_buffer;
        p_audio_buf->i_nb_samples = p_audio_block->i_samples;
        p_audio_buf->start_date = p_audio_block->i_dts;
        p_audio_buf->end_date = p_audio_block->i_dts + p_audio_block->i_length;
1634

1635
        audio_timer_start( id->p_encoder );
1636
        p_block = id->p_encoder->pf_encode_audio( id->p_encoder, p_audio_buf );
1637 1638
        audio_timer_stop( id->p_encoder );

1639 1640 1641 1642
        block_ChainAppend( out, p_block );
        block_Release( p_audio_block );
        free( p_audio_buf );
    }
1643

1644 1645
    return VLC_SUCCESS;
}
1646

1647 1648 1649
static void audio_release_buffer( aout_buffer_t *p_buffer )
{
    if( p_buffer && p_buffer->p_sys ) block_Release( p_buffer->p_sys );
1650
    free( p_buffer );
1651
}
1652

1653 1654 1655 1656 1657
static aout_buffer_t *audio_new_buffer( decoder_t *p_dec, int i_samples )
{
    aout_buffer_t *p_buffer;
    block_t *p_block;
    int i_size;
1658

1659 1660
    if( p_dec->fmt_out.audio.i_bitspersample )
    {
1661
        i_size = i_samples * p_dec->fmt_out.audio.i_bitspersample / 8 *
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
            p_dec->fmt_out.audio.i_channels;
    }
    else if( p_dec->fmt_out.audio.i_bytes_per_frame &&
             p_dec->fmt_out.audio.i_frame_length )
    {
        i_size = i_samples * p_dec->fmt_out.audio.i_bytes_per_frame /
            p_dec->fmt_out.audio.i_frame_length;
    }
    else
    {
        i_size = i_samples * 4 * p_dec->fmt_out.audio.i_channels;
    }
1674

1675
    p_buffer = malloc( sizeof(aout_buffer_t) );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
1676
    if( !p_buffer ) return NULL;
1677
    p_buffer->b_discontinuity = false;
1678 1679
    p_buffer->pf_release = audio_release_buffer;
    p_buffer->p_sys = p_block = block_New( p_dec, i_size );
Gildas Bazin's avatar
 
Gildas Bazin committed
1680

1681 1682 1683 1684
    p_buffer->p_buffer = p_block->p_buffer;
    p_buffer->i_size = p_buffer->i_nb_bytes = p_block->i_buffer;
    p_buffer->i_nb_samples = i_samples;
    p_block->i_samples = i_samples;
1685

1686
    return p_buffer;
1687 1688
}

1689 1690
static void audio_del_buffer( decoder_t *p_dec, aout_buffer_t *p_buffer )
{
Rafaël Carré's avatar
Rafaël Carré committed
1691
    VLC_UNUSED(p_dec);
1692
    if( p_buffer && p_buffer->p_sys ) block_Release( p_buffer->p_sys );
Rafaël Carré's avatar
Rafaël Carré committed
1693
    free( p_buffer );
1694
}
1695 1696 1697 1698

/*
 * video
 */
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722

static filter_t *transcode_video_filter_new( sout_stream_t *p_stream,
                                             es_format_t *p_fmt_in,
                                             es_format_t *p_fmt_out,
                                             config_chain_t  *p_cfg,
                                             const char *psz_name )
{
    sout_stream_sys_t *p_sys = p_stream->p_sys;
    filter_t *p_filter;
    int i;

    if( !p_stream || !p_fmt_in || !p_fmt_out ) return NULL;

    p_filter = vlc_object_create( p_stream, VLC_OBJECT_FILTER );
    vlc_object_attach( p_filter, p_stream );

    p_filter->pf_vout_buffer_new = video_new_buffer_filter;
    p_filter->pf_vout_buffer_del = video_del_buffer_filter;

    es_format_Copy( &p_filter->fmt_in,  p_fmt_in );
    es_format_Copy( &p_filter->fmt_out, p_fmt_out );
    p_filter->p_cfg = p_cfg;

    p_filter->p_module = module_Need( p_filter, "video filter2",
1723
                                      psz_name, true );
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
    if( !p_filter->p_module )
    {
        msg_Dbg( p_stream, "no video filter found" );
        vlc_object_detach( p_filter );
        vlc_object_release( p_filter );
        return NULL;
    }

    p_filter->p_owner = malloc( sizeof(filter_owner_sys_t) );
    if( !p_filter->p_owner )
    {
        module_Unneed( p_filter,p_filter->p_module );
        vlc_object_detach( p_filter );
        vlc_object_release( p_filter );
        return NULL;
    }

    for( i = 0; i < PICTURE_RING_SIZE; i++ )
        p_filter->p_owner->pp_pics[i] = 0;
    p_filter->p_owner->p_sys = p_sys;

    return p_filter;
}

static void transcode_video_filter_close( sout_stream_t *p_stream,
                                          filter_t *p_filter )
{
    int j;

    if( !p_stream || !p_filter ) return;

    vlc_object_detach( p_filter );
    if( p_filter->p_module )
        module_Unneed( p_filter, p_filter->p_module );

    /* Clean-up pictures ring buffer */
    for( j = 0; j < PICTURE_RING_SIZE; j++ )
    {
        if( p_filter->p_owner->pp_pics[j] )
            video_del_buffer( VLC_OBJECT(p_filter),
                              p_filter->p_owner->pp_pics[j] );
    }
    free( p_filter->p_owner );
    vlc_object_release( p_filter );
    p_filter = NULL;
}

1771
static int transcode_video_new( sout_stream_t *p_stream, sout_stream_id_t *id )
1772
{
1773
    sout_stream_sys_t *p_sys = p_stream->p_sys;
1774
    int i;
1775

1776 1777
    /* Open decoder
     * Initialization of decoder structures
1778
     */
1779 1780 1781
    id->p_decoder->fmt_out = id->p_decoder->fmt_in;
    id->p_decoder->fmt_out.i_extra = 0;
    id->p_decoder->fmt_out.p_extra = 0;
1782 1783
    id->p_decoder->pf_decode_video = NULL;
    id->p_decoder->pf_get_cc = NULL;
1784
    id->p_decoder->pf_get_cc = 0;
1785 1786 1787 1788 1789 1790 1791
    id->p_decoder->pf_vout_buffer_new = video_new_buffer_decoder;
    id->p_decoder->pf_vout_buffer_del = video_del_buffer_decoder;
    id->p_decoder->pf_picture_link    = video_link_picture_decoder;
    id->p_decoder->pf_picture_unlink  = video_unlink_picture_decoder;
    id->p_decoder->p_owner = malloc( sizeof(decoder_owner_sys_t) );
    for( i = 0; i < PICTURE_RING_SIZE; i++ )
        id->p_decoder->p_owner->pp_pics[i] = 0;
1792
    id->p_decoder->p_owner->p_sys = p_sys;
1793
    /* id->p_decoder->p_cfg = p_sys->p_video_cfg; */
1794

1795 1796
    id->p_decoder->p_module =
        module_Need( id->p_decoder, "decoder", "$codec", 0 );
1797

1798 1799 1800 1801
    if( !id->p_decoder->p_module )
    {
        msg_Err( p_stream, "cannot find decoder" );
        return VLC_EGENERIC;
1802
    }
1803

1804 1805 1806 1807 1808 1809
    /*
     * Open encoder.
     * Because some info about the decoded input will only be available
     * once the first frame is decoded, we actually only test the availability
     * of the encoder here.
     */
Gildas Bazin's avatar
 
Gildas Bazin committed
1810

Gildas Bazin's avatar
 
Gildas Bazin committed
1811
    /* Initialization of encoder format structures */
1812 1813 1814
    es_format_Init( &id->p_encoder->fmt_in, id->p_decoder->fmt_in.i_cat,
                    id->p_decoder->fmt_out.i_codec );
    id->p_encoder->fmt_in.video.i_chroma = id->p_decoder->fmt_out.i_codec;
Gildas Bazin's avatar
 
Gildas Bazin committed
1815

1816
    /* The dimensions will be set properly later on.
1817
     * Just put sensible values so we can test an encoder is available. */
1818
    id->p_encoder->fmt_in.video.i_width =
1819 1820 1821 1822
        id->p_encoder->fmt_out.video.i_width ?
        id->p_encoder->fmt_out.video.i_width :
        id->p_decoder->fmt_in.video.i_width ?
        id->p_decoder->fmt_in.video.i_width : 16;
1823
    id->p_encoder->fmt_in.video.i_height =
1824 1825 1826 1827
        id->p_encoder->fmt_out.video.i_height ?
        id->p_encoder->fmt_out.video.i_height :
        id->p_decoder->fmt_in.video.i_height ?
        id->p_decoder->fmt_in.video.i_height : 16;
1828 1829
    id->p_encoder->fmt_in.video.i_frame_rate = ENC_FRAMERATE;
    id->p_encoder->fmt_in.video.i_frame_rate_base = ENC_FRAMERATE_BASE;
Gildas Bazin's avatar
 
Gildas Bazin committed
1830

1831
    id->p_encoder->i_threads = p_sys->i_threads;
1832 1833
    id->p_encoder->p_cfg = p_sys->p_video_cfg;

Gildas Bazin's avatar
 
Gildas Bazin committed
1834
    id->p_encoder->p_module =
1835
        module_Need( id->p_encoder, "encoder", p_sys->psz_venc, true );
Gildas Bazin's avatar
 
Gildas Bazin committed
1836
    if( !id->p_encoder->p_module )
1837
    {
1838
        msg_Err( p_stream, "cannot find encoder (%s)", p_sys->psz_venc );
1839 1840
        module_Unneed( id->p_decoder, id->p_decoder->p_module );
        id->p_decoder->p_module = 0;
Gildas Bazin's avatar
 
Gildas Bazin committed
1841
        return VLC_EGENERIC;
1842
    }
Laurent Aimar's avatar
Laurent Aimar committed
1843

Gildas Bazin's avatar
 
Gildas Bazin committed
1844
    /* Close the encoder.
1845
     * We'll open it only when we have the first frame. */
Gildas Bazin's avatar
 
Gildas Bazin committed
1846
    module_Unneed( id->p_encoder, id->p_encoder->p_module );
1847
    if( id->p_encoder->fmt_out.p_extra )
1848
    {
1849
        free( id->p_encoder->fmt_out.p_extra );
1850 1851 1852
        id->p_encoder->fmt_out.p_extra = NULL;
        id->p_encoder->fmt_out.i_extra = 0;
    }
Gildas Bazin's avatar
 
Gildas Bazin committed
1853
    id->p_encoder->p_module = NULL;
1854

1855
    if( p_sys->i_threads >= 1 )
1856
    {
1857 1858
        int i_priority = p_sys->b_high_priority ? VLC_THREAD_PRIORITY_OUTPUT :
                           VLC_THREAD_PRIORITY_VIDEO;
1859
        p_sys->id_video = id;
1860
        vlc_mutex_init( &p_sys->lock_out );
1861 1862 1863 1864 1865 1866
        vlc_cond_init( p_stream, &p_sys->cond );
        memset( p_sys->pp_pics, 0, sizeof(p_sys->pp_pics) );
        p_sys->i_first_pic = 0;
        p_sys->i_last_pic = 0;
        p_sys->p_buffers = NULL;
        p_sys->b_die = p_sys->b_error = 0;
1867
        if( vlc_thread_create( p_sys, "encoder", EncoderThread, i_priority,
1868
                               false ) )
1869 1870
        {
            msg_Err( p_stream, "cannot spawn encoder thread" );
1871 1872
            module_Unneed( id->p_decoder, id->p_decoder->p_module );
            id->p_decoder->p_module = 0;
1873 1874 1875 1876
            return VLC_EGENERIC;
        }
    }

1877 1878 1879
    return VLC_SUCCESS;
}

1880 1881
static int transcode_video_encoder_open( sout_stream_t *p_stream,
                                         sout_stream_id_t *id )
1882
{
1883
     sout_stream_sys_t *p_sys = p_stream->p_sys;
1884

1885 1886
     /* Calculate scaling, padding, cropping etc.
      * width/height of source */
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
     int i_src_width = id->p_decoder->fmt_out.video.i_width;
     int i_src_height = id->p_decoder->fmt_out.video.i_height;

     /* with/height scaling */
     float f_scale_width = 1;
     float f_scale_height = 1;

     /* width/height of output stream */
     int i_dst_width;
     int i_dst_height;

     /* aspect ratio */
     float f_aspect = (float)id->p_decoder->fmt_out.video.i_aspect /
                             VOUT_ASPECT_FACTOR;

     msg_Dbg( p_stream, "decoder aspect is %i:%i",
                  id->p_decoder->fmt_out.video.i_aspect, VOUT_ASPECT_FACTOR );

     /* Change f_aspect from source frame to source pixel */
     f_aspect = f_aspect * i_src_height / i_src_width;
     msg_Dbg( p_stream, "source pixel aspect is %f:1", f_aspect );

     /* width/height after cropping */
     p_sys->i_src_x_offset = p_sys->i_crop_left & ~1;
     p_sys->i_src_y_offset = p_sys->i_crop_top & ~1;
     p_sys->i_crop_width = i_src_width - ( p_sys->i_crop_left & ~1 ) -
                            ( p_sys->i_crop_right & ~1 );
     p_sys->i_crop_height = i_src_height - ( p_sys->i_crop_top & ~1 ) -
                            ( p_sys->i_crop_bottom & ~1 );

    /* Calculate scaling factor for specified parameters */
1918 1919
    if( id->p_encoder->fmt_out.video.i_width <= 0 &&
        id->p_encoder->fmt_out.video.i_height <= 0 && p_sys->f_scale )
1920
    {
1921
        /* Global scaling. Make sure width will remain a factor of 16 */
1922
        float f_real_scale;
1923 1924 1925 1926 1927
        int  i_new_height;
        int i_new_width = i_src_width * p_sys->f_scale;

        if( i_new_width % 16 <= 7 && i_new_width >= 16 )
            i_new_width -= i_new_width % 16;
1928
        else
1929 1930 1931
            i_new_width += 16 - i_new_width % 16;

        f_real_scale = (float)( i_new_width ) / (float) i_src_width;
1932

1933
        i_new_height = __MAX( 16, i_src_height * (float)f_real_scale );
1934

1935 1936
        f_scale_width = f_real_scale;
        f_scale_height = (float) i_new_height / (float) i_src_height;
1937 1938 1939 1940
    }
    else if( id->p_encoder->fmt_out.video.i_width > 0 &&
             id->p_encoder->fmt_out.video.i_height <= 0 )
    {
1941 1942 1943 1944
        /* Only width specified */
        f_scale_width = (float)id->p_encoder->fmt_out.video.i_width /
                             p_sys->i_crop_width;
        f_scale_height = f_scale_width;
1945 1946 1947 1948
    }
    else if( id->p_encoder->fmt_out.video.i_width <= 0 &&
             id->p_encoder->fmt_out.video.i_height > 0 )
    {
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
         /* Only height specified */
         f_scale_height = (float)id->p_encoder->fmt_out.video.i_height /
                              p_sys->i_crop_height;
         f_scale_width = f_scale_height;
     }
     else if( id->p_encoder->fmt_out.video.i_width > 0 &&
              id->p_encoder->fmt_out.video.i_height > 0 )
     {
         /* Width and height specified */
         f_scale_width = (float)id->p_encoder->fmt_out.video.i_width
                               / p_sys->i_crop_width;
         f_scale_height = (float)id->p_encoder->fmt_out.video.i_height
                               / p_sys->i_crop_height;
     }

1964 1965 1966 1967
     /* check maxwidth and maxheight
      * note: maxwidth and maxheight currently does not handle
      * canvas and padding, just scaling and cropping.
      */
1968 1969 1970 1971 1972
     if( p_sys->i_maxwidth && f_scale_width > (float)p_sys->i_maxwidth /
                                                     p_sys->i_crop_width )
     {
         f_scale_width = (float)p_sys->i_maxwidth / p_sys->i_crop_width;
     }
1973

1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
     if( p_sys->i_maxheight && f_scale_height > (float)p_sys->i_maxheight /
                                                       p_sys->i_crop_height )
     {
         f_scale_height = (float)p_sys->i_maxheight / p_sys->i_crop_height;
     }

     /* Change aspect ratio from source pixel to scaled pixel */
     f_aspect = f_aspect * f_scale_height / f_scale_width;
     msg_Dbg( p_stream, "scaled pixel aspect is %f:1", f_aspect );

1984 1985 1986
     /* Correct scaling for target aspect ratio
      * Shrink video if necessary
      */
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
     if ( p_sys->i_canvas_aspect > 0 )
     {
         float f_target_aspect = (float)p_sys->i_canvas_aspect /
                                        VOUT_ASPECT_FACTOR;

         if( p_sys->i_canvas_width > 0 && p_sys->i_canvas_height > 0)
         {
             /* Calculate pixel aspect of canvas */
             f_target_aspect = f_target_aspect / p_sys->i_canvas_width *
                               p_sys->i_canvas_height;
         }
         if( f_target_aspect > f_aspect )
         {
             /* Reduce width scale to increase aspect */
             f_scale_width = f_scale_width * f_aspect / f_target_aspect;
         }
         else
         {
             /* Reduce height scale to decrease aspect */
             f_scale_height = f_scale_height * f_target_aspect / f_aspect;
         }
         f_aspect = f_target_aspect;
2009
         msg_Dbg( p_stream, "canvas scaled pixel aspect is %f:1", f_aspect );
2010 2011 2012
     }

     /* f_scale_width and f_scale_height are now final */
2013 2014 2015
     /* Calculate width, height from scaling
      * Make sure its multiple of 2
      */
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
     i_dst_width = 2 * (int)( p_sys->i_crop_width * f_scale_width / 2 + 0.5 );
     i_dst_height = 2 *
                    (int)( p_sys->i_crop_height * f_scale_height / 2 + 0.5 );

     p_sys->i_nopadd_width = i_dst_width;
     p_sys->i_nopadd_height = i_dst_height;
     p_sys->i_dst_x_offset = 0;
     p_sys->i_dst_y_offset = 0;

     /* Handle canvas and padding */
     if( p_sys->i_canvas_width <= 0 )
     {
         /* No canvas width set, add explicit padding border */
         i_dst_width = p_sys->i_nopadd_width + ( p_sys->i_padd_left & ~1 ) +
                      ( p_sys->i_padd_right & ~1 );
         p_sys->i_dst_x_offset = ( p_sys->i_padd_left & ~1 );
     }
     else
     {
         /* Canvas set, check if we have to padd or crop */
         if( p_sys->i_canvas_width < p_sys->i_nopadd_width )
         {
             /* need to crop more, but keep same scaling */
             int i_crop = 2 * (int)( ( p_sys->i_canvas_width & ~1 ) /
                                       f_scale_width / 2 + 0.5 );

             p_sys->i_src_x_offset += ( ( p_sys->i_crop_width - i_crop ) / 2 )
                                           & ~1;
             p_sys->i_crop_width = i_crop;
             i_dst_width = p_sys->i_canvas_width & ~1;
             p_sys->i_nopadd_width = i_dst_width;
         }
         else if( p_sys->i_canvas_width > p_sys->i_nopadd_width )
         {
             /* need to padd */
             i_dst_width = p_sys->i_canvas_width & ~1;
             p_sys->i_dst_x_offset = ( i_dst_width - p_sys->i_nopadd_width )/2;
             p_sys->i_dst_x_offset = p_sys->i_dst_x_offset & ~1;
         }
     }

     if( p_sys->i_canvas_height <= 0 )
     {
         /* No canvas set, add padding border */
         i_dst_height = p_sys->i_nopadd_height + ( p_sys->i_padd_top & ~1 ) +
                        ( p_sys->i_padd_bottom & ~1 );
         p_sys->i_dst_y_offset = ( p_sys->i_padd_top & ~1 );
     }
     else
     {
         /* Canvas set, check if we have to padd or crop */
         if( p_sys->i_canvas_height < p_sys->i_nopadd_height )
         {
             /* need to crop more, but keep same scaling */
             int i_crop = 2 * (int)( ( p_sys->i_canvas_height & ~1 ) /
                                        f_scale_height / 2 + 0.5 );

             p_sys->i_src_y_offset += ( ( p_sys->i_crop_height - i_crop ) / 2 )
                                                & ~1;
             p_sys->i_crop_height = i_crop;
             i_dst_height = p_sys->i_canvas_height & ~1;
             p_sys->i_nopadd_height = i_dst_height;
         }
         else if( p_sys->i_canvas_height > p_sys->i_nopadd_height )
         {
             /* need to padd */
             i_dst_height = p_sys->i_canvas_height & ~1;
             p_sys->i_dst_y_offset = ( i_dst_height - p_sys->i_nopadd_height )
                                        /2;
             p_sys->i_dst_y_offset = p_sys->i_dst_y_offset & ~1;
         }
     }

     /* Change aspect ratio from scaled pixel to output frame */
     f_aspect = f_aspect * i_dst_width / i_dst_height;

     /* Store calculated values */
     id->p_encoder->fmt_out.video.i_width = i_dst_width;
     id->p_encoder->fmt_out.video.i_height = i_dst_height;

     id->p_encoder->fmt_in.video.i_width = i_dst_width;
     id->p_encoder->fmt_in.video.i_height = i_dst_height;

2099
     msg_Dbg( p_stream, "source %ix%i, crop %ix%i, "
2100 2101 2102 2103 2104 2105 2106 2107
                        "destination %ix%i, padding %ix%i",
         i_src_width, i_src_height,
         p_sys->i_crop_width, p_sys->i_crop_height,
         p_sys->i_nopadd_width, p_sys->i_nopadd_height,
         i_dst_width, i_dst_height
     );

    /* Handle frame rate conversion */
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
    if( !id->p_encoder->fmt_out.video.i_frame_rate ||
        !id->p_encoder->fmt_out.video.i_frame_rate_base )
    {
        if( id->p_decoder->fmt_out.video.i_frame_rate &&
            id->p_decoder->fmt_out.video.i_frame_rate_base )
        {
            id->p_encoder->fmt_out.video.i_frame_rate =
                id->p_decoder->fmt_out.video.i_frame_rate;
            id->p_encoder->fmt_out.video.i_frame_rate_base =
                id->p_decoder->fmt_out.video.i_frame_rate_base;
        }
        else
        {
            /* Pick a sensible default value */
2122 2123
            id->p_encoder->fmt_out.video.i_frame_rate = ENC_FRAMERATE;
            id->p_encoder->fmt_out.video.i_frame_rate_base = ENC_FRAMERATE_BASE;
2124 2125 2126 2127 2128 2129 2130
        }
    }

    id->p_encoder->fmt_in.video.i_frame_rate =
        id->p_encoder->fmt_out.video.i_frame_rate;
    id->p_encoder->fmt_in.video.i_frame_rate_base =
        id->p_encoder->fmt_out.video.i_frame_rate_base;
2131

2132 2133 2134 2135 2136 2137
    date_Init( &id->interpolated_pts,
               id->p_encoder->fmt_out.video.i_frame_rate,
               id->p_encoder->fmt_out.video.i_frame_rate_base );

    /* Check whether a particular aspect ratio was requested */
    if( !id->p_encoder->fmt_out.video.i_aspect )
2138
    {
2139 2140
        id->p_encoder->fmt_out.video.i_aspect =
                (int)( f_aspect * VOUT_ASPECT_FACTOR + 0.5 );
2141
    }
2142 2143
    id->p_encoder->fmt_in.video.i_aspect =
        id->p_encoder->fmt_out.video.i_aspect;
2144

2145 2146
    msg_Dbg( p_stream, "encoder aspect is %i:%i",
             id->p_encoder->fmt_out.video.i_aspect, VOUT_ASPECT_FACTOR );
2147

2148
    id->p_encoder->p_module =
2149
        module_Need( id->p_encoder, "encoder", p_sys->psz_venc, true );
2150
    if( !id->p_encoder->p_module )
2151
    {
2152
        msg_Err( p_stream, "cannot find encoder (%s)", p_sys->psz_venc );
2153
        return VLC_EGENERIC;
2154
    }
2155 2156 2157 2158 2159 2160

    id->p_encoder->fmt_in.video.i_chroma = id->p_encoder->fmt_in.i_codec;

    /* Hack for mp2v/mp1v transcoding support */
    if( id->p_encoder->fmt_out.i_codec == VLC_FOURCC('m','p','1','v') ||
        id->p_encoder->fmt_out.i_codec == VLC_FOURCC('m','p','2','v') )
2161
    {
2162
        id->p_encoder->fmt_out.i_codec = VLC_FOURCC('m','p','g','v');
2163
    }
2164 2165 2166 2167

    id->id = p_stream->p_sys->p_out->pf_add( p_stream->p_sys->p_out,
                                             &id->p_encoder->fmt_out );
    if( !id->id )
2168
    {
2169 2170
        msg_Err( p_stream, "cannot add this stream" );
        return VLC_EGENERIC;
2171
    }
2172 2173 2174 2175 2176 2177 2178

    return VLC_SUCCESS;
}

static void transcode_video_close( sout_stream_t *p_stream,
                                   sout_stream_id_t *id )
{
2179
    int i;
2180 2181

    if( p_stream->p_sys->i_threads >= 1 )
2182
    {
2183
        vlc_mutex_lock( &p_stream->p_sys->lock_out );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
2184
        vlc_object_kill( p_stream->p_sys );
2185 2186 2187 2188 2189
        vlc_cond_signal( &p_stream->p_sys->cond );
        vlc_mutex_unlock( &p_stream->p_sys->lock_out );
        vlc_thread_join( p_stream->p_sys );
        vlc_mutex_destroy( &p_stream->p_sys->lock_out );
        vlc_cond_destroy( &p_stream->p_sys->cond );
2190
    }
2191

2192 2193
    video_timer_close( id->p_encoder );

2194 2195 2196 2197
    /* Close decoder */
    if( id->p_decoder->p_module )
        module_Unneed( id->p_decoder, id->p_decoder->p_module );

2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
    if( id->p_decoder->p_owner )
    {
        /* Clean-up pictures ring buffer */
        for( i = 0; i < PICTURE_RING_SIZE; i++ )
        {
            if( id->p_decoder->p_owner->pp_pics[i] )
                video_del_buffer( VLC_OBJECT(id->p_decoder),
                                  id->p_decoder->p_owner->pp_pics[i] );
        }
        free( id->p_decoder->p_owner );
    }

2210 2211 2212 2213 2214 2215
    /* Close encoder */
    if( id->p_encoder->p_module )
        module_Unneed( id->p_encoder, id->p_encoder->p_module );

    /* Close filters */
    for( i = 0; i < id->i_filter; i++ )
2216
    {
2217
        transcode_video_filter_close( p_stream, id->pp_filter[i] );
2218
        id->pp_filter[i] = NULL;
2219
    }
2220
    id->i_filter = 0;
2221 2222

    for( i = 0; i < id->i_ufilter; i++ )
2223
    {
2224
        transcode_video_filter_close( p_stream, id->pp_ufilter[i] );
2225
        id->pp_ufilter[i] = NULL;
2226
    }
2227
    id->i_ufilter = 0;
2228 2229
}

2230 2231 2232
static int transcode_video_process( sout_stream_t *p_stream,
                                    sout_stream_id_t *id,
                                    block_t *in, block_t **out )
2233
{
2234
    sout_stream_sys_t *p_sys = p_stream->p_sys;
2235
    int i_duplicate = 1, i;
2236
    picture_t *p_pic, *p_pic2 = NULL;
2237
    *out = NULL;
Clément Stenac's avatar
Clément Stenac committed
2238

2239
    while( (p_pic = id->p_decoder->pf_decode_video( id->p_decoder, &in )) )
2240
    {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2241
        subpicture_t *p_subpic = NULL;
2242 2243

        sout_UpdateStatistic( p_stream->p_sout, SOUT_STATISTIC_DECODED_VIDEO, 1 );
2244

2245 2246 2247
        if( p_stream->p_sout->i_out_pace_nocontrol && p_sys->b_hurry_up )
        {
            mtime_t current_date = mdate();
2248
            if( current_date + 50000 > p_pic->date )
2249
            {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
2250
                msg_Dbg( p_stream, "late picture skipped (%"PRId64")",
2251
                         current_date + 50000 - p_pic->date );
2252 2253 2254 2255 2256
                p_pic->pf_release( p_pic );
                continue;
            }
        }

2257
        if( p_sys->b_master_sync )
2258 2259
        {
            mtime_t i_video_drift;
2260
            mtime_t i_master_drift = p_sys->i_master_drift;
2261
            mtime_t i_pts;
2262

2263
            i_pts = date_Get( &id->interpolated_pts ) + 1;
2264 2265
            if ( p_pic->date - i_pts > MASTER_SYNC_MAX_DRIFT
                  || p_pic->date - i_pts < -MASTER_SYNC_MAX_DRIFT )
2266
            {
2267
                msg_Dbg( p_stream, "drift is too high, resetting master sync" );
2268 2269
                date_Set( &id->interpolated_pts, p_pic->date );
                i_pts = p_pic->date + 1;
2270
            }
2271
            i_video_drift = p_pic->date - i_pts;
2272 2273
            i_duplicate = 1;

2274 2275 2276
            /* Set the pts of the frame being encoded */
            p_pic->date = i_pts;

Jean-Paul Saman's avatar
Jean-Paul Saman committed
2277
            if( i_video_drift < (i_master_drift - 50000) )
2278
            {
2279
#if 0
2280
                msg_Dbg( p_stream, "dropping frame (%i)",
2281
                         (int)(i_video_drift - i_master_drift) );
2282
#endif
2283
                p_pic->pf_release( p_pic );
2284
                continue;
2285
            }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2286
            else if( i_video_drift > (i_master_drift + 50000) )
2287
            {
2288
#if 0
2289
                msg_Dbg( p_stream, "adding frame (%i)",
2290
                         (int)(i_video_drift - i_master_drift) );
2291
#endif
2292 2293 2294 2295
                i_duplicate = 2;
            }
        }

2296
        if( !id->p_encoder->p_module )
2297
        {
2298
            if( transcode_video_encoder_open( p_stream, id ) != VLC_SUCCESS )
Gildas Bazin's avatar
 
Gildas Bazin committed
2299
            {
2300
                p_pic->pf_release( p_pic );
2301
                transcode_video_close( p_stream, id );
2302
                id->b_transcode = false;
2303
                return VLC_EGENERIC;
Gildas Bazin's avatar
 
Gildas Bazin committed
2304 2305
            }

2306 2307 2308 2309
            /* Deinterlace */
            if( p_stream->p_sys->b_deinterlace )
            {
                id->pp_filter[id->i_filter] =
2310
                    transcode_video_filter_new( p_stream,
2311 2312
                            &id->p_decoder->fmt_out,
                            &id->p_decoder->fmt_out,
2313 2314
                            p_sys->p_deinterlace_cfg,
                            p_sys->psz_deinterlace );
2315

2316
                if( id->pp_filter[id->i_filter] )
2317
                    id->i_filter++;
2318 2319 2320 2321 2322 2323
            }

#if (defined(HAVE_FFMPEG_SWSCALE_H) || defined(HAVE_LIBSWSCALE_TREE)) || defined(HAVE_LIBSWSCALE_SWSCALE_H)
            if( ( id->p_decoder->fmt_out.video.i_chroma !=
                  id->p_encoder->fmt_in.video.i_chroma ) ||
                ( id->p_decoder->fmt_out.video.i_width !=
2324
                  id->p_encoder->fmt_in.video.i_width ) ||
2325
                ( id->p_decoder->fmt_out.video.i_height !=
2326
                  id->p_encoder->fmt_in.video.i_height ) )
2327 2328 2329
            {
                id->pp_filter[id->i_filter] =
                    transcode_video_filter_new( p_stream,
2330 2331
                            &id->p_decoder->fmt_out,
                            &id->p_encoder->fmt_in,
2332 2333
                            NULL, "scale" );
                if( !id->pp_filter[id->i_filter] )
2334
                {
2335 2336
                    p_pic->pf_release( p_pic );
                    transcode_video_close( p_stream, id );
2337
                    id->b_transcode = false;
2338
                    return VLC_EGENERIC;
2339
                }
2340
                id->i_filter++;
2341
            }
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
#if 0 /* FIXME: */
            /* we don't do chroma conversion or scaling in croppad */
//             es_format_t fmt_in, fmt_out;
//             es_format_Copy( &fmt_out, &id->p_encoder->fmt_in );
//             es_format_Copy( &fmt_in, &id->p_encoder->fmt_in );

            if( ( id->p_decoder->fmt_out.video.i_chroma ==
                  id->p_encoder->fmt_in.video.i_chroma ) &&

                ( ( (int)id->p_decoder->fmt_out.video.i_width !=
                    p_sys->i_crop_width ) ||
                  ( p_sys->i_crop_width != p_sys->i_nopadd_width ) ||
2354
                  ( p_sys->i_nopadd_width !=
2355 2356 2357 2358 2359
                    (int)id->p_encoder->fmt_out.video.i_width ) ||

                  ( (int)id->p_decoder->fmt_out.video.i_height !=
                    p_sys->i_crop_height ) ||
                  ( p_sys->i_crop_height != p_sys->i_nopadd_height ) ||
2360
                  ( p_sys->i_nopadd_height !=
2361 2362 2363 2364
                    (int)id->p_encoder->fmt_out.video.i_height ) ) )
            {
                id->pp_filter[id->i_filter] =
                    transcode_video_filter_new( p_stream,
2365 2366
                            &id->p_decoder->fmt_out,
                            &id->p_encoder->fmt_in,
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
                            NULL, "croppadd" );
                if( id->pp_filter[id->i_filter] )
                {
                    /* Set crop and padding information */
                    id->pp_filter[id->i_filter]->fmt_in.video.i_x_offset = p_sys->i_src_x_offset;
                    id->pp_filter[id->i_filter]->fmt_in.video.i_y_offset = p_sys->i_src_y_offset;
                    id->pp_filter[id->i_filter]->fmt_in.video.i_visible_width = p_sys->i_crop_width;
                    id->pp_filter[id->i_filter]->fmt_in.video.i_visible_height = p_sys->i_crop_height;

                    id->pp_filter[id->i_filter]->fmt_out.video.i_x_offset = p_sys->i_dst_x_offset;
                    id->pp_filter[id->i_filter]->fmt_out.video.i_y_offset = p_sys->i_dst_y_offset;
                    id->pp_filter[id->i_filter]->fmt_out.video.i_visible_width = p_sys->i_nopadd_width;
                    id->pp_filter[id->i_filter]->fmt_out.video.i_visible_height = p_sys->i_nopadd_height;
2380

2381 2382 2383 2384 2385
                    id->i_filter++;
                }
            }
#endif
#else
2386 2387 2388
            /* Check if we need a filter for chroma conversion or resizing */
            if( id->p_decoder->fmt_out.video.i_chroma !=
                id->p_encoder->fmt_in.video.i_chroma ||
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2389

2390 2391 2392
                (int)id->p_decoder->fmt_out.video.i_width != p_sys->i_crop_width ||
                p_sys->i_crop_width != p_sys->i_nopadd_width ||
                p_sys->i_nopadd_width != (int)id->p_encoder->fmt_out.video.i_width ||
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2393

2394 2395 2396
                (int)id->p_decoder->fmt_out.video.i_height != p_sys->i_crop_height ||
                p_sys->i_crop_height != p_sys->i_nopadd_height ||
                p_sys->i_nopadd_height != (int)id->p_encoder->fmt_out.video.i_height)
Gildas Bazin's avatar
 
Gildas Bazin committed
2397
            {
2398
                id->pp_filter[id->i_filter] =
2399
                    transcode_video_filter_new( p_stream,
2400 2401
                            &id->p_decoder->fmt_out,
                            &id->p_encoder->fmt_in,
2402 2403 2404 2405 2406
                            NULL, "crop padd" );
                if( !id->pp_filter[id->i_filter] )
                {
                    p_pic->pf_release( p_pic );
                    transcode_video_close( p_stream, id );
2407
                    id->b_transcode = false;
2408 2409
                    return VLC_EGENERIC;
                }
2410

2411
                /* Set crop and padding information */ 
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
                id->pp_filter[id->i_filter]->fmt_in.video.i_x_offset = p_sys->i_src_x_offset;
                id->pp_filter[id->i_filter]->fmt_in.video.i_y_offset = p_sys->i_src_y_offset;
                id->pp_filter[id->i_filter]->fmt_in.video.i_visible_width = p_sys->i_crop_width;
                id->pp_filter[id->i_filter]->fmt_in.video.i_visible_height = p_sys->i_crop_height;

                id->pp_filter[id->i_filter]->fmt_out.video.i_x_offset = p_sys->i_dst_x_offset;
                id->pp_filter[id->i_filter]->fmt_out.video.i_y_offset = p_sys->i_dst_y_offset;
                id->pp_filter[id->i_filter]->fmt_out.video.i_visible_width = p_sys->i_nopadd_width;
                id->pp_filter[id->i_filter]->fmt_out.video.i_visible_height = p_sys->i_nopadd_height;

2422
                id->i_filter++;
Gildas Bazin's avatar
 
Gildas Bazin committed
2423
            }
2424
#endif
2425
            for( i = 0; (i < p_sys->i_vfilters) && (id->i_ufilter < TRANSCODE_FILTERS); i++ )
2426
            {
2427
                id->pp_ufilter[id->i_ufilter] =
2428 2429 2430 2431
                    transcode_video_filter_new( p_stream,
                            &id->p_decoder->fmt_out, &id->p_encoder->fmt_in,
                            p_sys->p_vfilters_cfg[i], p_sys->psz_vfilters[i] );
                if( id->pp_ufilter[id->i_filter] )
2432
                    id->i_ufilter++;
2433
                else
2434
                    id->pp_ufilter[id->i_ufilter] = NULL;
2435
            }
Gildas Bazin's avatar
 
Gildas Bazin committed
2436
        }
2437

2438 2439
        /* Run filter chain */
        for( i = 0; i < id->i_filter; i++ )
2440
        {
2441
            p_pic = id->pp_filter[i]->pf_video_filter(id->pp_filter[i], p_pic);
2442 2443
        }

2444 2445 2446
        /*
         * Encoding
         */
Gildas Bazin's avatar
 
Gildas Bazin committed
2447

2448
        /* Check if we have a subpicture to overlay */
2449
        if( p_sys->p_spu )
2450
        {
2451
            p_subpic = spu_SortSubpictures( p_sys->p_spu, p_pic->date,
2452
                       false /* Fixme: check if stream is paused */ );
2453
            /* TODO: get another pic */
2454
        }
Gildas Bazin's avatar
 
Gildas Bazin committed
2455

2456 2457 2458
        /* Overlay subpicture */
        if( p_subpic )
        {
2459 2460
            int i_scale_width, i_scale_height;
            video_format_t *p_fmt;
2461

2462 2463 2464 2465
            i_scale_width = id->p_encoder->fmt_in.video.i_width * 1000 /
                id->p_decoder->fmt_out.video.i_width;
            i_scale_height = id->p_encoder->fmt_in.video.i_height * 1000 /
                id->p_decoder->fmt_out.video.i_height;
2466

2467
            if( p_pic->i_refcount && !id->i_filter )
2468 2469
            {
                /* We can't modify the picture, we need to duplicate it */
2470
                picture_t *p_tmp = video_new_buffer_decoder( id->p_decoder );
2471 2472
                if( p_tmp )
                {
2473
                    vout_CopyPicture( p_stream, p_tmp, p_pic );
2474 2475 2476 2477 2478
                    p_pic->pf_release( p_pic );
                    p_pic = p_tmp;
                }
            }

2479 2480 2481 2482
            if( id->i_filter )
                p_fmt = &id->pp_filter[id->i_filter -1]->fmt_out.video;
            else
                p_fmt = &id->p_decoder->fmt_out.video;
2483

2484 2485 2486 2487 2488
            /* FIXME (shouldn't have to be done here) */
            p_fmt->i_sar_num = p_fmt->i_aspect *
                p_fmt->i_height / p_fmt->i_width;
            p_fmt->i_sar_den = VOUT_ASPECT_FACTOR;

2489 2490
            spu_RenderSubpictures( p_sys->p_spu, p_fmt, p_pic, p_pic, p_subpic,
                                   i_scale_width, i_scale_height );
2491 2492
        }

2493 2494
        /* Run user specified filter chain */
        for( i = 0; i < id->i_ufilter; i++ )
2495
        {
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2496 2497
            p_pic = id->pp_ufilter[i]->pf_video_filter( id->pp_ufilter[i],
                                                        p_pic );
2498 2499
        }

2500
        if( p_sys->i_threads == 0 )
2501 2502
        {
            block_t *p_block;
2503 2504

            video_timer_start( id->p_encoder );
2505
            p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
2506 2507
            video_timer_stop( id->p_encoder );

2508
            block_ChainAppend( out, p_block );
2509
        }
2510

2511 2512 2513
        if( p_sys->b_master_sync )
        {
            mtime_t i_pts = date_Get( &id->interpolated_pts ) + 1;
2514 2515
            if ( p_pic->date - i_pts > MASTER_SYNC_MAX_DRIFT
                  || p_pic->date - i_pts < -MASTER_SYNC_MAX_DRIFT )
2516
            {
2517
                msg_Dbg( p_stream, "drift is too high, resetting master sync" );
2518 2519 2520 2521 2522
                date_Set( &id->interpolated_pts, p_pic->date );
                i_pts = p_pic->date + 1;
            }
            date_Increment( &id->interpolated_pts, 1 );
        }
2523

2524 2525 2526
        if( p_sys->b_master_sync && i_duplicate > 1 )
        {
            mtime_t i_pts = date_Get( &id->interpolated_pts ) + 1;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2527 2528
            if( (p_pic->date - i_pts > MASTER_SYNC_MAX_DRIFT)
                 || ((p_pic->date - i_pts) < -MASTER_SYNC_MAX_DRIFT) )
2529
            {
2530
                msg_Dbg( p_stream, "drift is too high, resetting master sync" );
2531 2532 2533 2534 2535 2536 2537 2538
                date_Set( &id->interpolated_pts, p_pic->date );
                i_pts = p_pic->date + 1;
            }
            date_Increment( &id->interpolated_pts, 1 );

            if( p_sys->i_threads >= 1 )
            {
                /* We can't modify the picture, we need to duplicate it */
2539 2540
                p_pic2 = video_new_buffer_decoder( id->p_decoder );
                if( p_pic2 != NULL )
2541
                {
2542 2543
                    vout_CopyPicture( p_stream, p_pic2, p_pic );
                    p_pic2->date = i_pts;
2544 2545 2546
                }
            }
            else
2547
            {
2548
                block_t *p_block;
2549
                p_pic->date = i_pts;
2550
                p_block = id->p_encoder->pf_encode_video(id->p_encoder, p_pic);
2551 2552
                block_ChainAppend( out, p_block );
            }
2553
        }
2554

2555
        if( p_sys->i_threads == 0 )
2556
        {
2557
            p_pic->pf_release( p_pic );
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573
        }
        else
        {
            vlc_mutex_lock( &p_sys->lock_out );
            p_sys->pp_pics[p_sys->i_last_pic++] = p_pic;
            p_sys->i_last_pic %= PICTURE_RING_SIZE;
            *out = p_sys->p_buffers;
            p_sys->p_buffers = NULL;
            if( p_pic2 != NULL )
            {
                p_sys->pp_pics[p_sys->i_last_pic++] = p_pic2;
                p_sys->i_last_pic %= PICTURE_RING_SIZE;
            }
            vlc_cond_signal( &p_sys->cond );
            vlc_mutex_unlock( &p_sys->lock_out );
        }
2574 2575 2576 2577 2578
    }

    return VLC_SUCCESS;
}

2579
static int EncoderThread( sout_stream_sys_t *p_sys )
2580
{
2581 2582
    sout_stream_id_t *id = p_sys->id_video;
    picture_t *p_pic;
2583

2584
    while( !p_sys->b_die && !p_sys->b_error )
2585 2586 2587 2588
    {
        block_t *p_block;

        vlc_mutex_lock( &p_sys->lock_out );
2589
        while( p_sys->i_last_pic == p_sys->i_first_pic )
2590 2591
        {
            vlc_cond_wait( &p_sys->cond, &p_sys->lock_out );
2592
            if( p_sys->b_die || p_sys->b_error ) break;
2593
        }
2594
        if( p_sys->b_die || p_sys->b_error )
2595 2596 2597 2598 2599 2600 2601 2602 2603
        {
            vlc_mutex_unlock( &p_sys->lock_out );
            break;
        }

        p_pic = p_sys->pp_pics[p_sys->i_first_pic++];
        p_sys->i_first_pic %= PICTURE_RING_SIZE;
        vlc_mutex_unlock( &p_sys->lock_out );

2604
        video_timer_start( id->p_encoder );
2605
        p_block = id->p_encoder->pf_encode_video( id->p_encoder, p_pic );
2606 2607
        video_timer_stop( id->p_encoder );

2608
        vlc_mutex_lock( &p_sys->lock_out );
2609
        block_ChainAppend( &p_sys->p_buffers, p_block );
2610

2611 2612
        vlc_mutex_unlock( &p_sys->lock_out );
        p_pic->pf_release( p_pic );
2613 2614
    }

2615
    while( p_sys->i_last_pic != p_sys->i_first_pic )
2616 2617 2618
    {
        p_pic = p_sys->pp_pics[p_sys->i_first_pic++];
        p_sys->i_first_pic %= PICTURE_RING_SIZE;
2619
        p_pic->pf_release( p_pic );
2620
    }
2621
    block_ChainRelease( p_sys->p_buffers );
2622 2623

    return 0;
2624
}
Gildas Bazin's avatar
 
Gildas Bazin committed
2625

2626
struct picture_sys_t
Gildas Bazin's avatar
 
Gildas Bazin committed
2627
{
2628
    vlc_object_t *p_owner;
2629
};
Gildas Bazin's avatar
 
Gildas Bazin committed
2630

2631 2632 2633
static void video_release_buffer( picture_t *p_pic )
{
    if( p_pic && !p_pic->i_refcount && p_pic->pf_release && p_pic->p_sys )
2634
    {
2635
        video_del_buffer_decoder( (decoder_t *)p_pic->p_sys->p_owner, p_pic );
2636
    }
2637 2638
    else if( p_pic && p_pic->i_refcount > 0 ) p_pic->i_refcount--;
}
2639

2640 2641
static picture_t *video_new_buffer( vlc_object_t *p_this, picture_t **pp_ring,
                                    sout_stream_sys_t *p_sys )
2642
{
2643 2644 2645
    decoder_t *p_dec = (decoder_t *)p_this;
    picture_t *p_pic;
    int i;
2646

2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
    /* Find an empty space in the picture ring buffer */
    for( i = 0; i < PICTURE_RING_SIZE; i++ )
    {
        if( pp_ring[i] != 0 && pp_ring[i]->i_status == DESTROYED_PICTURE )
        {
            pp_ring[i]->i_status = RESERVED_PICTURE;
            return pp_ring[i];
        }
    }
    for( i = 0; i < PICTURE_RING_SIZE; i++ )
    {
        if( pp_ring[i] == 0 ) break;
    }

2661
    if( i == PICTURE_RING_SIZE && p_sys->i_threads >= 1 )
2662
    {
2663
        int i_first_pic = p_sys->i_first_pic;
2664

2665
        if( p_sys->i_first_pic != p_sys->i_last_pic )
2666 2667
        {
            /* Encoder still has stuff to encode, wait to clear-up the list */
2668
            while( p_sys->i_first_pic == i_first_pic )
2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686
                msleep( 100000 );
        }

        /* Find an empty space in the picture ring buffer */
        for( i = 0; i < PICTURE_RING_SIZE; i++ )
        {
            if( pp_ring[i] != 0 && pp_ring[i]->i_status == DESTROYED_PICTURE )
            {
                pp_ring[i]->i_status = RESERVED_PICTURE;
                return pp_ring[i];
            }
        }
        for( i = 0; i < PICTURE_RING_SIZE; i++ )
        {
            if( pp_ring[i] == 0 ) break;
        }
    }

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
    if( i == PICTURE_RING_SIZE )
    {
        msg_Err( p_this, "decoder/filter is leaking pictures, "
                 "resetting its ring buffer" );

        for( i = 0; i < PICTURE_RING_SIZE; i++ )
        {
            pp_ring[i]->pf_release( pp_ring[i] );
        }

        i = 0;
    }

    p_pic = malloc( sizeof(picture_t) );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2701
    if( !p_pic ) return NULL;
2702 2703 2704 2705 2706 2707 2708 2709
    p_dec->fmt_out.video.i_chroma = p_dec->fmt_out.i_codec;
    vout_AllocatePicture( VLC_OBJECT(p_dec), p_pic,
                          p_dec->fmt_out.video.i_chroma,
                          p_dec->fmt_out.video.i_width,
                          p_dec->fmt_out.video.i_height,
                          p_dec->fmt_out.video.i_aspect );

    if( !p_pic->i_planes )
2710
    {
2711
        free( p_pic );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2712
        return NULL;
2713
    }
Gildas Bazin's avatar
 
Gildas Bazin committed
2714

2715 2716
    p_pic->pf_release = video_release_buffer;
    p_pic->p_sys = malloc( sizeof(picture_sys_t) );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2717 2718 2719 2720 2721 2722
    if( !p_pic->p_sys )
    {
        free( p_pic );
        return NULL;
    }

2723 2724 2725 2726
    p_pic->p_sys->p_owner = p_this;
    p_pic->i_status = RESERVED_PICTURE;

    pp_ring[i] = p_pic;
2727 2728 2729
    return p_pic;
}

2730 2731 2732
static picture_t *video_new_buffer_decoder( decoder_t *p_dec )
{
    return video_new_buffer( VLC_OBJECT(p_dec),
2733
                             p_dec->p_owner->pp_pics, p_dec->p_owner->p_sys );
2734 2735 2736 2737 2738
}

static picture_t *video_new_buffer_filter( filter_t *p_filter )
{
    return video_new_buffer( VLC_OBJECT(p_filter),
2739 2740
                             p_filter->p_owner->pp_pics,
                             p_filter->p_owner->p_sys );
2741 2742 2743
}

static void video_del_buffer( vlc_object_t *p_this, picture_t *p_pic )
2744
{
Rafaël Carré's avatar
Rafaël Carré committed
2745 2746 2747 2748 2749 2750 2751
    VLC_UNUSED(p_this);
    if( p_pic )
    {
        free( p_pic->p_data_orig );
        free( p_pic->p_sys );
        free( p_pic );
    }
2752 2753
}

2754 2755
static void video_del_buffer_decoder( decoder_t *p_decoder, picture_t *p_pic )
{
Rafaël Carré's avatar
Rafaël Carré committed
2756
    VLC_UNUSED(p_decoder);
2757 2758 2759 2760 2761 2762
    p_pic->i_refcount = 0;
    p_pic->i_status = DESTROYED_PICTURE;
}

static void video_del_buffer_filter( filter_t *p_filter, picture_t *p_pic )
{
Rafaël Carré's avatar
Rafaël Carré committed
2763
    VLC_UNUSED(p_filter);
2764 2765 2766 2767 2768
    p_pic->i_refcount = 0;
    p_pic->i_status = DESTROYED_PICTURE;
}

static void video_link_picture_decoder( decoder_t *p_dec, picture_t *p_pic )
2769
{
Rafaël Carré's avatar
Rafaël Carré committed
2770
    VLC_UNUSED(p_dec);
2771 2772 2773
    p_pic->i_refcount++;
}

2774
static void video_unlink_picture_decoder( decoder_t *p_dec, picture_t *p_pic )
2775
{
Rafaël Carré's avatar
Rafaël Carré committed
2776
    VLC_UNUSED(p_dec);
2777
    video_release_buffer( p_pic );
Gildas Bazin's avatar
 
Gildas Bazin committed
2778
}
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789

/*
 * SPU
 */
static subpicture_t *spu_new_buffer( decoder_t * );
static void spu_del_buffer( decoder_t *, subpicture_t * );

static int transcode_spu_new( sout_stream_t *p_stream, sout_stream_id_t *id )
{
    sout_stream_sys_t *p_sys = p_stream->p_sys;

2790 2791 2792
    /*
     * Open decoder
     */
2793

2794
    /* Initialization of decoder structures */
2795
    id->p_decoder->pf_decode_sub = NULL;
2796 2797
    id->p_decoder->pf_spu_buffer_new = spu_new_buffer;
    id->p_decoder->pf_spu_buffer_del = spu_del_buffer;
2798
    id->p_decoder->p_owner = (decoder_owner_sys_t *)p_stream;
2799
    /* id->p_decoder->p_cfg = p_sys->p_spu_cfg; */
2800 2801

    id->p_decoder->p_module =
2802
        module_Need( id->p_decoder, "decoder", "$codec", 0 );
2803 2804 2805 2806 2807 2808 2809 2810 2811

    if( !id->p_decoder->p_module )
    {
        msg_Err( p_stream, "cannot find decoder" );
        return VLC_EGENERIC;
    }

    if( !p_sys->b_soverlay )
    {
2812
        /* Open encoder */
2813
        /* Initialization of encoder format structures */
2814 2815
        es_format_Init( &id->p_encoder->fmt_in, id->p_decoder->fmt_in.i_cat,
                        id->p_decoder->fmt_in.i_codec );
2816 2817 2818 2819

        id->p_encoder->p_cfg = p_sys->p_spu_cfg;

        id->p_encoder->p_module =
2820
            module_Need( id->p_encoder, "encoder", p_sys->psz_senc, true );
2821 2822 2823 2824

        if( !id->p_encoder->p_module )
        {
            module_Unneed( id->p_decoder, id->p_decoder->p_module );
2825
            msg_Err( p_stream, "cannot find encoder (%s)", p_sys->psz_senc );
2826 2827 2828
            return VLC_EGENERIC;
        }
    }
2829 2830

    if( !p_sys->p_spu )
2831
    {
2832 2833
        p_sys->p_spu = spu_Create( p_stream );
        spu_Init( p_sys->p_spu );
2834 2835 2836 2837 2838
    }

    return VLC_SUCCESS;
}

Rafaël Carré's avatar
Rafaël Carré committed
2839
static void transcode_spu_close( sout_stream_id_t *id)
2840 2841 2842 2843 2844 2845
{
    /* Close decoder */
    if( id->p_decoder->p_module )
        module_Unneed( id->p_decoder, id->p_decoder->p_module );

    /* Close encoder */
2846 2847
    if( id->p_encoder->p_module )
        module_Unneed( id->p_encoder, id->p_encoder->p_module );
2848 2849 2850 2851 2852 2853 2854 2855
}

static int transcode_spu_process( sout_stream_t *p_stream,
                                  sout_stream_id_t *id,
                                  block_t *in, block_t **out )
{
    sout_stream_sys_t *p_sys = p_stream->p_sys;
    subpicture_t *p_subpic;
2856
    *out = NULL;
2857 2858

    p_subpic = id->p_decoder->pf_decode_sub( id->p_decoder, &in );
2859 2860 2861 2862
    if( !p_subpic )
        return VLC_EGENERIC;

    sout_UpdateStatistic( p_stream->p_sout, SOUT_STATISTIC_DECODED_SUBTITLE, 1 );
2863

2864
    if( p_sys->b_master_sync && p_sys->i_master_drift )
2865
    {
2866 2867
        p_subpic->i_start -= p_sys->i_master_drift;
        if( p_subpic->i_stop ) p_subpic->i_stop -= p_sys->i_master_drift;
2868 2869
    }

2870 2871 2872 2873 2874
    if( p_sys->b_soverlay )
    {
        spu_DisplaySubpicture( p_sys->p_spu, p_subpic );
    }
    else
2875 2876
    {
        block_t *p_block;
2877

2878
        p_block = id->p_encoder->pf_encode_sub( id->p_encoder, p_subpic );
2879 2880 2881 2882 2883 2884
        spu_del_buffer( id->p_decoder, p_subpic );
        if( p_block )
        {
            block_ChainAppend( out, p_block );
            return VLC_SUCCESS;
        }
2885
    }
2886

2887 2888 2889 2890 2891
    return VLC_EGENERIC;
}

static subpicture_t *spu_new_buffer( decoder_t *p_dec )
{
2892 2893
    sout_stream_t *p_stream = (sout_stream_t *)p_dec->p_owner;
    return spu_CreateSubpicture( p_stream->p_sys->p_spu );
2894 2895 2896 2897
}

static void spu_del_buffer( decoder_t *p_dec, subpicture_t *p_subpic )
{
2898 2899
    sout_stream_t *p_stream = (sout_stream_t *)p_dec->p_owner;
    spu_DestroySubpicture( p_stream->p_sys->p_spu, p_subpic );
2900
}
2901 2902 2903 2904 2905 2906 2907

/*
 * OSD menu
 */
static int transcode_osd_new( sout_stream_t *p_stream, sout_stream_id_t *id )
{
    sout_stream_sys_t *p_sys = p_stream->p_sys;
2908

2909 2910
    id->p_decoder->fmt_in.i_cat = SPU_ES;
    id->p_encoder->fmt_out.psz_language = strdup( "osd" );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2911

2912 2913 2914
    if( p_sys->i_osdcodec != 0 || p_sys->psz_osdenc )
    {
        msg_Dbg( p_stream, "creating osdmenu transcoding from fcc=`%4.4s' "
2915
                 "to fcc=`%4.4s'", (char*)&id->p_encoder->fmt_out.i_codec,
2916 2917 2918 2919
                 (char*)&p_sys->i_osdcodec );

        /* Complete destination format */
        id->p_encoder->fmt_out.i_codec = p_sys->i_osdcodec;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2920

2921
        /* Open encoder */
2922 2923 2924
        es_format_Init( &id->p_encoder->fmt_in, id->p_decoder->fmt_in.i_cat,
                        VLC_FOURCC('Y','U','V','A') );
        id->p_encoder->fmt_in.psz_language = strdup( "osd" );
2925 2926 2927 2928

        id->p_encoder->p_cfg = p_sys->p_osd_cfg;

        id->p_encoder->p_module =
2929
            module_Need( id->p_encoder, "encoder", p_sys->psz_osdenc, true );
2930 2931 2932

        if( !id->p_encoder->p_module )
        {
2933
            msg_Err( p_stream, "cannot find encoder (%s)", p_sys->psz_osdenc );
2934 2935
            goto error;
        }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2936

2937 2938
        /* open output stream */
        id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->p_encoder->fmt_out );
2939
        id->b_transcode = true;
2940 2941 2942 2943 2944 2945

        if( !id->id ) goto error;
    }
    else
    {
        msg_Dbg( p_stream, "not transcoding a stream (fcc=`%4.4s')",
2946 2947
                 (char*)&id->p_decoder->fmt_out.i_codec );
        id->id = p_sys->p_out->pf_add( p_sys->p_out, &id->p_decoder->fmt_out );
2948
        id->b_transcode = false;
2949 2950 2951 2952 2953 2954 2955

        if( !id->id ) goto error;
    }

    if( !p_sys->p_spu )
    {
        p_sys->p_spu = spu_Create( p_stream );
2956
        spu_Init( p_sys->p_spu );
2957
    }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2958

2959
    return VLC_SUCCESS;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2960

2961 2962 2963 2964
 error:
    msg_Err( p_stream, "starting osd encoding thread failed" );
    if( id->p_encoder->p_module )
            module_Unneed( id->p_encoder, id->p_encoder->p_module );
2965
    p_sys->b_osd = false;
2966 2967
    return VLC_EGENERIC;
}
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2968

2969
static void transcode_osd_close( sout_stream_t *p_stream, sout_stream_id_t *id)
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2970
{
2971
    sout_stream_sys_t *p_sys = p_stream->p_sys;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2972

2973
    /* Close encoder */
2974
    if( p_sys->b_osd && id )
2975 2976 2977 2978
    {
        if( id->p_encoder->p_module )
            module_Unneed( id->p_encoder, id->p_encoder->p_module );
    }
2979
    p_sys->b_osd = false;
2980 2981 2982 2983 2984 2985 2986 2987
}

static int transcode_osd_process( sout_stream_t *p_stream,
                                  sout_stream_id_t *id,
                                  block_t *in, block_t **out )
{
    sout_stream_sys_t *p_sys = p_stream->p_sys;
    subpicture_t *p_subpic = NULL;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
2988

2989 2990 2991
    /* Check if we have a subpicture to send */
    if( p_sys->p_spu && in->i_dts > 0)
    {
2992
        p_subpic = spu_SortSubpictures( p_sys->p_spu, in->i_dts, false );
2993 2994 2995 2996 2997 2998 2999
    }
    else
    {
        msg_Warn( p_stream, "spu channel not initialized, doing it now" );
        if( !p_sys->p_spu )
        {
            p_sys->p_spu = spu_Create( p_stream );
3000
            spu_Init( p_sys->p_spu );
3001 3002
        }
    }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
3003

3004 3005 3006
    if( p_subpic )
    {
        block_t *p_block = NULL;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
3007

3008 3009 3010 3011 3012
        if( p_sys->b_master_sync && p_sys->i_master_drift )
        {
            p_subpic->i_start -= p_sys->i_master_drift;
            if( p_subpic->i_stop ) p_subpic->i_stop -= p_sys->i_master_drift;
        }
Jean-Paul Saman's avatar
Jean-Paul Saman committed
3013

3014 3015
        p_block = id->p_encoder->pf_encode_sub( id->p_encoder, p_subpic );
        spu_DestroySubpicture( p_sys->p_spu, p_subpic );
3016 3017 3018 3019
        if( p_block )
        {
            p_block->i_dts = p_block->i_pts = in->i_dts;
            block_ChainAppend( out, p_block );
Jean-Paul Saman's avatar
Jean-Paul Saman committed
3020
            return VLC_SUCCESS;
3021 3022 3023 3024
        }
    }
    return VLC_EGENERIC;
}