]> git.sesse.net Git - vlc/blob - modules/codec/schroedinger.c
upnp: change item b_net and i_type
[vlc] / modules / codec / schroedinger.c
1 /*****************************************************************************
2  * schroedinger.c: Dirac decoder module making use of libschroedinger.
3  *          (http://www.bbc.co.uk/rd/projects/dirac/index.shtml)
4  *          (http://diracvideo.org)
5  *****************************************************************************
6  * Copyright (C) 2008-2011 VLC authors and VideoLAN
7  *
8  * Authors: Jonathan Rosser <jonathan.rosser@gmail.com>
9  *          David Flynn <davidf at rd dot bbc.co.uk>
10  *          Anuradha Suraparaju <asuraparaju at gmail dot com>
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU Lesser General Public License as published by
14  * the Free Software Foundation; either version 2.1 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public License
23  * along with this program; if not, write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <assert.h>
36
37 #include <vlc_common.h>
38 #include <vlc_plugin.h>
39 #include <vlc_codec.h>
40
41 #include <schroedinger/schro.h>
42
43 /*****************************************************************************
44  * Module descriptor
45  *****************************************************************************/
46 static int        OpenDecoder  ( vlc_object_t * );
47 static void       CloseDecoder ( vlc_object_t * );
48 static int        OpenEncoder  ( vlc_object_t * );
49 static void       CloseEncoder ( vlc_object_t * );
50
51 #define ENC_CFG_PREFIX "sout-schro-"
52
53 #define ENC_CHROMAFMT "chroma-fmt"
54 #define ENC_CHROMAFMT_TEXT N_("Chroma format")
55 #define ENC_CHROMAFMT_LONGTEXT N_("Picking chroma format will force a " \
56                                   "conversion of the video into that format")
57 static const char *const enc_chromafmt_list[] =
58   { "420", "422", "444" };
59 static const char *const enc_chromafmt_list_text[] =
60   { N_("4:2:0"), N_("4:2:2"), N_("4:4:4") };
61
62 #define ENC_RATE_CONTROL "rate-control"
63 #define ENC_RATE_CONTROL_TEXT N_("Rate control method")
64 #define ENC_RATE_CONTROL_LONGTEXT N_("Method used to encode the video sequence")
65
66 static const char *enc_rate_control_list[] = {
67   "constant_noise_threshold",
68   "constant_bitrate",
69   "low_delay",
70   "lossless",
71   "constant_lambda",
72   "constant_error",
73   "constant_quality"
74 };
75
76 static const char *enc_rate_control_list_text[] = {
77   N_("Constant noise threshold mode"),
78   N_("Constant bitrate mode (CBR)"),
79   N_("Low Delay mode"),
80   N_("Lossless mode"),
81   N_("Constant lambda mode"),
82   N_("Constant error mode"),
83   N_("Constant quality mode")
84 };
85
86 #define ENC_GOP_STRUCTURE "gop-structure"
87 #define ENC_GOP_STRUCTURE_TEXT N_("GOP structure")
88 #define ENC_GOP_STRUCTURE_LONGTEXT N_("GOP structure used to encode the video sequence")
89
90 static const char *enc_gop_structure_list[] = {
91   "adaptive",
92   "intra_only",
93   "backref",
94   "chained_backref",
95   "biref",
96   "chained_biref"
97 };
98
99 static const char *enc_gop_structure_list_text[] = {
100   N_("No fixed gop structure. A picture can be intra or inter and refer to previous or future pictures."),
101   N_("I-frame only sequence"),
102   N_("Inter pictures refere to previous pictures only"),
103   N_("Inter pictures refere to previous pictures only"),
104   N_("Inter pictures can refer to previous or future pictures"),
105   N_("Inter pictures can refer to previous or future pictures")
106 };
107
108 #define ENC_QUALITY "quality"
109 #define ENC_QUALITY_TEXT N_("Constant quality factor")
110 #define ENC_QUALITY_LONGTEXT N_("Quality factor to use in constant quality mode")
111
112 #define ENC_NOISE_THRESHOLD "noise-threshold"
113 #define ENC_NOISE_THRESHOLD_TEXT N_("Noise Threshold")
114 #define ENC_NOISE_THRESHOLD_LONGTEXT N_("Noise threshold to use in constant noise threshold mode")
115
116 #define ENC_BITRATE "bitrate"
117 #define ENC_BITRATE_TEXT N_("CBR bitrate (kbps)")
118 #define ENC_BITRATE_LONGTEXT N_("Target bitrate in kbps when encoding in constant bitrate mode")
119
120 #define ENC_MAX_BITRATE "max-bitrate"
121 #define ENC_MAX_BITRATE_TEXT N_("Maximum bitrate (kbps)")
122 #define ENC_MAX_BITRATE_LONGTEXT N_("Maximum bitrate in kbps when encoding in constant bitrate mode")
123
124 #define ENC_MIN_BITRATE "min-bitrate"
125 #define ENC_MIN_BITRATE_TEXT N_("Minimum bitrate (kbps)")
126 #define ENC_MIN_BITRATE_LONGTEXT N_("Minimum bitrate in kbps when encoding in constant bitrate mode")
127
128 #define ENC_AU_DISTANCE "gop-length"
129 #define ENC_AU_DISTANCE_TEXT N_("GOP length")
130 #define ENC_AU_DISTANCE_LONGTEXT N_("Number of pictures between successive sequence headers i.e. length of the group of pictures")
131
132
133 #define ENC_PREFILTER "filtering"
134 #define ENC_PREFILTER_TEXT N_("Prefilter")
135 #define ENC_PREFILTER_LONGTEXT N_("Enable adaptive prefiltering")
136
137 static const char *enc_filtering_list[] = {
138   "none",
139   "center_weighted_median",
140   "gaussian",
141   "add_noise",
142   "adaptive_gaussian",
143   "lowpass"
144 };
145
146 static const char *enc_filtering_list_text[] = {
147   N_("No pre-filtering"),
148   N_("Centre Weighted Median"),
149   N_("Gaussian Low Pass Filter"),
150   N_("Add Noise"),
151   N_("Gaussian Adaptive Low Pass Filter"),
152   N_("Low Pass Filter"),
153 };
154
155 #define ENC_PREFILTER_STRENGTH "filter-value"
156 #define ENC_PREFILTER_STRENGTH_TEXT N_("Amount of prefiltering")
157 #define ENC_PREFILTER_STRENGTH_LONGTEXT N_("Higher value implies more prefiltering")
158
159 #define ENC_CODINGMODE "coding-mode"
160 #define ENC_CODINGMODE_TEXT N_("Picture coding mode")
161 #define ENC_CODINGMODE_LONGTEXT N_("Field coding is where interlaced fields are coded" \
162                                    " separately as opposed to a pseudo-progressive frame")
163 static const char *const enc_codingmode_list[] =
164   { "auto", "progressive", "field" };
165 static const char *const enc_codingmode_list_text[] =
166   { N_("auto - let encoder decide based upon input (Best)"),
167     N_("force coding frame as single picture"),
168     N_("force coding frame as separate interlaced fields"),
169   };
170
171 /* advanced option only */
172 #define ENC_MCBLK_SIZE "motion-block-size"
173 #define ENC_MCBLK_SIZE_TEXT N_("Size of motion compensation blocks")
174
175 static const char *enc_block_size_list[] = {
176   "automatic",
177   "small",
178   "medium",
179   "large"
180 };
181 static const char *const enc_block_size_list_text[] =
182   { N_("automatic - let encoder decide based upon input (Best)"),
183     N_("small - use small motion compensation blocks"),
184     N_("medium - use medium motion compensation blocks"),
185     N_("large - use large motion compensation blocks"),
186   };
187
188 /* advanced option only */
189 #define ENC_MCBLK_OVERLAP "motion-block-overlap"
190 #define ENC_MCBLK_OVERLAP_TEXT N_("Overlap of motion compensation blocks")
191
192 static const char *enc_block_overlap_list[] = {
193   "automatic",
194   "none",
195   "partial",
196   "full"
197 };
198 static const char *const enc_block_overlap_list_text[] =
199   { N_("automatic - let encoder decide based upon input (Best)"),
200     N_("none - Motion compensation blocks do not overlap"),
201     N_("partial - Motion compensation blocks only partially overlap"),
202     N_("full - Motion compensation blocks fully overlap"),
203   };
204
205
206 #define ENC_MVPREC "mv-precision"
207 #define ENC_MVPREC_TEXT N_("Motion Vector precision")
208 #define ENC_MVPREC_LONGTEXT N_("Motion Vector precision in pels")
209 static const char *const enc_mvprec_list[] =
210   { "1", "1/2", "1/4", "1/8" };
211
212 /* advanced option only */
213 #define ENC_ME_COMBINED "me-combined"
214 #define ENC_ME_COMBINED_TEXT N_("Three component motion estimation")
215 #define ENC_ME_COMBINED_LONGTEXT N_("Use chroma as part of the motion estimation process")
216
217 #define ENC_DWTINTRA "intra-wavelet"
218 #define ENC_DWTINTRA_TEXT N_("Intra picture DWT filter")
219
220 #define ENC_DWTINTER "inter-wavelet"
221 #define ENC_DWTINTER_TEXT N_("Inter picture DWT filter")
222
223 static const char *enc_wavelet_list[] = {
224   "desl_dubuc_9_7",
225   "le_gall_5_3",
226   "desl_dubuc_13_7",
227   "haar_0",
228   "haar_1",
229   "fidelity",
230   "daub_9_7"
231 };
232
233 static const char *enc_wavelet_list_text[] = {
234   "Deslauriers-Dubuc (9,7)",
235   "LeGall (5,3)",
236   "Deslauriers-Dubuc (13,7)",
237   "Haar with no shift",
238   "Haar with single shift per level",
239   "Fidelity filter",
240   "Daubechies (9,7) integer approximation"
241 };
242
243 #define ENC_DWTDEPTH "transform-depth"
244 #define ENC_DWTDEPTH_TEXT N_("Number of DWT iterations")
245 #define ENC_DWTDEPTH_LONGTEXT N_("Also known as DWT levels")
246
247
248 /* advanced option only */
249 #define ENC_MULTIQUANT "enable-multiquant"
250 #define ENC_MULTIQUANT_TEXT N_("Enable multiple quantizers")
251 #define ENC_MULTIQUANT_LONGTEXT N_("Enable multiple quantizers per subband (one per codeblock)")
252
253 /* advanced option only */
254 #define ENC_NOAC "enable-noarith"
255 #define ENC_NOAC_TEXT N_("Disable arithmetic coding")
256 #define ENC_NOAC_LONGTEXT N_("Use variable length codes instead, useful for very high bitrates")
257
258 /* visual modelling */
259 /* advanced option only */
260 #define ENC_PWT "perceptual-weighting"
261 #define ENC_PWT_TEXT N_("perceptual weighting method")
262
263 static const char *enc_perceptual_weighting_list[] = {
264   "none",
265   "ccir959",
266   "moo",
267   "manos_sakrison"
268 };
269
270 /* advanced option only */
271 #define ENC_PDIST "perceptual-distance"
272 #define ENC_PDIST_TEXT N_("perceptual distance")
273 #define ENC_PDIST_LONGTEXT N_("perceptual distance to calculate perceptual weight")
274
275 /* advanced option only */
276 #define ENC_HSLICES "horiz-slices"
277 #define ENC_HSLICES_TEXT N_("Horizontal slices per frame")
278 #define ENC_HSLICES_LONGTEXT N_("Number of horizontal slices per frame in low delay mode")
279
280 /* advanced option only */
281 #define ENC_VSLICES "vert-slices"
282 #define ENC_VSLICES_TEXT N_("Vertical slices per frame")
283 #define ENC_VSLICES_LONGTEXT N_("Number of vertical slices per frame in low delay mode")
284
285 /* advanced option only */
286 #define ENC_SCBLK_SIZE "codeblock-size"
287 #define ENC_SCBLK_SIZE_TEXT N_("Size of code blocks in each subband")
288
289 static const char *enc_codeblock_size_list[] = {
290   "automatic",
291   "small",
292   "medium",
293   "large",
294   "full"
295 };
296 static const char *const enc_codeblock_size_list_text[] =
297   { N_("automatic - let encoder decide based upon input (Best)"),
298     N_("small - use small code blocks"),
299     N_("medium - use medium sized code blocks"),
300     N_("large - use large code blocks"),
301     N_("full - One code block per subband"),
302   };
303
304 /* advanced option only */
305 #define ENC_ME_HIERARCHICAL "enable-hierarchical-me"
306 #define ENC_ME_HIERARCHICAL_TEXT N_("Enable hierarchical Motion Estimation")
307
308 /* advanced option only */
309 #define ENC_ME_DOWNSAMPLE_LEVELS "downsample-levels"
310 #define ENC_ME_DOWNSAMPLE_LEVELS_TEXT N_("Number of levels of downsampling")
311 #define ENC_ME_DOWNSAMPLE_LEVELS_LONGTEXT N_("Number of levels of downsampling in hierarchical motion estimation mode")
312
313 /* advanced option only */
314 #define ENC_ME_GLOBAL_MOTION "enable-global-me"
315 #define ENC_ME_GLOBAL_MOTION_TEXT N_("Enable Global Motion Estimation")
316
317 /* advanced option only */
318 #define ENC_ME_PHASECORR "enable-phasecorr-me"
319 #define ENC_ME_PHASECORR_TEXT N_("Enable Phase Correlation Estimation")
320
321 /* advanced option only */
322 #define ENC_SCD "enable-scd"
323 #define ENC_SCD_TEXT N_("Enable Scene Change Detection")
324
325 /* advanced option only */
326 #define ENC_FORCE_PROFILE "force-profile"
327 #define ENC_FORCE_PROFILE_TEXT N_("Force Profile")
328
329 static const char *enc_profile_list[] = {
330   "auto",
331   "vc2_low_delay",
332   "vc2_simple",
333   "vc2_main",
334   "main"
335 };
336
337 static const char *const enc_profile_list_text[] =
338   { N_("automatic - let encoder decide based upon input (Best)"),
339     N_("VC2 Low Delay Profile"),
340     N_("VC2 Simple Profile"),
341     N_("VC2 Main Profile"),
342     N_("Main Profile"),
343   };
344
345 static const char *const ppsz_enc_options[] = {
346     ENC_RATE_CONTROL, ENC_GOP_STRUCTURE, ENC_QUALITY, ENC_NOISE_THRESHOLD, ENC_BITRATE,
347     ENC_MIN_BITRATE, ENC_MAX_BITRATE, ENC_AU_DISTANCE, ENC_CHROMAFMT,
348     ENC_PREFILTER, ENC_PREFILTER_STRENGTH, ENC_CODINGMODE, ENC_MCBLK_SIZE,
349     ENC_MCBLK_OVERLAP, ENC_MVPREC, ENC_ME_COMBINED, ENC_DWTINTRA, ENC_DWTINTER,
350     ENC_DWTDEPTH, ENC_MULTIQUANT, ENC_NOAC, ENC_PWT, ENC_PDIST, ENC_HSLICES,
351     ENC_VSLICES, ENC_SCBLK_SIZE, ENC_ME_HIERARCHICAL, ENC_ME_DOWNSAMPLE_LEVELS,
352     ENC_ME_GLOBAL_MOTION, ENC_ME_PHASECORR, ENC_SCD, ENC_FORCE_PROFILE,
353     NULL
354 };
355
356
357 /* Module declaration */
358
359 vlc_module_begin ()
360     set_category( CAT_INPUT )
361     set_subcategory( SUBCAT_INPUT_VCODEC )
362     set_shortname( "Schroedinger" )
363     set_description( N_("Dirac video decoder using libschroedinger") )
364     set_capability( "decoder", 200 )
365     set_callbacks( OpenDecoder, CloseDecoder )
366     add_shortcut( "schroedinger" )
367
368     /* encoder */
369     add_submodule()
370     set_section( N_("Encoding") , NULL )
371     set_description( N_("Dirac video encoder using libschroedinger") )
372     set_capability( "encoder", 110 )
373     set_callbacks( OpenEncoder, CloseEncoder )
374     add_shortcut( "schroedinger", "schro" )
375
376     add_string( ENC_CFG_PREFIX ENC_RATE_CONTROL, NULL,
377                  ENC_RATE_CONTROL_TEXT, ENC_RATE_CONTROL_LONGTEXT, false )
378     change_string_list( enc_rate_control_list, enc_rate_control_list_text )
379
380     add_float( ENC_CFG_PREFIX ENC_QUALITY, -1.,
381                ENC_QUALITY_TEXT, ENC_QUALITY_LONGTEXT, false )
382     change_float_range(-1., 10.);
383
384     add_float( ENC_CFG_PREFIX ENC_NOISE_THRESHOLD, -1.,
385                ENC_NOISE_THRESHOLD_TEXT, ENC_NOISE_THRESHOLD_LONGTEXT, false )
386     change_float_range(-1., 100.);
387
388     add_integer( ENC_CFG_PREFIX ENC_BITRATE, -1,
389                  ENC_BITRATE_TEXT, ENC_BITRATE_LONGTEXT, false )
390     change_integer_range(-1, INT_MAX);
391
392     add_integer( ENC_CFG_PREFIX ENC_MAX_BITRATE, -1,
393                  ENC_MAX_BITRATE_TEXT, ENC_MAX_BITRATE_LONGTEXT, false )
394     change_integer_range(-1, INT_MAX);
395
396     add_integer( ENC_CFG_PREFIX ENC_MIN_BITRATE, -1,
397                  ENC_MIN_BITRATE_TEXT, ENC_MIN_BITRATE_LONGTEXT, false )
398     change_integer_range(-1, INT_MAX);
399
400     add_string( ENC_CFG_PREFIX ENC_GOP_STRUCTURE, NULL,
401                  ENC_GOP_STRUCTURE_TEXT, ENC_GOP_STRUCTURE_LONGTEXT, false )
402     change_string_list( enc_gop_structure_list, enc_gop_structure_list_text )
403
404     add_integer( ENC_CFG_PREFIX ENC_AU_DISTANCE, -1,
405                  ENC_AU_DISTANCE_TEXT, ENC_AU_DISTANCE_LONGTEXT, false )
406     change_integer_range(-1, INT_MAX);
407
408     add_string( ENC_CFG_PREFIX ENC_CHROMAFMT, "420",
409                 ENC_CHROMAFMT_TEXT, ENC_CHROMAFMT_LONGTEXT, false )
410     change_string_list( enc_chromafmt_list, enc_chromafmt_list_text )
411
412     add_string( ENC_CFG_PREFIX ENC_CODINGMODE, "auto",
413                 ENC_CODINGMODE_TEXT, ENC_CODINGMODE_LONGTEXT, false )
414     change_string_list( enc_codingmode_list, enc_codingmode_list_text )
415
416     add_string( ENC_CFG_PREFIX ENC_MVPREC, NULL,
417                 ENC_MVPREC_TEXT, ENC_MVPREC_LONGTEXT, false )
418     change_string_list( enc_mvprec_list, enc_mvprec_list )
419
420     /* advanced option only */
421     add_string( ENC_CFG_PREFIX ENC_MCBLK_SIZE, NULL,
422                 ENC_MCBLK_SIZE_TEXT, ENC_MCBLK_SIZE_TEXT, true )
423     change_string_list( enc_block_size_list, enc_block_size_list_text )
424
425
426     /* advanced option only */
427     add_string( ENC_CFG_PREFIX ENC_MCBLK_OVERLAP, NULL,
428                 ENC_MCBLK_OVERLAP_TEXT, ENC_MCBLK_OVERLAP_TEXT, true )
429     change_string_list( enc_block_overlap_list, enc_block_overlap_list_text )
430
431     /* advanced option only */
432     add_integer( ENC_CFG_PREFIX ENC_ME_COMBINED, -1,
433               ENC_ME_COMBINED_TEXT, ENC_ME_COMBINED_LONGTEXT, true )
434     change_integer_range(-1, 1 );
435
436     /* advanced option only */
437     add_integer( ENC_CFG_PREFIX ENC_ME_HIERARCHICAL, -1,
438                  ENC_ME_HIERARCHICAL_TEXT, ENC_ME_HIERARCHICAL_TEXT, true )
439     change_integer_range(-1, 1 );
440
441     /* advanced option only */
442     add_integer( ENC_CFG_PREFIX ENC_ME_DOWNSAMPLE_LEVELS, -1,
443                  ENC_ME_DOWNSAMPLE_LEVELS_TEXT, ENC_ME_DOWNSAMPLE_LEVELS_LONGTEXT, true )
444     change_integer_range(-1, 8 );
445
446     /* advanced option only */
447     add_integer( ENC_CFG_PREFIX ENC_ME_GLOBAL_MOTION, -1,
448                  ENC_ME_GLOBAL_MOTION_TEXT, ENC_ME_GLOBAL_MOTION_TEXT, true )
449     change_integer_range(-1, 1 );
450
451     /* advanced option only */
452     add_integer( ENC_CFG_PREFIX ENC_ME_PHASECORR, -1,
453                  ENC_ME_PHASECORR_TEXT, ENC_ME_PHASECORR_TEXT, true )
454     change_integer_range(-1, 1 );
455
456     add_string( ENC_CFG_PREFIX ENC_DWTINTRA, NULL,
457                 ENC_DWTINTRA_TEXT, ENC_DWTINTRA_TEXT, false )
458     change_string_list( enc_wavelet_list, enc_wavelet_list_text )
459
460     add_string( ENC_CFG_PREFIX ENC_DWTINTER, NULL,
461                 ENC_DWTINTER_TEXT, ENC_DWTINTER_TEXT, false )
462     change_string_list( enc_wavelet_list, enc_wavelet_list_text )
463
464     add_integer( ENC_CFG_PREFIX ENC_DWTDEPTH, -1,
465                  ENC_DWTDEPTH_TEXT, ENC_DWTDEPTH_LONGTEXT, false )
466     change_integer_range(-1, SCHRO_LIMIT_ENCODER_TRANSFORM_DEPTH );
467
468     /* advanced option only */
469     add_integer( ENC_CFG_PREFIX ENC_MULTIQUANT, -1,
470                  ENC_MULTIQUANT_TEXT, ENC_MULTIQUANT_LONGTEXT, true )
471     change_integer_range(-1, 1 );
472
473     /* advanced option only */
474     add_string( ENC_CFG_PREFIX ENC_SCBLK_SIZE, NULL,
475                 ENC_SCBLK_SIZE_TEXT, ENC_SCBLK_SIZE_TEXT, true )
476     change_string_list( enc_codeblock_size_list, enc_codeblock_size_list_text )
477
478     add_string( ENC_CFG_PREFIX ENC_PREFILTER, NULL,
479                 ENC_PREFILTER_TEXT, ENC_PREFILTER_LONGTEXT, false )
480     change_string_list( enc_filtering_list, enc_filtering_list_text )
481
482     add_float( ENC_CFG_PREFIX ENC_PREFILTER_STRENGTH, -1.,
483                  ENC_PREFILTER_STRENGTH_TEXT, ENC_PREFILTER_STRENGTH_LONGTEXT, false )
484     change_float_range(-1., 100.0);
485
486     /* advanced option only */
487     add_integer( ENC_CFG_PREFIX ENC_SCD, -1,
488                  ENC_SCD_TEXT, ENC_SCD_TEXT, true )
489     change_integer_range(-1, 1 );
490
491     /* advanced option only */
492     add_string( ENC_CFG_PREFIX ENC_PWT, NULL,
493                 ENC_PWT_TEXT, ENC_PWT_TEXT, true )
494     change_string_list( enc_perceptual_weighting_list, enc_perceptual_weighting_list )
495
496     /* advanced option only */
497     add_float( ENC_CFG_PREFIX ENC_PDIST, -1,
498                ENC_PDIST_TEXT, ENC_PDIST_LONGTEXT, true )
499     change_float_range(-1., 100.);
500
501     /* advanced option only */
502     add_integer( ENC_CFG_PREFIX ENC_NOAC, -1,
503               ENC_NOAC_TEXT, ENC_NOAC_LONGTEXT, true )
504     change_integer_range(-1, 1 );
505
506     /* advanced option only */
507     add_integer( ENC_CFG_PREFIX ENC_HSLICES, -1,
508                  ENC_HSLICES_TEXT, ENC_HSLICES_LONGTEXT, true )
509     change_integer_range(-1, INT_MAX );
510
511     /* advanced option only */
512     add_integer( ENC_CFG_PREFIX ENC_VSLICES, -1,
513                  ENC_VSLICES_TEXT, ENC_VSLICES_LONGTEXT, true )
514     change_integer_range(-1, INT_MAX );
515
516     /* advanced option only */
517     add_string( ENC_CFG_PREFIX ENC_FORCE_PROFILE, NULL,
518                 ENC_FORCE_PROFILE_TEXT, ENC_FORCE_PROFILE_TEXT, true )
519     change_string_list( enc_profile_list, enc_profile_list_text )
520
521 vlc_module_end ()
522
523
524 /*****************************************************************************
525  * Local prototypes
526  *****************************************************************************/
527 static picture_t *DecodeBlock  ( decoder_t *p_dec, block_t **pp_block );
528
529 struct picture_free_t
530 {
531    picture_t *p_pic;
532    decoder_t *p_dec;
533 };
534
535 /*****************************************************************************
536  * decoder_sys_t : Schroedinger decoder descriptor
537  *****************************************************************************/
538 struct decoder_sys_t
539 {
540     /*
541      * Dirac properties
542      */
543     mtime_t i_lastpts;
544     mtime_t i_frame_pts_delta;
545     SchroDecoder *p_schro;
546     SchroVideoFormat *p_format;
547 };
548
549 /*****************************************************************************
550  * OpenDecoder: probe the decoder and return score
551  *****************************************************************************/
552 static int OpenDecoder( vlc_object_t *p_this )
553 {
554     decoder_t *p_dec = (decoder_t*)p_this;
555     decoder_sys_t *p_sys;
556     SchroDecoder *p_schro;
557
558     if( p_dec->fmt_in.i_codec != VLC_CODEC_DIRAC )
559     {
560         return VLC_EGENERIC;
561     }
562
563     /* Allocate the memory needed to store the decoder's structure */
564     p_sys = malloc(sizeof(decoder_sys_t));
565     if( p_sys == NULL )
566         return VLC_ENOMEM;
567
568     /* Initialise the schroedinger (and hence liboil libraries */
569     /* This does no allocation and is safe to call */
570     schro_init();
571
572     /* Initialise the schroedinger decoder */
573     if( !(p_schro = schro_decoder_new()) )
574     {
575         free( p_sys );
576         return VLC_EGENERIC;
577     }
578
579     p_dec->p_sys = p_sys;
580     p_sys->p_schro = p_schro;
581     p_sys->p_format = NULL;
582     p_sys->i_lastpts = VLC_TS_INVALID;
583     p_sys->i_frame_pts_delta = 0;
584
585     /* Set output properties */
586     p_dec->fmt_out.i_cat = VIDEO_ES;
587     p_dec->fmt_out.i_codec = VLC_CODEC_I420;
588
589     /* Set callbacks */
590     p_dec->pf_decode_video = DecodeBlock;
591
592     return VLC_SUCCESS;
593 }
594
595 /*****************************************************************************
596  * SetPictureFormat: Set the decoded picture params to the ones from the stream
597  *****************************************************************************/
598 static void SetVideoFormat( decoder_t *p_dec )
599 {
600     decoder_sys_t *p_sys = p_dec->p_sys;
601
602     p_sys->p_format = schro_decoder_get_video_format(p_sys->p_schro);
603     if( p_sys->p_format == NULL ) return;
604
605     p_sys->i_frame_pts_delta = CLOCK_FREQ
606                             * p_sys->p_format->frame_rate_denominator
607                             / p_sys->p_format->frame_rate_numerator;
608
609     switch( p_sys->p_format->chroma_format )
610     {
611     case SCHRO_CHROMA_420: p_dec->fmt_out.i_codec = VLC_CODEC_I420; break;
612     case SCHRO_CHROMA_422: p_dec->fmt_out.i_codec = VLC_CODEC_I422; break;
613     case SCHRO_CHROMA_444: p_dec->fmt_out.i_codec = VLC_CODEC_I444; break;
614     default:
615         p_dec->fmt_out.i_codec = 0;
616         break;
617     }
618
619     p_dec->fmt_out.video.i_visible_width = p_sys->p_format->clean_width;
620     p_dec->fmt_out.video.i_x_offset = p_sys->p_format->left_offset;
621     p_dec->fmt_out.video.i_width = p_sys->p_format->width;
622
623     p_dec->fmt_out.video.i_visible_height = p_sys->p_format->clean_height;
624     p_dec->fmt_out.video.i_y_offset = p_sys->p_format->top_offset;
625     p_dec->fmt_out.video.i_height = p_sys->p_format->height;
626
627     /* aspect_ratio_[numerator|denominator] describes the pixel aspect ratio */
628     p_dec->fmt_out.video.i_sar_num = p_sys->p_format->aspect_ratio_numerator;
629     p_dec->fmt_out.video.i_sar_den = p_sys->p_format->aspect_ratio_denominator;
630
631     p_dec->fmt_out.video.i_frame_rate =
632         p_sys->p_format->frame_rate_numerator;
633     p_dec->fmt_out.video.i_frame_rate_base =
634         p_sys->p_format->frame_rate_denominator;
635 }
636
637 /*****************************************************************************
638  * SchroFrameFree: schro_frame callback to release the associated picture_t
639  * When schro_decoder_reset() is called there will be pictures in the
640  * decoding pipeline that need to be released rather than displayed.
641  *****************************************************************************/
642 static void SchroFrameFree( SchroFrame *frame, void *priv)
643 {
644     struct picture_free_t *p_free = priv;
645
646     if( !p_free )
647         return;
648
649     picture_Release( p_free->p_pic );
650     free(p_free);
651     (void)frame;
652 }
653
654 /*****************************************************************************
655  * CreateSchroFrameFromPic: wrap a picture_t in a SchroFrame
656  *****************************************************************************/
657 static SchroFrame *CreateSchroFrameFromPic( decoder_t *p_dec )
658 {
659     decoder_sys_t *p_sys = p_dec->p_sys;
660     SchroFrame *p_schroframe = schro_frame_new();
661     picture_t *p_pic = NULL;
662     struct picture_free_t *p_free;
663
664     if( !p_schroframe )
665         return NULL;
666
667     p_pic = decoder_NewPicture( p_dec );
668
669     if( !p_pic )
670         return NULL;
671
672     p_schroframe->format = SCHRO_FRAME_FORMAT_U8_420;
673     if( p_sys->p_format->chroma_format == SCHRO_CHROMA_422 )
674     {
675         p_schroframe->format = SCHRO_FRAME_FORMAT_U8_422;
676     }
677     else if( p_sys->p_format->chroma_format == SCHRO_CHROMA_444 )
678     {
679         p_schroframe->format = SCHRO_FRAME_FORMAT_U8_444;
680     }
681
682     p_schroframe->width = p_sys->p_format->width;
683     p_schroframe->height = p_sys->p_format->height;
684
685     p_free = malloc( sizeof( *p_free ) );
686     p_free->p_pic = p_pic;
687     p_free->p_dec = p_dec;
688     schro_frame_set_free_callback( p_schroframe, SchroFrameFree, p_free );
689
690     for( int i=0; i<3; i++ )
691     {
692         p_schroframe->components[i].width = p_pic->p[i].i_visible_pitch;
693         p_schroframe->components[i].stride = p_pic->p[i].i_pitch;
694         p_schroframe->components[i].height = p_pic->p[i].i_visible_lines;
695         p_schroframe->components[i].length =
696             p_pic->p[i].i_pitch * p_pic->p[i].i_lines;
697         p_schroframe->components[i].data = p_pic->p[i].p_pixels;
698
699         if(i!=0)
700         {
701             p_schroframe->components[i].v_shift =
702                 SCHRO_FRAME_FORMAT_V_SHIFT( p_schroframe->format );
703             p_schroframe->components[i].h_shift =
704                 SCHRO_FRAME_FORMAT_H_SHIFT( p_schroframe->format );
705         }
706     }
707
708     p_pic->b_progressive = !p_sys->p_format->interlaced;
709     p_pic->b_top_field_first = p_sys->p_format->top_field_first;
710     p_pic->i_nb_fields = 2;
711
712     return p_schroframe;
713 }
714
715 /*****************************************************************************
716  * SchroBufferFree: schro_buffer callback to release the associated block_t
717  *****************************************************************************/
718 static void SchroBufferFree( SchroBuffer *buf, void *priv )
719 {
720     block_t *p_block = priv;
721
722     if( !p_block )
723         return;
724
725     block_Release( p_block );
726     (void)buf;
727 }
728
729 /*****************************************************************************
730  * CloseDecoder: decoder destruction
731  *****************************************************************************/
732 static void CloseDecoder( vlc_object_t *p_this )
733 {
734     decoder_t *p_dec = (decoder_t *)p_this;
735     decoder_sys_t *p_sys = p_dec->p_sys;
736
737     schro_decoder_free( p_sys->p_schro );
738     free( p_sys );
739 }
740
741 /****************************************************************************
742  * DecodeBlock: the whole thing
743  ****************************************************************************
744  * Blocks need not be Dirac dataunit aligned.
745  * If a block has a PTS signaled, it applies to the first picture at or after p_block
746  *
747  * If this function returns a picture (!NULL), it is called again and the
748  * same block is resubmitted.  To avoid this, set *pp_block to NULL;
749  * If this function returns NULL, the *pp_block is lost (and leaked).
750  * This function must free all blocks when finished with them.
751  ****************************************************************************/
752 static picture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
753 {
754     decoder_sys_t *p_sys = p_dec->p_sys;
755
756     if( !pp_block ) return NULL;
757
758     if ( *pp_block ) {
759         block_t *p_block = *pp_block;
760
761         /* reset the decoder when seeking as the decode in progress is invalid */
762         /* discard the block as it is just a null magic block */
763         if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY ) {
764             schro_decoder_reset( p_sys->p_schro );
765
766             p_sys->i_lastpts = VLC_TS_INVALID;
767             block_Release( p_block );
768             *pp_block = NULL;
769             return NULL;
770         }
771
772         SchroBuffer *p_schrobuffer;
773         p_schrobuffer = schro_buffer_new_with_data( p_block->p_buffer, p_block->i_buffer );
774         p_schrobuffer->free = SchroBufferFree;
775         p_schrobuffer->priv = p_block;
776         if( p_block->i_pts > VLC_TS_INVALID ) {
777             mtime_t *p_pts = malloc( sizeof(*p_pts) );
778             if( p_pts ) {
779                 *p_pts = p_block->i_pts;
780                 /* if this call fails, p_pts is freed automatically */
781                 p_schrobuffer->tag = schro_tag_new( p_pts, free );
782             }
783         }
784
785         /* this stops the same block being fed back into this function if
786          * we were on the next iteration of this loop to output a picture */
787         *pp_block = NULL;
788         schro_decoder_autoparse_push( p_sys->p_schro, p_schrobuffer );
789         /* DO NOT refer to p_block after this point, it may have been freed */
790     }
791
792     while( 1 )
793     {
794         SchroFrame *p_schroframe;
795         picture_t *p_pic;
796         int state = schro_decoder_autoparse_wait( p_sys->p_schro );
797
798         switch( state )
799         {
800         case SCHRO_DECODER_FIRST_ACCESS_UNIT:
801             SetVideoFormat( p_dec );
802             break;
803
804         case SCHRO_DECODER_NEED_BITS:
805             return NULL;
806
807         case SCHRO_DECODER_NEED_FRAME:
808             p_schroframe = CreateSchroFrameFromPic( p_dec );
809
810             if( !p_schroframe )
811             {
812                 msg_Err( p_dec, "Could not allocate picture for decoder");
813                 return NULL;
814             }
815
816             schro_decoder_add_output_picture( p_sys->p_schro, p_schroframe);
817             break;
818
819         case SCHRO_DECODER_OK: {
820             SchroTag *p_tag = schro_decoder_get_picture_tag( p_sys->p_schro );
821             p_schroframe = schro_decoder_pull( p_sys->p_schro );
822             if( !p_schroframe || !p_schroframe->priv )
823             {
824                 /* frame can't be one that was allocated by us
825                  *   -- no private data: discard */
826                 if( p_tag ) schro_tag_free( p_tag );
827                 if( p_schroframe ) schro_frame_unref( p_schroframe );
828                 break;
829             }
830             p_pic = ((struct picture_free_t*) p_schroframe->priv)->p_pic;
831             p_schroframe->priv = NULL;
832
833             if( p_tag )
834             {
835                 /* free is handled by schro_frame_unref */
836                 p_pic->date = *(mtime_t*) p_tag->value;
837                 schro_tag_free( p_tag );
838             }
839             else if( p_sys->i_lastpts > VLC_TS_INVALID )
840             {
841                 /* NB, this shouldn't happen since the packetizer does a
842                  * very thorough job of inventing timestamps.  The
843                  * following is just a very rough fall back incase packetizer
844                  * is missing. */
845                 /* maybe it would be better to set p_pic->b_force ? */
846                 p_pic->date = p_sys->i_lastpts + p_sys->i_frame_pts_delta;
847             }
848             p_sys->i_lastpts = p_pic->date;
849
850             schro_frame_unref( p_schroframe );
851             return p_pic;
852         }
853         case SCHRO_DECODER_EOS:
854             /* NB, the new api will not emit _EOS, it handles the reset internally */
855             break;
856
857         case SCHRO_DECODER_ERROR:
858             msg_Err( p_dec, "SCHRO_DECODER_ERROR");
859             return NULL;
860         }
861     }
862 }
863
864 /*****************************************************************************
865  * Local prototypes
866  *****************************************************************************/
867 static block_t *Encode( encoder_t *p_enc, picture_t *p_pict );
868
869
870 /*****************************************************************************
871  * picture_pts_t : store pts alongside picture number, not carried through
872  * encoder
873  *****************************************************************************/
874 struct picture_pts_t
875 {
876    mtime_t i_pts;    /* associated pts */
877    uint32_t u_pnum;  /* dirac picture number */
878    bool b_empty;     /* entry is invalid */
879 };
880
881 /*****************************************************************************
882  * encoder_sys_t : Schroedinger encoder descriptor
883  *****************************************************************************/
884 #define SCHRO_PTS_TLB_SIZE 256
885 struct encoder_sys_t
886 {
887     /*
888      * Schro properties
889      */
890     SchroEncoder *p_schro;
891     SchroVideoFormat *p_format;
892     int started;
893     bool b_auto_field_coding;
894
895     uint32_t i_input_picnum;
896     block_fifo_t *p_dts_fifo;
897
898     block_t *p_chain;
899
900     struct picture_pts_t pts_tlb[SCHRO_PTS_TLB_SIZE];
901     mtime_t i_pts_offset;
902     mtime_t i_field_time;
903
904     bool b_eos_signalled;
905     bool b_eos_pulled;
906 };
907
908 static struct
909 {
910     unsigned int i_height;
911     int i_approx_fps;
912     SchroVideoFormatEnum i_vf;
913 } schro_format_guess[] = {
914     /* Important: Keep this list ordered in ascending picture height */
915     {1, 0, SCHRO_VIDEO_FORMAT_CUSTOM},
916     {120, 15, SCHRO_VIDEO_FORMAT_QSIF},
917     {144, 12, SCHRO_VIDEO_FORMAT_QCIF},
918     {240, 15, SCHRO_VIDEO_FORMAT_SIF},
919     {288, 12, SCHRO_VIDEO_FORMAT_CIF},
920     {480, 30, SCHRO_VIDEO_FORMAT_SD480I_60},
921     {480, 15, SCHRO_VIDEO_FORMAT_4SIF},
922     {576, 12, SCHRO_VIDEO_FORMAT_4CIF},
923     {576, 25, SCHRO_VIDEO_FORMAT_SD576I_50},
924     {720, 50, SCHRO_VIDEO_FORMAT_HD720P_50},
925     {720, 60, SCHRO_VIDEO_FORMAT_HD720P_60},
926     {1080, 24, SCHRO_VIDEO_FORMAT_DC2K_24},
927     {1080, 25, SCHRO_VIDEO_FORMAT_HD1080I_50},
928     {1080, 30, SCHRO_VIDEO_FORMAT_HD1080I_60},
929     {1080, 50, SCHRO_VIDEO_FORMAT_HD1080P_50},
930     {1080, 60, SCHRO_VIDEO_FORMAT_HD1080P_60},
931     {2160, 24, SCHRO_VIDEO_FORMAT_DC4K_24},
932     {0, 0, 0},
933 };
934
935 /*****************************************************************************
936  * ResetPTStlb: Purge all entries in @p_enc@'s PTS-tlb
937  *****************************************************************************/
938 static void ResetPTStlb( encoder_t *p_enc )
939 {
940     encoder_sys_t *p_sys = p_enc->p_sys;
941     for( int i = 0; i < SCHRO_PTS_TLB_SIZE; i++ )
942     {
943         p_sys->pts_tlb[i].b_empty = true;
944     }
945 }
946
947
948 /*****************************************************************************
949  * StorePicturePTS: Store the PTS value for a particular picture number
950  *****************************************************************************/
951 static void StorePicturePTS( encoder_t *p_enc, uint32_t u_pnum, mtime_t i_pts )
952 {
953     encoder_sys_t *p_sys = p_enc->p_sys;
954
955     for( int i = 0; i<SCHRO_PTS_TLB_SIZE; i++ )
956     {
957         if( p_sys->pts_tlb[i].b_empty )
958         {
959             p_sys->pts_tlb[i].u_pnum = u_pnum;
960             p_sys->pts_tlb[i].i_pts = i_pts;
961             p_sys->pts_tlb[i].b_empty = false;
962
963             return;
964         }
965     }
966
967     msg_Err( p_enc, "Could not store PTS %"PRId64" for frame %u", i_pts, u_pnum );
968 }
969
970 /*****************************************************************************
971  * GetPicturePTS: Retrieve the PTS value for a particular picture number
972  *****************************************************************************/
973 static mtime_t GetPicturePTS( encoder_t *p_enc, uint32_t u_pnum )
974 {
975     encoder_sys_t *p_sys = p_enc->p_sys;
976
977     for( int i = 0; i < SCHRO_PTS_TLB_SIZE; i++ )
978     {
979         if( !p_sys->pts_tlb[i].b_empty &&
980             p_sys->pts_tlb[i].u_pnum == u_pnum )
981         {
982              p_sys->pts_tlb[i].b_empty = true;
983              return p_sys->pts_tlb[i].i_pts;
984         }
985     }
986
987     msg_Err( p_enc, "Could not retrieve PTS for picture %u", u_pnum );
988     return 0;
989 }
990
991 static inline bool SchroSetEnum( const encoder_t *p_enc, int i_list_size, const char *list[],
992                   const char *psz_name,  const char *psz_name_text,  const char *psz_value)
993 {
994     encoder_sys_t *p_sys = p_enc->p_sys;
995     if( list && psz_name_text && psz_name && psz_value ) {
996         for( int i = 0; i < i_list_size; ++i ) {
997             if( strcmp( list[i], psz_value ) )
998                 continue;
999             schro_encoder_setting_set_double( p_sys->p_schro, psz_name, i );
1000             return true;
1001         }
1002         msg_Err( p_enc, "Invalid %s: %s", psz_name_text, psz_value );
1003     }
1004     return false;
1005 }
1006
1007 static bool SetEncChromaFormat( encoder_t *p_enc, uint32_t i_codec )
1008 {
1009     encoder_sys_t *p_sys = p_enc->p_sys;
1010
1011     switch( i_codec ) {
1012     case VLC_CODEC_I420:
1013         p_enc->fmt_in.i_codec = i_codec;
1014         p_enc->fmt_in.video.i_bits_per_pixel = 12;
1015         p_sys->p_format->chroma_format = SCHRO_CHROMA_420;
1016            break;
1017     case VLC_CODEC_I422:
1018         p_enc->fmt_in.i_codec = i_codec;
1019         p_enc->fmt_in.video.i_bits_per_pixel = 16;
1020         p_sys->p_format->chroma_format = SCHRO_CHROMA_422;
1021         break;
1022     case VLC_CODEC_I444:
1023         p_enc->fmt_in.i_codec = i_codec;
1024         p_enc->fmt_in.video.i_bits_per_pixel = 24;
1025         p_sys->p_format->chroma_format = SCHRO_CHROMA_444;
1026         break;
1027     default:
1028         return false;
1029     }
1030
1031     return true;
1032 }
1033
1034 #define SCHRO_SET_FLOAT(psz_name, pschro_name) \
1035     f_tmp = var_GetFloat( p_enc, ENC_CFG_PREFIX psz_name ); \
1036     if( f_tmp >= 0.0 ) \
1037         schro_encoder_setting_set_double( p_sys->p_schro, pschro_name, f_tmp );
1038
1039 #define SCHRO_SET_INTEGER(psz_name, pschro_name, ignore_val) \
1040     i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX psz_name ); \
1041     if( i_tmp > ignore_val ) \
1042         schro_encoder_setting_set_double( p_sys->p_schro, pschro_name, i_tmp );
1043
1044 #define SCHRO_SET_ENUM(list, psz_name, psz_name_text, pschro_name) \
1045     psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX psz_name ); \
1046     if( !psz_tmp ) \
1047         goto error; \
1048     else if ( *psz_tmp != '\0' ) { \
1049         int i_list_size = ARRAY_SIZE(list); \
1050         if( !SchroSetEnum( p_enc, i_list_size, list, pschro_name, psz_name_text, psz_tmp ) ) { \
1051             free( psz_tmp ); \
1052             goto error; \
1053         } \
1054     } \
1055     free( psz_tmp );
1056
1057 /*****************************************************************************
1058  * OpenEncoder: probe the encoder and return score
1059  *****************************************************************************/
1060 static int OpenEncoder( vlc_object_t *p_this )
1061 {
1062     encoder_t *p_enc = (encoder_t *)p_this;
1063     encoder_sys_t *p_sys;
1064     int i_tmp;
1065     float f_tmp;
1066     char *psz_tmp;
1067
1068     if( p_enc->fmt_out.i_codec != VLC_CODEC_DIRAC &&
1069         !p_enc->b_force )
1070     {
1071         return VLC_EGENERIC;
1072     }
1073
1074     if( !p_enc->fmt_in.video.i_frame_rate || !p_enc->fmt_in.video.i_frame_rate_base ||
1075         !p_enc->fmt_in.video.i_visible_height || !p_enc->fmt_in.video.i_visible_width )
1076     {
1077         msg_Err( p_enc, "Framerate and picture dimensions must be non-zero" );
1078         return VLC_EGENERIC;
1079     }
1080
1081     /* Allocate the memory needed to store the decoder's structure */
1082     if( ( p_sys = calloc( 1, sizeof( *p_sys ) ) ) == NULL )
1083         return VLC_ENOMEM;
1084
1085     p_enc->p_sys = p_sys;
1086     p_enc->pf_encode_video = Encode;
1087     p_enc->fmt_out.i_codec = VLC_CODEC_DIRAC;
1088     p_enc->fmt_out.i_cat = VIDEO_ES;
1089
1090     if( ( p_sys->p_dts_fifo = block_FifoNew() ) == NULL )
1091     {
1092         CloseEncoder( p_this );
1093         return VLC_ENOMEM;
1094     }
1095
1096     ResetPTStlb( p_enc );
1097
1098     /* guess the video format based upon number of lines and picture height */
1099     int i = 0;
1100     SchroVideoFormatEnum guessed_video_fmt = SCHRO_VIDEO_FORMAT_CUSTOM;
1101     /* Pick the dirac_video_format in this order of preference:
1102      *  1. an exact match in frame height and an approximate fps match
1103      *  2. the previous preset with a smaller number of lines.
1104      */
1105     do
1106     {
1107         if( schro_format_guess[i].i_height > p_enc->fmt_in.video.i_height )
1108         {
1109             guessed_video_fmt = schro_format_guess[i-1].i_vf;
1110             break;
1111         }
1112         if( schro_format_guess[i].i_height != p_enc->fmt_in.video.i_height )
1113             continue;
1114         int src_fps = p_enc->fmt_in.video.i_frame_rate / p_enc->fmt_in.video.i_frame_rate_base;
1115         int delta_fps = abs( schro_format_guess[i].i_approx_fps - src_fps );
1116         if( delta_fps > 2 )
1117             continue;
1118
1119         guessed_video_fmt = schro_format_guess[i].i_vf;
1120         break;
1121     } while( schro_format_guess[++i].i_height );
1122
1123     schro_init();
1124     p_sys->p_schro = schro_encoder_new();
1125     if( !p_sys->p_schro ) {
1126         msg_Err( p_enc, "Failed to initialize libschroedinger encoder" );
1127         return VLC_EGENERIC;
1128     }
1129     schro_encoder_set_packet_assembly( p_sys->p_schro, true );
1130
1131     if( !( p_sys->p_format = schro_encoder_get_video_format( p_sys->p_schro ) ) ) {
1132         msg_Err( p_enc, "Failed to get Schroedigner video format" );
1133         schro_encoder_free( p_sys->p_schro );
1134         return VLC_EGENERIC;
1135     }
1136
1137     /* initialise the video format parameters to the guessed format */
1138     schro_video_format_set_std_video_format( p_sys->p_format, guessed_video_fmt );
1139
1140     /* constants set from the input video format */
1141     p_sys->p_format->width                  = p_enc->fmt_in.video.i_visible_width;
1142     p_sys->p_format->height                 = p_enc->fmt_in.video.i_visible_height;
1143     p_sys->p_format->frame_rate_numerator   = p_enc->fmt_in.video.i_frame_rate;
1144     p_sys->p_format->frame_rate_denominator = p_enc->fmt_in.video.i_frame_rate_base;
1145     unsigned u_asr_num, u_asr_den;
1146     vlc_ureduce( &u_asr_num, &u_asr_den,
1147                  p_enc->fmt_in.video.i_sar_num,
1148                  p_enc->fmt_in.video.i_sar_den, 0 );
1149     p_sys->p_format->aspect_ratio_numerator   = u_asr_num;
1150     p_sys->p_format->aspect_ratio_denominator = u_asr_den;
1151
1152     config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg );
1153
1154     SCHRO_SET_ENUM(enc_rate_control_list, ENC_RATE_CONTROL, ENC_RATE_CONTROL_TEXT, "rate_control")
1155
1156     SCHRO_SET_ENUM(enc_gop_structure_list, ENC_GOP_STRUCTURE, ENC_GOP_STRUCTURE_TEXT, "gop_structure")
1157
1158     psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_CHROMAFMT );
1159     if( !psz_tmp )
1160         goto error;
1161     else {
1162         uint32_t i_codec;
1163         if( !strcmp( psz_tmp, "420" ) ) {
1164             i_codec = VLC_CODEC_I420;
1165         }
1166         else if( !strcmp( psz_tmp, "422" ) ) {
1167             i_codec = VLC_CODEC_I422;
1168         }
1169         else if( !strcmp( psz_tmp, "444" ) ) {
1170             i_codec = VLC_CODEC_I444;
1171         }
1172         else {
1173             msg_Err( p_enc, "Invalid chroma format: %s", psz_tmp );
1174             free( psz_tmp );
1175             goto error;
1176         }
1177         SetEncChromaFormat( p_enc, i_codec );
1178     }
1179     free( psz_tmp );
1180
1181     SCHRO_SET_FLOAT(ENC_QUALITY, "quality")
1182
1183     SCHRO_SET_FLOAT(ENC_NOISE_THRESHOLD, "noise_threshold")
1184
1185     /* use bitrate from sout-transcode-vb in kbps */
1186     i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_BITRATE );
1187     if( i_tmp > -1 )
1188         schro_encoder_setting_set_double( p_sys->p_schro, "bitrate", i_tmp * 1000 );
1189     else
1190         schro_encoder_setting_set_double( p_sys->p_schro, "bitrate", p_enc->fmt_out.i_bitrate );
1191
1192        p_enc->fmt_out.i_bitrate = schro_encoder_setting_get_double( p_sys->p_schro, "bitrate" );
1193
1194     i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_MIN_BITRATE );
1195     if( i_tmp > -1 )
1196         schro_encoder_setting_set_double( p_sys->p_schro, "min_bitrate", i_tmp * 1000 );
1197
1198     i_tmp = var_GetInteger( p_enc, ENC_CFG_PREFIX ENC_MAX_BITRATE );
1199     if( i_tmp > -1 )
1200         schro_encoder_setting_set_double( p_sys->p_schro, "max_bitrate", i_tmp * 1000 );
1201
1202     SCHRO_SET_INTEGER(ENC_AU_DISTANCE, "au_distance", -1)
1203
1204     SCHRO_SET_ENUM(enc_filtering_list, ENC_PREFILTER, ENC_PREFILTER_TEXT, "filtering")
1205
1206     SCHRO_SET_FLOAT(ENC_PREFILTER_STRENGTH, "filter_value")
1207
1208
1209     psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_CODINGMODE );
1210     if( !psz_tmp )
1211         goto error;
1212     else if( !strcmp( psz_tmp, "auto" ) ) {
1213         p_sys->b_auto_field_coding = true;
1214     }
1215     else if( !strcmp( psz_tmp, "progressive" ) ) {
1216         p_sys->b_auto_field_coding = false;
1217         schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", false);
1218     }
1219     else if( !strcmp( psz_tmp, "field" ) ) {
1220         p_sys->b_auto_field_coding = false;
1221         schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", true);
1222     }
1223     else {
1224         msg_Err( p_enc, "Invalid codingmode: %s", psz_tmp );
1225         free( psz_tmp );
1226         goto error;
1227     }
1228     free( psz_tmp );
1229
1230     SCHRO_SET_ENUM(enc_block_size_list, ENC_MCBLK_SIZE, ENC_MCBLK_SIZE_TEXT, "motion_block_size")
1231
1232     SCHRO_SET_ENUM(enc_block_overlap_list, ENC_MCBLK_OVERLAP, ENC_MCBLK_OVERLAP_TEXT, "motion_block_overlap")
1233
1234     psz_tmp = var_GetString( p_enc, ENC_CFG_PREFIX ENC_MVPREC );
1235     if( !psz_tmp )
1236         goto error;
1237     else if( *psz_tmp != '\0') {
1238         if( !strcmp( psz_tmp, "1" ) ) {
1239             schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 0 );
1240         }
1241         else if( !strcmp( psz_tmp, "1/2" ) ) {
1242             schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 1 );
1243         }
1244         else if( !strcmp( psz_tmp, "1/4" ) ) {
1245             schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 2 );
1246         }
1247         else if( !strcmp( psz_tmp, "1/8" ) ) {
1248             schro_encoder_setting_set_double( p_sys->p_schro, "mv_precision", 3 );
1249         }
1250         else {
1251             msg_Err( p_enc, "Invalid mv_precision: %s", psz_tmp );
1252             free( psz_tmp );
1253             goto error;
1254         }
1255     }
1256     free( psz_tmp );
1257
1258     SCHRO_SET_INTEGER(ENC_ME_COMBINED, "enable_chroma_me", -1)
1259
1260     SCHRO_SET_ENUM(enc_wavelet_list, ENC_DWTINTRA, ENC_DWTINTRA_TEXT, "intra_wavelet")
1261
1262     SCHRO_SET_ENUM(enc_wavelet_list, ENC_DWTINTER, ENC_DWTINTER_TEXT, "inter_wavelet")
1263
1264     SCHRO_SET_INTEGER(ENC_DWTDEPTH, "transform_depth", -1)
1265
1266     SCHRO_SET_INTEGER(ENC_MULTIQUANT, "enable_multiquant", -1)
1267
1268     SCHRO_SET_INTEGER(ENC_NOAC, "enable_noarith", -1)
1269
1270     SCHRO_SET_ENUM(enc_perceptual_weighting_list, ENC_PWT, ENC_PWT_TEXT, "perceptual_weighting")
1271
1272     SCHRO_SET_FLOAT(ENC_PDIST, "perceptual_distance")
1273
1274     SCHRO_SET_INTEGER(ENC_HSLICES, "horiz_slices", -1)
1275
1276     SCHRO_SET_INTEGER(ENC_VSLICES, "vert_slices", -1)
1277
1278     SCHRO_SET_ENUM(enc_codeblock_size_list, ENC_SCBLK_SIZE, ENC_SCBLK_SIZE_TEXT, "codeblock_size")
1279
1280     SCHRO_SET_INTEGER(ENC_ME_HIERARCHICAL, "enable_hierarchical_estimation", -1)
1281
1282     SCHRO_SET_INTEGER(ENC_ME_DOWNSAMPLE_LEVELS, "downsample_levels", 1)
1283
1284     SCHRO_SET_INTEGER(ENC_ME_GLOBAL_MOTION, "enable_global_motion", -1)
1285
1286     SCHRO_SET_INTEGER(ENC_ME_PHASECORR, "enable_phasecorr_estimation", -1)
1287
1288     SCHRO_SET_INTEGER(ENC_SCD, "enable_scene_change_detection", -1)
1289
1290     SCHRO_SET_ENUM(enc_profile_list, ENC_FORCE_PROFILE, ENC_FORCE_PROFILE_TEXT, "force_profile")
1291
1292     p_sys->started = 0;
1293
1294     return VLC_SUCCESS;
1295 error:
1296     CloseEncoder( p_this );
1297     return VLC_EGENERIC;
1298 }
1299
1300
1301 struct enc_picture_free_t
1302 {
1303    picture_t *p_pic;
1304    encoder_t *p_enc;
1305 };
1306
1307 /*****************************************************************************
1308  * EncSchroFrameFree: schro_frame callback to release the associated picture_t
1309  * When schro_encoder_reset() is called there will be pictures in the
1310  * encoding pipeline that need to be released rather than displayed.
1311  *****************************************************************************/
1312 static void EncSchroFrameFree( SchroFrame *frame, void *priv )
1313 {
1314     struct enc_picture_free_t *p_free = priv;
1315
1316     if( !p_free )
1317         return;
1318
1319     picture_Release( p_free->p_pic );
1320     free( p_free );
1321     (void)frame;
1322 }
1323
1324 /*****************************************************************************
1325  * CreateSchroFrameFromPic: wrap a picture_t in a SchroFrame
1326  *****************************************************************************/
1327 static SchroFrame *CreateSchroFrameFromInputPic( encoder_t *p_enc,  picture_t *p_pic )
1328 {
1329     encoder_sys_t *p_sys = p_enc->p_sys;
1330     SchroFrame *p_schroframe = schro_frame_new();
1331     struct enc_picture_free_t *p_free;
1332
1333     if( !p_schroframe )
1334         return NULL;
1335
1336     if( !p_pic )
1337         return NULL;
1338
1339     p_schroframe->format = SCHRO_FRAME_FORMAT_U8_420;
1340     if( p_sys->p_format->chroma_format == SCHRO_CHROMA_422 )
1341     {
1342         p_schroframe->format = SCHRO_FRAME_FORMAT_U8_422;
1343     }
1344     else if( p_sys->p_format->chroma_format == SCHRO_CHROMA_444 )
1345     {
1346         p_schroframe->format = SCHRO_FRAME_FORMAT_U8_444;
1347     }
1348
1349     p_schroframe->width  = p_sys->p_format->width;
1350     p_schroframe->height = p_sys->p_format->height;
1351
1352     p_free = malloc( sizeof( *p_free ) );
1353     if( unlikely( p_free == NULL ) ) {
1354         schro_frame_unref( p_schroframe );
1355         return NULL;
1356     }
1357
1358     p_free->p_pic = p_pic;
1359     p_free->p_enc = p_enc;
1360     schro_frame_set_free_callback( p_schroframe, EncSchroFrameFree, p_free );
1361
1362     for( int i=0; i<3; i++ )
1363     {
1364         p_schroframe->components[i].width  = p_pic->p[i].i_visible_pitch;
1365         p_schroframe->components[i].stride = p_pic->p[i].i_pitch;
1366         p_schroframe->components[i].height = p_pic->p[i].i_visible_lines;
1367         p_schroframe->components[i].length =
1368             p_pic->p[i].i_pitch * p_pic->p[i].i_lines;
1369         p_schroframe->components[i].data   = p_pic->p[i].p_pixels;
1370
1371         if( i!=0 )
1372         {
1373             p_schroframe->components[i].v_shift =
1374                 SCHRO_FRAME_FORMAT_V_SHIFT( p_schroframe->format );
1375             p_schroframe->components[i].h_shift =
1376                 SCHRO_FRAME_FORMAT_H_SHIFT( p_schroframe->format );
1377         }
1378     }
1379
1380     return p_schroframe;
1381 }
1382
1383 /* Attempt to find dirac picture number in an encapsulation unit */
1384 static int ReadDiracPictureNumber( uint32_t *p_picnum, block_t *p_block )
1385 {
1386     uint32_t u_pos = 4;
1387     /* protect against falling off the edge */
1388     while( u_pos + 13 < p_block->i_buffer )
1389     {
1390         /* find the picture startcode */
1391         if( p_block->p_buffer[u_pos] & 0x08 )
1392         {
1393             *p_picnum = GetDWBE( p_block->p_buffer + u_pos + 9 );
1394             return 1;
1395         }
1396         /* skip to the next dirac data unit */
1397         uint32_t u_npo = GetDWBE( p_block->p_buffer + u_pos + 1 );
1398         assert( u_npo <= UINT32_MAX - u_pos );
1399         if( u_npo == 0 )
1400             u_npo = 13;
1401         u_pos += u_npo;
1402     }
1403     return 0;
1404 }
1405
1406
1407 static block_t *Encode( encoder_t *p_enc, picture_t *p_pic )
1408 {
1409     encoder_sys_t *p_sys = p_enc->p_sys;
1410     block_t *p_block, *p_output_chain = NULL;
1411     SchroFrame *p_frame;
1412     bool b_go = true;
1413
1414     if( !p_pic ) {
1415         if( !p_sys->started || p_sys->b_eos_pulled )
1416             return NULL;
1417
1418         if( !p_sys->b_eos_signalled ) {
1419             p_sys->b_eos_signalled = 1;
1420             schro_encoder_end_of_stream( p_sys->p_schro );
1421         }
1422     } else {
1423         /* we only know if the sequence is interlaced when the first
1424          * picture arrives, so final setup is done here */
1425         /* XXX todo, detect change of interlace */
1426         p_sys->p_format->interlaced = !p_pic->b_progressive;
1427         p_sys->p_format->top_field_first = p_pic->b_top_field_first;
1428
1429         if( p_sys->b_auto_field_coding )
1430             schro_encoder_setting_set_double( p_sys->p_schro, "interlaced_coding", !p_pic->b_progressive );
1431     }
1432
1433     if( !p_sys->started ) {
1434         date_t date;
1435
1436         if( p_pic->format.i_chroma != p_enc->fmt_in.i_codec ) {
1437             char chroma_in[5], chroma_out[5];
1438             vlc_fourcc_to_char( p_pic->format.i_chroma, chroma_in );
1439             chroma_in[4]  = '\0';
1440             chroma_out[4] = '\0';
1441             vlc_fourcc_to_char( p_enc->fmt_in.i_codec, chroma_out );
1442             msg_Warn( p_enc, "Resetting chroma from %s to %s", chroma_out, chroma_in );
1443             if( !SetEncChromaFormat( p_enc, p_pic->format.i_chroma ) ) {
1444                 msg_Err( p_enc, "Could not reset chroma format to %s", chroma_in );
1445                 return NULL;
1446             }
1447         }
1448
1449         date_Init( &date, p_enc->fmt_in.video.i_frame_rate, p_enc->fmt_in.video.i_frame_rate_base );
1450         /* FIXME - Unlike dirac-research codec Schro doesn't have a function that returns the delay in pics yet.
1451          *   Use a default of 1
1452          */
1453         date_Increment( &date, 1 );
1454         p_sys->i_pts_offset = date_Get( &date );
1455         if( schro_encoder_setting_get_double( p_sys->p_schro, "interlaced_coding" ) > 0.0 ) {
1456             date_Set( &date, 0 );
1457             date_Increment( &date, 1);
1458             p_sys->i_field_time = date_Get( &date ) / 2;
1459         }
1460
1461         schro_video_format_set_std_signal_range( p_sys->p_format, SCHRO_SIGNAL_RANGE_8BIT_VIDEO );
1462         schro_encoder_set_video_format( p_sys->p_schro, p_sys->p_format );
1463         schro_encoder_start( p_sys->p_schro );
1464         p_sys->started = 1;
1465     }
1466
1467     if( !p_sys->b_eos_signalled ) {
1468         /* create a schro frame from the input pic and load */
1469         /* Increase ref count by 1 so that the picture is not freed until
1470            Schro finishes with it */
1471         picture_Hold( p_pic );
1472
1473         p_frame = CreateSchroFrameFromInputPic( p_enc, p_pic );
1474         if( !p_frame )
1475             return NULL;
1476         schro_encoder_push_frame( p_sys->p_schro, p_frame );
1477
1478
1479         /* store pts in a lookaside buffer, so that the same pts may
1480         * be used for the picture in coded order */
1481         StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date );
1482         p_sys->i_input_picnum++;
1483
1484         /* store dts in a queue, so that they appear in order in
1485          * coded order */
1486         p_block = block_Alloc( 1 );
1487         if( !p_block )
1488             return NULL;
1489         p_block->i_dts = p_pic->date - p_sys->i_pts_offset;
1490         block_FifoPut( p_sys->p_dts_fifo, p_block );
1491         p_block = NULL;
1492
1493         /* for field coding mode, insert an extra value into both the
1494          * pts lookaside buffer and dts queue, offset to correspond
1495          * to a one field delay. */
1496         if( schro_encoder_setting_get_double( p_sys->p_schro, "interlaced_coding" ) > 0.0 ) {
1497             StorePicturePTS( p_enc, p_sys->i_input_picnum, p_pic->date + p_sys->i_field_time );
1498             p_sys->i_input_picnum++;
1499
1500             p_block = block_Alloc( 1 );
1501             if( !p_block )
1502                 return NULL;
1503             p_block->i_dts = p_pic->date - p_sys->i_pts_offset + p_sys->i_field_time;
1504             block_FifoPut( p_sys->p_dts_fifo, p_block );
1505             p_block = NULL;
1506         }
1507     }
1508
1509     do
1510     {
1511         SchroStateEnum state;
1512         state = schro_encoder_wait( p_sys->p_schro );
1513         switch( state )
1514         {
1515         case SCHRO_STATE_NEED_FRAME:
1516             b_go = false;
1517             break;
1518         case SCHRO_STATE_AGAIN:
1519             break;
1520         case SCHRO_STATE_END_OF_STREAM:
1521             p_sys->b_eos_pulled = 1;
1522             b_go = false;
1523             break;
1524         case SCHRO_STATE_HAVE_BUFFER:
1525         {
1526             SchroBuffer *p_enc_buf;
1527             uint32_t u_pic_num;
1528             int i_presentation_frame;
1529             p_enc_buf = schro_encoder_pull( p_sys->p_schro, &i_presentation_frame );
1530             p_block = block_Alloc( p_enc_buf->length );
1531             if( !p_block )
1532                 return NULL;
1533
1534             memcpy( p_block->p_buffer, p_enc_buf->data, p_enc_buf->length );
1535             schro_buffer_unref( p_enc_buf );
1536
1537             /* Presence of a Sequence header indicates a seek point */
1538             if( 0 == p_block->p_buffer[4] )
1539             {
1540                 p_block->i_flags |= BLOCK_FLAG_TYPE_I;
1541
1542                 if( !p_enc->fmt_out.p_extra ) {
1543                     const uint8_t eos[] = { 'B','B','C','D',0x10,0,0,0,13,0,0,0,0 };
1544                     uint32_t len = GetDWBE( p_block->p_buffer + 5 );
1545                     /* if it hasn't been done so far, stash a copy of the
1546                      * sequence header for muxers such as ogg */
1547                     /* The OggDirac spec advises that a Dirac EOS DataUnit
1548                      * is appended to the sequence header to allow guard
1549                      * against poor streaming servers */
1550                     /* XXX, should this be done using the packetizer ? */
1551
1552                     if( len > UINT32_MAX - sizeof( eos ) )
1553                         return NULL;
1554
1555                     p_enc->fmt_out.p_extra = malloc( len + sizeof( eos ) );
1556                     if( !p_enc->fmt_out.p_extra )
1557                         return NULL;
1558                     memcpy( p_enc->fmt_out.p_extra, p_block->p_buffer, len );
1559                     memcpy( (uint8_t*)p_enc->fmt_out.p_extra + len, eos, sizeof( eos ) );
1560                     SetDWBE( (uint8_t*)p_enc->fmt_out.p_extra + len + sizeof(eos) - 4, len );
1561                     p_enc->fmt_out.i_extra = len + sizeof( eos );
1562                 }
1563             }
1564
1565             if( ReadDiracPictureNumber( &u_pic_num, p_block ) ) {
1566                 block_t *p_dts_block = block_FifoGet( p_sys->p_dts_fifo );
1567                 p_block->i_dts = p_dts_block->i_dts;
1568                    p_block->i_pts = GetPicturePTS( p_enc, u_pic_num );
1569                 block_Release( p_dts_block );
1570                 block_ChainAppend( &p_output_chain, p_block );
1571             } else {
1572                 /* End of sequence */
1573                 block_ChainAppend( &p_output_chain, p_block );
1574             }
1575             break;
1576         }
1577         default:
1578             break;
1579         }
1580     } while( b_go );
1581
1582     return p_output_chain;
1583 }
1584
1585 /*****************************************************************************
1586  * CloseEncoder: Schro encoder destruction
1587  *****************************************************************************/
1588 static void CloseEncoder( vlc_object_t *p_this )
1589 {
1590     encoder_t *p_enc = (encoder_t *)p_this;
1591     encoder_sys_t *p_sys = p_enc->p_sys;
1592
1593     /* Free the encoder resources */
1594     if( p_sys->p_schro )
1595         schro_encoder_free( p_sys->p_schro );
1596
1597     free( p_sys->p_format );
1598
1599     if( p_sys->p_dts_fifo )
1600         block_FifoRelease( p_sys->p_dts_fifo );
1601
1602     block_ChainRelease( p_sys->p_chain );
1603
1604     free( p_sys );
1605 }