]> git.sesse.net Git - x264/blob - encoder/set.c
d3a5f606a98aa22fdbb6dc388212c16e26ba832b
[x264] / encoder / set.c
1 /*****************************************************************************
2  * set: header writing
3  *****************************************************************************
4  * Copyright (C) 2003-2011 x264 project
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *          Loren Merritt <lorenm@u.washington.edu>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
22  *
23  * This program is also available under a commercial proprietary license.
24  * For more information, contact us at licensing@x264.com.
25  *****************************************************************************/
26
27 #include "common/common.h"
28 #include "set.h"
29
30 #define bs_write_ue bs_write_ue_big
31
32 // Indexed by pic_struct values
33 static const uint8_t num_clock_ts[10] = { 0, 1, 1, 1, 2, 2, 3, 3, 2, 3 };
34
35 static void transpose( uint8_t *buf, int w )
36 {
37     for( int i = 0; i < w; i++ )
38         for( int j = 0; j < i; j++ )
39             XCHG( uint8_t, buf[w*i+j], buf[w*j+i] );
40 }
41
42 static void scaling_list_write( bs_t *s, x264_pps_t *pps, int idx )
43 {
44     const int len = idx<4 ? 16 : 64;
45     const uint8_t *zigzag = idx<4 ? x264_zigzag_scan4[0] : x264_zigzag_scan8[0];
46     const uint8_t *list = pps->scaling_list[idx];
47     const uint8_t *def_list = (idx==CQM_4IC) ? pps->scaling_list[CQM_4IY]
48                             : (idx==CQM_4PC) ? pps->scaling_list[CQM_4PY]
49                             : x264_cqm_jvt[idx];
50     if( !memcmp( list, def_list, len ) )
51         bs_write1( s, 0 );   // scaling_list_present_flag
52     else if( !memcmp( list, x264_cqm_jvt[idx], len ) )
53     {
54         bs_write1( s, 1 );   // scaling_list_present_flag
55         bs_write_se( s, -8 ); // use jvt list
56     }
57     else
58     {
59         int run;
60         bs_write1( s, 1 );   // scaling_list_present_flag
61
62         // try run-length compression of trailing values
63         for( run = len; run > 1; run-- )
64             if( list[zigzag[run-1]] != list[zigzag[run-2]] )
65                 break;
66         if( run < len && len - run < bs_size_se( (int8_t)-list[zigzag[run]] ) )
67             run = len;
68
69         for( int j = 0; j < run; j++ )
70             bs_write_se( s, (int8_t)(list[zigzag[j]] - (j>0 ? list[zigzag[j-1]] : 8)) ); // delta
71
72         if( run < len )
73             bs_write_se( s, (int8_t)-list[zigzag[run]] );
74     }
75 }
76
77 void x264_sei_write( bs_t *s, uint8_t *payload, int payload_size, int payload_type )
78 {
79     int i;
80
81     bs_realign( s );
82
83     for( i = 0; i <= payload_type-255; i += 255 )
84         bs_write( s, 8, 255 );
85     bs_write( s, 8, payload_type-i );
86
87     for( i = 0; i <= payload_size-255; i += 255 )
88         bs_write( s, 8, 255 );
89     bs_write( s, 8, payload_size-i );
90
91     for( i = 0; i < payload_size; i++ )
92         bs_write(s, 8, payload[i] );
93
94     bs_rbsp_trailing( s );
95     bs_flush( s );
96 }
97
98 void x264_sps_init( x264_sps_t *sps, int i_id, x264_param_t *param )
99 {
100     sps->i_id = i_id;
101     sps->i_mb_width = ( param->i_width + 15 ) / 16;
102     sps->i_mb_height= ( param->i_height + 15 ) / 16;
103
104     sps->b_qpprime_y_zero_transform_bypass = param->rc.i_rc_method == X264_RC_CQP && param->rc.i_qp_constant == 0;
105     if( sps->b_qpprime_y_zero_transform_bypass )
106         sps->i_profile_idc  = PROFILE_HIGH444_PREDICTIVE;
107     else if( BIT_DEPTH > 8 )
108         sps->i_profile_idc  = PROFILE_HIGH10;
109     else if( param->analyse.b_transform_8x8 || param->i_cqm_preset != X264_CQM_FLAT )
110         sps->i_profile_idc  = PROFILE_HIGH;
111     else if( param->b_cabac || param->i_bframe > 0 || param->b_interlaced || param->b_fake_interlaced || param->analyse.i_weighted_pred > 0 )
112         sps->i_profile_idc  = PROFILE_MAIN;
113     else
114         sps->i_profile_idc  = PROFILE_BASELINE;
115
116     sps->b_constraint_set0  = sps->i_profile_idc == PROFILE_BASELINE;
117     /* x264 doesn't support the features that are in Baseline and not in Main,
118      * namely arbitrary_slice_order and slice_groups. */
119     sps->b_constraint_set1  = sps->i_profile_idc <= PROFILE_MAIN;
120     /* Never set constraint_set2, it is not necessary and not used in real world. */
121     sps->b_constraint_set2  = 0;
122     sps->b_constraint_set3  = 0;
123
124     sps->i_level_idc = param->i_level_idc;
125     if( param->i_level_idc == 9 && ( sps->i_profile_idc >= PROFILE_BASELINE && sps->i_profile_idc <= PROFILE_EXTENDED ) )
126     {
127         sps->b_constraint_set3 = 1; /* level 1b with Baseline, Main or Extended profile is signalled via constraint_set3 */
128         sps->i_level_idc      = 11;
129     }
130     /* High 10 Intra profile */
131     if( param->i_keyint_max == 1 && sps->i_profile_idc == PROFILE_HIGH10 )
132         sps->b_constraint_set3 = 1;
133
134     sps->vui.i_num_reorder_frames = param->i_bframe_pyramid ? 2 : param->i_bframe ? 1 : 0;
135     /* extra slot with pyramid so that we don't have to override the
136      * order of forgetting old pictures */
137     sps->vui.i_max_dec_frame_buffering =
138     sps->i_num_ref_frames = X264_MIN(X264_REF_MAX, X264_MAX4(param->i_frame_reference, 1 + sps->vui.i_num_reorder_frames,
139                             param->i_bframe_pyramid ? 4 : 1, param->i_dpb_size));
140     sps->i_num_ref_frames -= param->i_bframe_pyramid == X264_B_PYRAMID_STRICT;
141     if( param->i_keyint_max == 1 )
142     {
143         sps->i_num_ref_frames = 0;
144         sps->vui.i_max_dec_frame_buffering = 0;
145     }
146
147     /* number of refs + current frame */
148     int max_frame_num = sps->vui.i_max_dec_frame_buffering * (!!param->i_bframe_pyramid+1) + 1;
149     /* Intra refresh cannot write a recovery time greater than max frame num-1 */
150     if( param->b_intra_refresh )
151     {
152         int time_to_recovery = X264_MIN( sps->i_mb_width - 1, param->i_keyint_max ) + param->i_bframe - 1;
153         max_frame_num = X264_MAX( max_frame_num, time_to_recovery+1 );
154     }
155
156     sps->i_log2_max_frame_num = 4;
157     while( (1 << sps->i_log2_max_frame_num) <= max_frame_num )
158         sps->i_log2_max_frame_num++;
159
160     sps->i_poc_type = param->i_bframe || param->b_interlaced ? 0 : 2;
161     if( sps->i_poc_type == 0 )
162     {
163         int max_delta_poc = (param->i_bframe + 2) * (!!param->i_bframe_pyramid + 1) * 2;
164         sps->i_log2_max_poc_lsb = 4;
165         while( (1 << sps->i_log2_max_poc_lsb) <= max_delta_poc * 2 )
166             sps->i_log2_max_poc_lsb++;
167     }
168
169     sps->b_vui = 1;
170
171     sps->b_gaps_in_frame_num_value_allowed = 0;
172     sps->b_frame_mbs_only = !(param->b_interlaced || param->b_fake_interlaced);
173     if( !sps->b_frame_mbs_only )
174         sps->i_mb_height = ( sps->i_mb_height + 1 ) & ~1;
175     sps->b_mb_adaptive_frame_field = param->b_interlaced;
176     sps->b_direct8x8_inference = 1;
177
178     sps->crop.i_left   = param->crop_rect.i_left;
179     sps->crop.i_top    = param->crop_rect.i_top;
180     sps->crop.i_right  = param->crop_rect.i_right + sps->i_mb_width*16 - param->i_width;
181     sps->crop.i_bottom = (param->crop_rect.i_bottom + sps->i_mb_height*16 - param->i_height) >> !sps->b_frame_mbs_only;
182     sps->b_crop = sps->crop.i_left  || sps->crop.i_top ||
183                   sps->crop.i_right || sps->crop.i_bottom;
184
185     sps->vui.b_aspect_ratio_info_present = 0;
186     if( param->vui.i_sar_width > 0 && param->vui.i_sar_height > 0 )
187     {
188         sps->vui.b_aspect_ratio_info_present = 1;
189         sps->vui.i_sar_width = param->vui.i_sar_width;
190         sps->vui.i_sar_height= param->vui.i_sar_height;
191     }
192
193     sps->vui.b_overscan_info_present = param->vui.i_overscan > 0 && param->vui.i_overscan <= 2;
194     if( sps->vui.b_overscan_info_present )
195         sps->vui.b_overscan_info = ( param->vui.i_overscan == 2 ? 1 : 0 );
196
197     sps->vui.b_signal_type_present = 0;
198     sps->vui.i_vidformat = ( param->vui.i_vidformat >= 0 && param->vui.i_vidformat <= 5 ? param->vui.i_vidformat : 5 );
199     sps->vui.b_fullrange = ( param->vui.b_fullrange ? 1 : 0 );
200     sps->vui.b_color_description_present = 0;
201
202     sps->vui.i_colorprim = ( param->vui.i_colorprim >= 0 && param->vui.i_colorprim <=  8 ? param->vui.i_colorprim : 2 );
203     sps->vui.i_transfer  = ( param->vui.i_transfer  >= 0 && param->vui.i_transfer  <= 10 ? param->vui.i_transfer  : 2 );
204     sps->vui.i_colmatrix = ( param->vui.i_colmatrix >= 0 && param->vui.i_colmatrix <=  8 ? param->vui.i_colmatrix : 2 );
205     if( sps->vui.i_colorprim != 2 ||
206         sps->vui.i_transfer  != 2 ||
207         sps->vui.i_colmatrix != 2 )
208     {
209         sps->vui.b_color_description_present = 1;
210     }
211
212     if( sps->vui.i_vidformat != 5 ||
213         sps->vui.b_fullrange ||
214         sps->vui.b_color_description_present )
215     {
216         sps->vui.b_signal_type_present = 1;
217     }
218
219     /* FIXME: not sufficient for interlaced video */
220     sps->vui.b_chroma_loc_info_present = param->vui.i_chroma_loc > 0 && param->vui.i_chroma_loc <= 5;
221     if( sps->vui.b_chroma_loc_info_present )
222     {
223         sps->vui.i_chroma_loc_top = param->vui.i_chroma_loc;
224         sps->vui.i_chroma_loc_bottom = param->vui.i_chroma_loc;
225     }
226
227     sps->vui.b_timing_info_present = param->i_timebase_num > 0 && param->i_timebase_den > 0;
228
229     if( sps->vui.b_timing_info_present )
230     {
231         sps->vui.i_num_units_in_tick = param->i_timebase_num;
232         sps->vui.i_time_scale = param->i_timebase_den * 2;
233         sps->vui.b_fixed_frame_rate = !param->b_vfr_input;
234     }
235
236     sps->vui.b_vcl_hrd_parameters_present = 0; // we don't support VCL HRD
237     sps->vui.b_nal_hrd_parameters_present = !!param->i_nal_hrd;
238     sps->vui.b_pic_struct_present = param->b_pic_struct;
239
240     // NOTE: HRD related parts of the SPS are initialised in x264_ratecontrol_init_reconfigurable
241
242     sps->vui.b_bitstream_restriction = 1;
243     if( sps->vui.b_bitstream_restriction )
244     {
245         sps->vui.b_motion_vectors_over_pic_boundaries = 1;
246         sps->vui.i_max_bytes_per_pic_denom = 0;
247         sps->vui.i_max_bits_per_mb_denom = 0;
248         sps->vui.i_log2_max_mv_length_horizontal =
249         sps->vui.i_log2_max_mv_length_vertical = (int)log2f( X264_MAX( 1, param->analyse.i_mv_range*4-1 ) ) + 1;
250     }
251 }
252
253 void x264_sps_write( bs_t *s, x264_sps_t *sps )
254 {
255     bs_realign( s );
256     bs_write( s, 8, sps->i_profile_idc );
257     bs_write1( s, sps->b_constraint_set0 );
258     bs_write1( s, sps->b_constraint_set1 );
259     bs_write1( s, sps->b_constraint_set2 );
260     bs_write1( s, sps->b_constraint_set3 );
261
262     bs_write( s, 4, 0 );    /* reserved */
263
264     bs_write( s, 8, sps->i_level_idc );
265
266     bs_write_ue( s, sps->i_id );
267
268     if( sps->i_profile_idc >= PROFILE_HIGH )
269     {
270         bs_write_ue( s, 1 ); // chroma_format_idc = 4:2:0
271         bs_write_ue( s, BIT_DEPTH-8 ); // bit_depth_luma_minus8
272         bs_write_ue( s, BIT_DEPTH-8 ); // bit_depth_chroma_minus8
273         bs_write1( s, sps->b_qpprime_y_zero_transform_bypass );
274         bs_write1( s, 0 ); // seq_scaling_matrix_present_flag
275     }
276
277     bs_write_ue( s, sps->i_log2_max_frame_num - 4 );
278     bs_write_ue( s, sps->i_poc_type );
279     if( sps->i_poc_type == 0 )
280         bs_write_ue( s, sps->i_log2_max_poc_lsb - 4 );
281     bs_write_ue( s, sps->i_num_ref_frames );
282     bs_write1( s, sps->b_gaps_in_frame_num_value_allowed );
283     bs_write_ue( s, sps->i_mb_width - 1 );
284     bs_write_ue( s, (sps->i_mb_height >> !sps->b_frame_mbs_only) - 1);
285     bs_write1( s, sps->b_frame_mbs_only );
286     if( !sps->b_frame_mbs_only )
287         bs_write1( s, sps->b_mb_adaptive_frame_field );
288     bs_write1( s, sps->b_direct8x8_inference );
289
290     bs_write1( s, sps->b_crop );
291     if( sps->b_crop )
292     {
293         bs_write_ue( s, sps->crop.i_left   / 2 );
294         bs_write_ue( s, sps->crop.i_right  / 2 );
295         bs_write_ue( s, sps->crop.i_top    / 2 );
296         bs_write_ue( s, sps->crop.i_bottom / 2 );
297     }
298
299     bs_write1( s, sps->b_vui );
300     if( sps->b_vui )
301     {
302         bs_write1( s, sps->vui.b_aspect_ratio_info_present );
303         if( sps->vui.b_aspect_ratio_info_present )
304         {
305             int i;
306             static const struct { uint8_t w, h, sar; } sar[] =
307             {
308                 // aspect_ratio_idc = 0 -> unspecified
309                 {  1,  1, 1 }, { 12, 11, 2 }, { 10, 11, 3 }, { 16, 11, 4 },
310                 { 40, 33, 5 }, { 24, 11, 6 }, { 20, 11, 7 }, { 32, 11, 8 },
311                 { 80, 33, 9 }, { 18, 11, 10}, { 15, 11, 11}, { 64, 33, 12},
312                 {160, 99, 13}, {  4,  3, 14}, {  3,  2, 15}, {  2,  1, 16},
313                 // aspect_ratio_idc = [17..254] -> reserved
314                 { 0, 0, 255 }
315             };
316             for( i = 0; sar[i].sar != 255; i++ )
317             {
318                 if( sar[i].w == sps->vui.i_sar_width &&
319                     sar[i].h == sps->vui.i_sar_height )
320                     break;
321             }
322             bs_write( s, 8, sar[i].sar );
323             if( sar[i].sar == 255 ) /* aspect_ratio_idc (extended) */
324             {
325                 bs_write( s, 16, sps->vui.i_sar_width );
326                 bs_write( s, 16, sps->vui.i_sar_height );
327             }
328         }
329
330         bs_write1( s, sps->vui.b_overscan_info_present );
331         if( sps->vui.b_overscan_info_present )
332             bs_write1( s, sps->vui.b_overscan_info );
333
334         bs_write1( s, sps->vui.b_signal_type_present );
335         if( sps->vui.b_signal_type_present )
336         {
337             bs_write( s, 3, sps->vui.i_vidformat );
338             bs_write1( s, sps->vui.b_fullrange );
339             bs_write1( s, sps->vui.b_color_description_present );
340             if( sps->vui.b_color_description_present )
341             {
342                 bs_write( s, 8, sps->vui.i_colorprim );
343                 bs_write( s, 8, sps->vui.i_transfer );
344                 bs_write( s, 8, sps->vui.i_colmatrix );
345             }
346         }
347
348         bs_write1( s, sps->vui.b_chroma_loc_info_present );
349         if( sps->vui.b_chroma_loc_info_present )
350         {
351             bs_write_ue( s, sps->vui.i_chroma_loc_top );
352             bs_write_ue( s, sps->vui.i_chroma_loc_bottom );
353         }
354
355         bs_write1( s, sps->vui.b_timing_info_present );
356         if( sps->vui.b_timing_info_present )
357         {
358             bs_write32( s, sps->vui.i_num_units_in_tick );
359             bs_write32( s, sps->vui.i_time_scale );
360             bs_write1( s, sps->vui.b_fixed_frame_rate );
361         }
362
363         bs_write1( s, sps->vui.b_nal_hrd_parameters_present );
364         if( sps->vui.b_nal_hrd_parameters_present )
365         {
366             bs_write_ue( s, sps->vui.hrd.i_cpb_cnt - 1 );
367             bs_write( s, 4, sps->vui.hrd.i_bit_rate_scale );
368             bs_write( s, 4, sps->vui.hrd.i_cpb_size_scale );
369
370             bs_write_ue( s, sps->vui.hrd.i_bit_rate_value - 1 );
371             bs_write_ue( s, sps->vui.hrd.i_cpb_size_value - 1 );
372
373             bs_write1( s, sps->vui.hrd.b_cbr_hrd );
374
375             bs_write( s, 5, sps->vui.hrd.i_initial_cpb_removal_delay_length - 1 );
376             bs_write( s, 5, sps->vui.hrd.i_cpb_removal_delay_length - 1 );
377             bs_write( s, 5, sps->vui.hrd.i_dpb_output_delay_length - 1 );
378             bs_write( s, 5, sps->vui.hrd.i_time_offset_length );
379         }
380
381         bs_write1( s, sps->vui.b_vcl_hrd_parameters_present );
382
383         if( sps->vui.b_nal_hrd_parameters_present || sps->vui.b_vcl_hrd_parameters_present )
384             bs_write1( s, 0 );   /* low_delay_hrd_flag */
385
386         bs_write1( s, sps->vui.b_pic_struct_present );
387         bs_write1( s, sps->vui.b_bitstream_restriction );
388         if( sps->vui.b_bitstream_restriction )
389         {
390             bs_write1( s, sps->vui.b_motion_vectors_over_pic_boundaries );
391             bs_write_ue( s, sps->vui.i_max_bytes_per_pic_denom );
392             bs_write_ue( s, sps->vui.i_max_bits_per_mb_denom );
393             bs_write_ue( s, sps->vui.i_log2_max_mv_length_horizontal );
394             bs_write_ue( s, sps->vui.i_log2_max_mv_length_vertical );
395             bs_write_ue( s, sps->vui.i_num_reorder_frames );
396             bs_write_ue( s, sps->vui.i_max_dec_frame_buffering );
397         }
398     }
399
400     bs_rbsp_trailing( s );
401     bs_flush( s );
402 }
403
404 void x264_pps_init( x264_pps_t *pps, int i_id, x264_param_t *param, x264_sps_t *sps )
405 {
406     pps->i_id = i_id;
407     pps->i_sps_id = sps->i_id;
408     pps->b_cabac = param->b_cabac;
409
410     pps->b_pic_order = param->b_interlaced;
411     pps->i_num_slice_groups = 1;
412
413     pps->i_num_ref_idx_l0_default_active = param->i_frame_reference;
414     pps->i_num_ref_idx_l1_default_active = 1;
415
416     pps->b_weighted_pred = param->analyse.i_weighted_pred > 0;
417     pps->b_weighted_bipred = param->analyse.b_weighted_bipred ? 2 : 0;
418
419     pps->i_pic_init_qp = param->rc.i_rc_method == X264_RC_ABR ? 26 + QP_BD_OFFSET : SPEC_QP( param->rc.i_qp_constant );
420     pps->i_pic_init_qs = 26 + QP_BD_OFFSET;
421
422     pps->i_chroma_qp_index_offset = param->analyse.i_chroma_qp_offset;
423     pps->b_deblocking_filter_control = 1;
424     pps->b_constrained_intra_pred = param->b_constrained_intra;
425     pps->b_redundant_pic_cnt = 0;
426
427     pps->b_transform_8x8_mode = param->analyse.b_transform_8x8 ? 1 : 0;
428
429     pps->i_cqm_preset = param->i_cqm_preset;
430     switch( pps->i_cqm_preset )
431     {
432     case X264_CQM_FLAT:
433         for( int i = 0; i < 6; i++ )
434             pps->scaling_list[i] = x264_cqm_flat16;
435         break;
436     case X264_CQM_JVT:
437         for( int i = 0; i < 6; i++ )
438             pps->scaling_list[i] = x264_cqm_jvt[i];
439         break;
440     case X264_CQM_CUSTOM:
441         /* match the transposed DCT & zigzag */
442         transpose( param->cqm_4iy, 4 );
443         transpose( param->cqm_4ic, 4 );
444         transpose( param->cqm_4py, 4 );
445         transpose( param->cqm_4pc, 4 );
446         transpose( param->cqm_8iy, 8 );
447         transpose( param->cqm_8py, 8 );
448         pps->scaling_list[CQM_4IY] = param->cqm_4iy;
449         pps->scaling_list[CQM_4IC] = param->cqm_4ic;
450         pps->scaling_list[CQM_4PY] = param->cqm_4py;
451         pps->scaling_list[CQM_4PC] = param->cqm_4pc;
452         pps->scaling_list[CQM_8IY+4] = param->cqm_8iy;
453         pps->scaling_list[CQM_8PY+4] = param->cqm_8py;
454         for( int i = 0; i < 6; i++ )
455             for( int j = 0; j < (i < 4 ? 16 : 64); j++ )
456                 if( pps->scaling_list[i][j] == 0 )
457                     pps->scaling_list[i] = x264_cqm_jvt[i];
458         break;
459     }
460 }
461
462 void x264_pps_write( bs_t *s, x264_pps_t *pps )
463 {
464     bs_realign( s );
465     bs_write_ue( s, pps->i_id );
466     bs_write_ue( s, pps->i_sps_id );
467
468     bs_write1( s, pps->b_cabac );
469     bs_write1( s, pps->b_pic_order );
470     bs_write_ue( s, pps->i_num_slice_groups - 1 );
471
472     bs_write_ue( s, pps->i_num_ref_idx_l0_default_active - 1 );
473     bs_write_ue( s, pps->i_num_ref_idx_l1_default_active - 1 );
474     bs_write1( s, pps->b_weighted_pred );
475     bs_write( s, 2, pps->b_weighted_bipred );
476
477     bs_write_se( s, pps->i_pic_init_qp - 26 - QP_BD_OFFSET );
478     bs_write_se( s, pps->i_pic_init_qs - 26 - QP_BD_OFFSET );
479     bs_write_se( s, pps->i_chroma_qp_index_offset );
480
481     bs_write1( s, pps->b_deblocking_filter_control );
482     bs_write1( s, pps->b_constrained_intra_pred );
483     bs_write1( s, pps->b_redundant_pic_cnt );
484
485     if( pps->b_transform_8x8_mode || pps->i_cqm_preset != X264_CQM_FLAT )
486     {
487         bs_write1( s, pps->b_transform_8x8_mode );
488         bs_write1( s, (pps->i_cqm_preset != X264_CQM_FLAT) );
489         if( pps->i_cqm_preset != X264_CQM_FLAT )
490         {
491             scaling_list_write( s, pps, CQM_4IY );
492             scaling_list_write( s, pps, CQM_4IC );
493             bs_write1( s, 0 ); // Cr = Cb
494             scaling_list_write( s, pps, CQM_4PY );
495             scaling_list_write( s, pps, CQM_4PC );
496             bs_write1( s, 0 ); // Cr = Cb
497             if( pps->b_transform_8x8_mode )
498             {
499                 scaling_list_write( s, pps, CQM_8IY+4 );
500                 scaling_list_write( s, pps, CQM_8PY+4 );
501             }
502         }
503         bs_write_se( s, pps->i_chroma_qp_index_offset );
504     }
505
506     bs_rbsp_trailing( s );
507     bs_flush( s );
508 }
509
510 void x264_sei_recovery_point_write( x264_t *h, bs_t *s, int recovery_frame_cnt )
511 {
512     bs_t q;
513     uint8_t tmp_buf[100];
514     bs_init( &q, tmp_buf, 100 );
515
516     bs_realign( &q );
517
518     bs_write_ue( &q, recovery_frame_cnt ); // recovery_frame_cnt
519     bs_write1( &q, 1 );   //exact_match_flag 1
520     bs_write1( &q, 0 );   //broken_link_flag 0
521     bs_write( &q, 2, 0 ); //changing_slice_group 0
522
523     bs_align_10( &q );
524     bs_flush( &q );
525
526     x264_sei_write( s, tmp_buf, bs_pos( &q ) / 8, SEI_RECOVERY_POINT );
527 }
528
529 int x264_sei_version_write( x264_t *h, bs_t *s )
530 {
531     // random ID number generated according to ISO-11578
532     static const uint8_t uuid[16] =
533     {
534         0xdc, 0x45, 0xe9, 0xbd, 0xe6, 0xd9, 0x48, 0xb7,
535         0x96, 0x2c, 0xd8, 0x20, 0xd9, 0x23, 0xee, 0xef
536     };
537     char *opts = x264_param2string( &h->param, 0 );
538     char *payload;
539     int length;
540
541     if( !opts )
542         return -1;
543     CHECKED_MALLOC( payload, 200 + strlen( opts ) );
544
545     memcpy( payload, uuid, 16 );
546     sprintf( payload+16, "x264 - core %d%s - H.264/MPEG-4 AVC codec - "
547              "Copy%s 2003-2011 - http://www.videolan.org/x264.html - options: %s",
548              X264_BUILD, X264_VERSION, HAVE_GPL?"left":"right", opts );
549     length = strlen(payload)+1;
550
551     x264_sei_write( s, (uint8_t *)payload, length, SEI_USER_DATA_UNREGISTERED );
552
553     x264_free( opts );
554     x264_free( payload );
555     return 0;
556 fail:
557     x264_free( opts );
558     return -1;
559 }
560
561 void x264_sei_buffering_period_write( x264_t *h, bs_t *s )
562 {
563     x264_sps_t *sps = h->sps;
564     bs_t q;
565     uint8_t tmp_buf[100];
566     bs_init( &q, tmp_buf, 100 );
567
568     bs_realign( &q );
569     bs_write_ue( &q, sps->i_id );
570
571     if( sps->vui.b_nal_hrd_parameters_present )
572     {
573         bs_write( &q, sps->vui.hrd.i_initial_cpb_removal_delay_length, h->initial_cpb_removal_delay );
574         bs_write( &q, sps->vui.hrd.i_initial_cpb_removal_delay_length, h->initial_cpb_removal_delay_offset );
575     }
576
577     bs_align_10( &q );
578     bs_flush( &q );
579
580     x264_sei_write( s, tmp_buf, bs_pos( &q ) / 8, SEI_BUFFERING_PERIOD );
581 }
582
583 void x264_sei_pic_timing_write( x264_t *h, bs_t *s )
584 {
585     x264_sps_t *sps = h->sps;
586     bs_t q;
587     uint8_t tmp_buf[100];
588     bs_init( &q, tmp_buf, 100 );
589
590     bs_realign( &q );
591
592     if( sps->vui.b_nal_hrd_parameters_present || sps->vui.b_vcl_hrd_parameters_present )
593     {
594         bs_write( &q, sps->vui.hrd.i_cpb_removal_delay_length, h->fenc->i_cpb_delay - h->i_cpb_delay_pir_offset );
595         bs_write( &q, sps->vui.hrd.i_dpb_output_delay_length, h->fenc->i_dpb_output_delay );
596     }
597
598     if( sps->vui.b_pic_struct_present )
599     {
600         bs_write( &q, 4, h->fenc->i_pic_struct-1 ); // We use index 0 for "Auto"
601
602         // These clock timestamps are not standardised so we don't set them
603         // They could be time of origin, capture or alternative ideal display
604         for( int i = 0; i < num_clock_ts[h->fenc->i_pic_struct]; i++ )
605             bs_write1( &q, 0 ); // clock_timestamp_flag
606     }
607
608     bs_align_10( &q );
609     bs_flush( &q );
610
611     x264_sei_write( s, tmp_buf, bs_pos( &q ) / 8, SEI_PIC_TIMING );
612 }
613
614 void x264_sei_frame_packing_write( x264_t *h, bs_t *s )
615 {
616     bs_t q;
617     uint8_t tmp_buf[100];
618     bs_init( &q, tmp_buf, 100 );
619
620     bs_realign( &q );
621
622     bs_write_ue( &q, 0 );                         // frame_packing_arrangement_id
623     bs_write1( &q, 0 );                           // frame_packing_arrangement_cancel_flag
624     bs_write ( &q, 7, h->param.i_frame_packing ); // frame_packing_arrangement_type
625     bs_write1( &q, 0 );                           // quincunx_sampling_flag
626
627     // 0: views are unrelated, 1: left view is on the left, 2: left view is on the right
628     bs_write ( &q, 6, 1 );                        // content_interpretation_type
629
630     bs_write1( &q, 0 );                           // spatial_flipping_flag
631     bs_write1( &q, 0 );                           // frame0_flipped_flag
632     bs_write1( &q, 0 );                           // field_views_flag
633     bs_write1( &q, h->param.i_frame_packing == 5 && !(h->fenc->i_frame&1) ); // current_frame_is_frame0_flag
634     bs_write1( &q, 0 );                           // frame0_self_contained_flag
635     bs_write1( &q, 0 );                           // frame1_self_contained_flag
636     if ( /* quincunx_sampling_flag == 0 && */ h->param.i_frame_packing != 5 )
637     {
638         bs_write( &q, 4, 0 );                     // frame0_grid_position_x
639         bs_write( &q, 4, 0 );                     // frame0_grid_position_y
640         bs_write( &q, 4, 0 );                     // frame1_grid_position_x
641         bs_write( &q, 4, 0 );                     // frame1_grid_position_y
642     }
643     bs_write( &q, 8, 0 );                         // frame_packing_arrangement_reserved_byte
644     bs_write_ue( &q, 1 );                         // frame_packing_arrangement_repetition_period
645     bs_write1( &q, 0 );                           // frame_packing_arrangement_extension_flag
646
647     bs_align_10( &q );
648     bs_flush( &q );
649
650     x264_sei_write( s, tmp_buf, bs_pos( &q ) / 8, SEI_FRAME_PACKING );
651 }
652
653 void x264_filler_write( x264_t *h, bs_t *s, int filler )
654 {
655     bs_realign( s );
656
657     for( int i = 0; i < filler; i++ )
658         bs_write( s, 8, 0xff );
659
660     bs_rbsp_trailing( s );
661     bs_flush( s );
662 }
663
664 void x264_sei_dec_ref_pic_marking_write( x264_t *h, bs_t *s )
665 {
666     x264_slice_header_t *sh = &h->sh_backup;
667     bs_t q;
668     uint8_t tmp_buf[100];
669     bs_init( &q, tmp_buf, 100 );
670
671     bs_realign( &q );
672
673     /* We currently only use this for repeating B-refs, as required by Blu-ray. */
674     bs_write1( &q, 0 );                 //original_idr_flag
675     bs_write_ue( &q, sh->i_frame_num ); //original_frame_num
676     if( !h->sps->b_frame_mbs_only )
677         bs_write1( &q, 0 );             //original_field_pic_flag
678
679     bs_write1( &q, sh->i_mmco_command_count > 0 );
680     if( sh->i_mmco_command_count > 0 )
681     {
682         for( int i = 0; i < sh->i_mmco_command_count; i++ )
683         {
684             bs_write_ue( &q, 1 );
685             bs_write_ue( &q, sh->mmco[i].i_difference_of_pic_nums - 1 );
686         }
687         bs_write_ue( &q, 0 );
688     }
689
690     bs_align_10( &q );
691     bs_flush( &q );
692
693     x264_sei_write( s, tmp_buf, bs_pos( &q ) / 8, SEI_DEC_REF_PIC_MARKING );
694 }
695
696 const x264_level_t x264_levels[] =
697 {
698     { 10,   1485,    99,   152064,     64,    175,  64, 64,  0, 2, 0, 0, 1 },
699     {  9,   1485,    99,   152064,    128,    350,  64, 64,  0, 2, 0, 0, 1 }, /* "1b" */
700     { 11,   3000,   396,   345600,    192,    500, 128, 64,  0, 2, 0, 0, 1 },
701     { 12,   6000,   396,   912384,    384,   1000, 128, 64,  0, 2, 0, 0, 1 },
702     { 13,  11880,   396,   912384,    768,   2000, 128, 64,  0, 2, 0, 0, 1 },
703     { 20,  11880,   396,   912384,   2000,   2000, 128, 64,  0, 2, 0, 0, 1 },
704     { 21,  19800,   792,  1824768,   4000,   4000, 256, 64,  0, 2, 0, 0, 0 },
705     { 22,  20250,  1620,  3110400,   4000,   4000, 256, 64,  0, 2, 0, 0, 0 },
706     { 30,  40500,  1620,  3110400,  10000,  10000, 256, 32, 22, 2, 0, 1, 0 },
707     { 31, 108000,  3600,  6912000,  14000,  14000, 512, 16, 60, 4, 1, 1, 0 },
708     { 32, 216000,  5120,  7864320,  20000,  20000, 512, 16, 60, 4, 1, 1, 0 },
709     { 40, 245760,  8192, 12582912,  20000,  25000, 512, 16, 60, 4, 1, 1, 0 },
710     { 41, 245760,  8192, 12582912,  50000,  62500, 512, 16, 24, 2, 1, 1, 0 },
711     { 42, 522240,  8704, 13369344,  50000,  62500, 512, 16, 24, 2, 1, 1, 1 },
712     { 50, 589824, 22080, 42393600, 135000, 135000, 512, 16, 24, 2, 1, 1, 1 },
713     { 51, 983040, 36864, 70778880, 240000, 240000, 512, 16, 24, 2, 1, 1, 1 },
714     { 0 }
715 };
716
717 #define ERROR(...)\
718 {\
719     if( verbose )\
720         x264_log( h, X264_LOG_WARNING, __VA_ARGS__ );\
721     ret = 1;\
722 }
723
724 int x264_validate_levels( x264_t *h, int verbose )
725 {
726     int ret = 0;
727     int mbs = h->sps->i_mb_width * h->sps->i_mb_height;
728     int dpb = mbs * 384 * h->sps->vui.i_max_dec_frame_buffering;
729     int cbp_factor = h->sps->i_profile_idc==PROFILE_HIGH10 ? 12 :
730                      h->sps->i_profile_idc==PROFILE_HIGH ? 5 : 4;
731
732     const x264_level_t *l = x264_levels;
733     while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
734         l++;
735
736     if( l->frame_size < mbs
737         || l->frame_size*8 < h->sps->i_mb_width * h->sps->i_mb_width
738         || l->frame_size*8 < h->sps->i_mb_height * h->sps->i_mb_height )
739         ERROR( "frame MB size (%dx%d) > level limit (%d)\n",
740                h->sps->i_mb_width, h->sps->i_mb_height, l->frame_size );
741     if( dpb > l->dpb )
742         ERROR( "DPB size (%d frames, %d bytes) > level limit (%d frames, %d bytes)\n",
743                 h->sps->vui.i_max_dec_frame_buffering, dpb, (int)(l->dpb / (384*mbs)), l->dpb );
744
745 #define CHECK( name, limit, val ) \
746     if( (val) > (limit) ) \
747         ERROR( name " (%d) > level limit (%d)\n", (int)(val), (limit) );
748
749     CHECK( "VBV bitrate", (l->bitrate * cbp_factor) / 4, h->param.rc.i_vbv_max_bitrate );
750     CHECK( "VBV buffer", (l->cpb * cbp_factor) / 4, h->param.rc.i_vbv_buffer_size );
751     CHECK( "MV range", l->mv_range, h->param.analyse.i_mv_range );
752     CHECK( "interlaced", !l->frame_only, h->param.b_interlaced );
753     CHECK( "fake interlaced", !l->frame_only, h->param.b_fake_interlaced );
754
755     if( h->param.i_fps_den > 0 )
756         CHECK( "MB rate", l->mbps, (int64_t)mbs * h->param.i_fps_num / h->param.i_fps_den );
757
758     /* TODO check the rest of the limits */
759     return ret;
760 }