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