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