codecparsers: {h264,h265}bitwriter: Remove redundant condition checks
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-bad / gst-libs / gst / codecparsers / gsth264bitwriter.c
1 /* GStreamer
2  *  Copyright (C) 2020 Intel Corporation
3  *     Author: He Junyan <junyan.he@intel.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the0
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include "gsth264bitwriter.h"
26 #include <gst/codecparsers/nalutils.h>
27 #include <gst/base/gstbitwriter.h>
28
29 /********************************  Utils ********************************/
30 #define SIGNED(val)    (2 * ABS(val) - ((val) > 0))
31
32 /* Write an unsigned integer Exp-Golomb-coded syntax element. i.e. ue(v) */
33 static gboolean
34 _bs_write_ue (GstBitWriter * bs, guint32 value)
35 {
36   guint32 size_in_bits = 0;
37   guint32 tmp_value = ++value;
38
39   while (tmp_value) {
40     ++size_in_bits;
41     tmp_value >>= 1;
42   }
43   if (size_in_bits > 1
44       && !gst_bit_writer_put_bits_uint32 (bs, 0, size_in_bits - 1))
45     return FALSE;
46   if (!gst_bit_writer_put_bits_uint32 (bs, value, size_in_bits))
47     return FALSE;
48   return TRUE;
49 }
50
51 #define WRITE_BITS_UNCHECK(bw, val, nbits)                                    \
52   (nbits <= 8 ? gst_bit_writer_put_bits_uint8 (bw, val, nbits) :              \
53    (nbits <= 16 ? gst_bit_writer_put_bits_uint16 (bw, val, nbits) :           \
54     (nbits <= 32 ? gst_bit_writer_put_bits_uint32 (bw, val, nbits) :          \
55      FALSE)))
56
57 #define WRITE_BITS(bw, val, nbits)                                            \
58   if (!WRITE_BITS_UNCHECK (bw, val, nbits)) {                                 \
59     g_warning ("Unsupported bit size: %u", nbits);                            \
60     have_space = FALSE;                                                       \
61     goto error;                                                               \
62   }
63
64 #define WRITE_UE_UNCHECK(bw, val)  _bs_write_ue (bw, val)
65
66 #ifdef WRITE_UE
67 #undef WRITE_UE
68 #endif
69 #define WRITE_UE(bw, val)                                                     \
70   if (!(have_space = WRITE_UE_UNCHECK (bw, val)))                             \
71     goto error;                                                               \
72
73 #define WRITE_UE_MAX(bw, val, max)                                            \
74   if ((guint32) val > (max) || !(have_space = WRITE_UE_UNCHECK (bw, val)))    \
75     goto error;
76
77 #define WRITE_SE(bw, val) WRITE_UE (bw, SIGNED (val))
78
79 #define WRITE_SE_RANGE(bw, val, min, max)                                     \
80   if (val > max || val < min ||                                               \
81       !(have_space = WRITE_UE_UNCHECK (bw, SIGNED (val))))                    \
82     goto error;
83
84 #define WRITE_BYTES_UNCHECK(bw, ptr, nbytes)                                  \
85   gst_bit_writer_put_bytes(bw, ptr, nbytes)
86
87 #ifdef WRITE_BYTES
88 #undef WRITE_BYTES
89 #endif
90 #define WRITE_BYTES(bw, ptr, nbytes)                                          \
91   if (!(have_space = WRITE_BYTES_UNCHECK (bw, ptr, nbytes)))                  \
92     goto error;
93
94 /*****************************  End of Utils ****************************/
95
96 /**** Default scaling_lists according to Table 7-2 *****/
97 static const guint8 default_4x4_intra[16] = {
98   6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32,
99   32, 37, 37, 42
100 };
101
102 static const guint8 default_4x4_inter[16] = {
103   10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27,
104   27, 30, 30, 34
105 };
106
107 static const guint8 default_8x8_intra[64] = {
108   6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18,
109   18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27,
110   27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, 31, 33,
111   33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42
112 };
113
114 static const guint8 default_8x8_inter[64] = {
115   9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19,
116   19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 24, 24, 24,
117   24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 28,
118   28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35
119 };
120
121 static gboolean
122 _h264_bit_writer_scaling_list (GstBitWriter * bw, gboolean * space,
123     const guint8 scaling_lists_4x4[6][16],
124     const guint8 scaling_lists_8x8[6][64], const guint8 fallback_4x4_inter[16],
125     const guint8 fallback_4x4_intra[16], const guint8 fallback_8x8_inter[64],
126     const guint8 fallback_8x8_intra[64], guint8 n_lists)
127 {
128   gboolean have_space = TRUE;
129   guint i, j;
130
131   const guint8 *default_lists[12] = {
132     fallback_4x4_intra, fallback_4x4_intra, fallback_4x4_intra,
133     fallback_4x4_inter, fallback_4x4_inter, fallback_4x4_inter,
134     fallback_8x8_intra, fallback_8x8_inter,
135     fallback_8x8_intra, fallback_8x8_inter,
136     fallback_8x8_intra, fallback_8x8_inter
137   };
138
139   GST_DEBUG ("writing scaling lists");
140
141   for (i = 0; i < 12; i++) {
142     if (i < n_lists) {
143       guint8 scaling_list_present_flag = FALSE;
144       const guint8 *scaling_list;
145       guint size;
146
147       if (i < 6) {
148         scaling_list = scaling_lists_4x4[i];
149         size = 16;
150       } else {
151         scaling_list = scaling_lists_8x8[i - 6];
152         size = 64;
153       }
154
155       if (memcmp (scaling_list, default_lists[i], size))
156         scaling_list_present_flag = TRUE;
157
158       WRITE_BITS (bw, scaling_list_present_flag, 1);
159       if (scaling_list_present_flag) {
160         guint8 last_scale, next_scale;
161         gint8 delta_scale;
162
163         for (j = 0; j < size; j++) {
164           last_scale = next_scale = 8;
165
166           for (j = 0; j < size; j++) {
167             if (next_scale != 0) {
168               delta_scale = (gint8) (scaling_list[j] - last_scale);
169
170               WRITE_SE (bw, delta_scale);
171
172               next_scale = scaling_list[j];
173             }
174             last_scale = (next_scale == 0) ? last_scale : next_scale;
175           }
176         }
177       }
178     }
179   }
180
181   *space = TRUE;
182   return TRUE;
183
184 error:
185   GST_WARNING ("error to write scaling lists");
186
187   *space = have_space;
188   return FALSE;
189 }
190
191 static gboolean
192 _h264_bit_writer_hrd_parameters (const GstH264HRDParams * hrd,
193     GstBitWriter * bw, gboolean * space)
194 {
195   gboolean have_space = TRUE;
196   guint sched_sel_idx;
197
198   GST_DEBUG ("writing \"HRD Parameters\"");
199
200   WRITE_UE_MAX (bw, hrd->cpb_cnt_minus1, 31);
201   WRITE_BITS (bw, hrd->bit_rate_scale, 4);
202   WRITE_BITS (bw, hrd->cpb_size_scale, 4);
203
204   for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1; sched_sel_idx++) {
205     WRITE_UE (bw, hrd->bit_rate_value_minus1[sched_sel_idx]);
206     WRITE_UE (bw, hrd->cpb_size_value_minus1[sched_sel_idx]);
207     WRITE_BITS (bw, hrd->cbr_flag[sched_sel_idx], 1);
208   }
209
210   WRITE_BITS (bw, hrd->initial_cpb_removal_delay_length_minus1, 5);
211   WRITE_BITS (bw, hrd->cpb_removal_delay_length_minus1, 5);
212   WRITE_BITS (bw, hrd->dpb_output_delay_length_minus1, 5);
213   WRITE_BITS (bw, hrd->time_offset_length, 5);
214
215   *space = TRUE;
216   return TRUE;
217
218 error:
219   GST_WARNING ("error to write \"HRD Parameters\"");
220
221   *space = have_space;
222   return FALSE;
223 }
224
225 #define EXTENDED_SAR 255
226
227 static gboolean
228 _h264_bit_writer_vui_parameters (const GstH264SPS * sps, GstBitWriter * bw,
229     gboolean * space)
230 {
231   gboolean have_space = TRUE;
232   const GstH264VUIParams *vui = &sps->vui_parameters;
233
234   GST_DEBUG ("writing \"VUI Parameters\"");
235
236   WRITE_BITS (bw, vui->aspect_ratio_info_present_flag, 1);
237   if (vui->aspect_ratio_info_present_flag) {
238     WRITE_BITS (bw, vui->aspect_ratio_idc, 8);
239     if (vui->aspect_ratio_idc == EXTENDED_SAR) {
240       WRITE_BITS (bw, vui->sar_width, 16);
241       WRITE_BITS (bw, vui->sar_height, 16);
242     }
243   }
244
245   WRITE_BITS (bw, vui->overscan_info_present_flag, 1);
246   if (vui->overscan_info_present_flag)
247     WRITE_BITS (bw, vui->overscan_appropriate_flag, 1);
248
249   WRITE_BITS (bw, vui->video_signal_type_present_flag, 1);
250   if (vui->video_signal_type_present_flag) {
251     WRITE_BITS (bw, vui->video_format, 3);
252     WRITE_BITS (bw, vui->video_full_range_flag, 1);
253     WRITE_BITS (bw, vui->colour_description_present_flag, 1);
254     if (vui->colour_description_present_flag) {
255       WRITE_BITS (bw, vui->colour_primaries, 8);
256       WRITE_BITS (bw, vui->transfer_characteristics, 8);
257       WRITE_BITS (bw, vui->matrix_coefficients, 8);
258     }
259   }
260
261   WRITE_BITS (bw, vui->chroma_loc_info_present_flag, 1);
262   if (vui->chroma_loc_info_present_flag) {
263     WRITE_UE_MAX (bw, vui->chroma_sample_loc_type_top_field, 5);
264     WRITE_UE_MAX (bw, vui->chroma_sample_loc_type_bottom_field, 5);
265   }
266
267   WRITE_BITS (bw, vui->timing_info_present_flag, 1);
268   if (vui->timing_info_present_flag) {
269     WRITE_BITS (bw, vui->num_units_in_tick, 32);
270     if (vui->num_units_in_tick == 0)
271       GST_WARNING ("num_units_in_tick = 0 write to stream "
272           "(incompliant to H.264 E.2.1).");
273
274     WRITE_BITS (bw, vui->time_scale, 32);
275     if (vui->time_scale == 0)
276       GST_WARNING ("time_scale = 0 write to stream "
277           "(incompliant to H.264 E.2.1).");
278
279     WRITE_BITS (bw, vui->fixed_frame_rate_flag, 1);
280   }
281
282   WRITE_BITS (bw, vui->nal_hrd_parameters_present_flag, 1);
283   if (vui->nal_hrd_parameters_present_flag) {
284     if (!_h264_bit_writer_hrd_parameters (&vui->nal_hrd_parameters, bw,
285             &have_space))
286       goto error;
287   }
288
289   WRITE_BITS (bw, vui->vcl_hrd_parameters_present_flag, 1);
290   if (vui->vcl_hrd_parameters_present_flag) {
291     if (!_h264_bit_writer_hrd_parameters (&vui->vcl_hrd_parameters, bw,
292             &have_space))
293       goto error;
294   }
295
296   if (vui->nal_hrd_parameters_present_flag ||
297       vui->vcl_hrd_parameters_present_flag)
298     WRITE_BITS (bw, vui->low_delay_hrd_flag, 1);
299
300   WRITE_BITS (bw, vui->pic_struct_present_flag, 1);
301   WRITE_BITS (bw, vui->bitstream_restriction_flag, 1);
302   if (vui->bitstream_restriction_flag) {
303     WRITE_BITS (bw, vui->motion_vectors_over_pic_boundaries_flag, 1);
304     WRITE_UE (bw, vui->max_bytes_per_pic_denom);
305     WRITE_UE_MAX (bw, vui->max_bits_per_mb_denom, 16);
306     WRITE_UE_MAX (bw, vui->log2_max_mv_length_horizontal, 16);
307     WRITE_UE_MAX (bw, vui->log2_max_mv_length_vertical, 16);
308     WRITE_UE (bw, vui->num_reorder_frames);
309     WRITE_UE (bw, vui->max_dec_frame_buffering);
310   }
311
312   *space = TRUE;
313   return TRUE;
314
315 error:
316   GST_WARNING ("error to write \"VUI Parameters\"");
317
318   *space = have_space;
319   return FALSE;
320 }
321
322 static gboolean
323 _h264_bit_writer_sps (const GstH264SPS * sps, GstBitWriter * bw,
324     gboolean * space)
325 {
326   gboolean have_space = TRUE;
327
328   GST_DEBUG ("writing SPS");
329
330   WRITE_BITS (bw, sps->profile_idc, 8);
331   WRITE_BITS (bw, sps->constraint_set0_flag, 1);
332   WRITE_BITS (bw, sps->constraint_set1_flag, 1);
333   WRITE_BITS (bw, sps->constraint_set2_flag, 1);
334   WRITE_BITS (bw, sps->constraint_set3_flag, 1);
335   WRITE_BITS (bw, sps->constraint_set4_flag, 1);
336   WRITE_BITS (bw, sps->constraint_set5_flag, 1);
337   /* reserved_zero_2bits */
338   WRITE_BITS (bw, 0, 2);
339
340   WRITE_BITS (bw, sps->level_idc, 8);
341
342   WRITE_UE_MAX (bw, sps->id, GST_H264_MAX_SPS_COUNT - 1);
343
344   if (sps->profile_idc == 100 || sps->profile_idc == 110 ||
345       sps->profile_idc == 122 || sps->profile_idc == 244 ||
346       sps->profile_idc == 44 || sps->profile_idc == 83 ||
347       sps->profile_idc == 86 || sps->profile_idc == 118 ||
348       sps->profile_idc == 128 || sps->profile_idc == 138 ||
349       sps->profile_idc == 139 || sps->profile_idc == 134 ||
350       sps->profile_idc == 135) {
351     WRITE_UE_MAX (bw, sps->chroma_format_idc, 3);
352     if (sps->chroma_format_idc == 3)
353       WRITE_BITS (bw, sps->separate_colour_plane_flag, 1);
354
355     WRITE_UE_MAX (bw, sps->bit_depth_luma_minus8, 6);
356     WRITE_UE_MAX (bw, sps->bit_depth_chroma_minus8, 6);
357     WRITE_BITS (bw, sps->qpprime_y_zero_transform_bypass_flag, 1);
358
359     WRITE_BITS (bw, sps->scaling_matrix_present_flag, 1);
360     if (sps->scaling_matrix_present_flag) {
361       guint8 n_lists;
362
363       n_lists = (sps->chroma_format_idc != 3) ? 8 : 12;
364       if (!_h264_bit_writer_scaling_list (bw, &have_space,
365               sps->scaling_lists_4x4, sps->scaling_lists_8x8,
366               default_4x4_inter, default_4x4_intra,
367               default_8x8_inter, default_8x8_intra, n_lists))
368         goto error;
369     }
370   }
371
372   WRITE_UE_MAX (bw, sps->log2_max_frame_num_minus4, 12);
373
374   WRITE_UE_MAX (bw, sps->pic_order_cnt_type, 2);
375   if (sps->pic_order_cnt_type == 0) {
376     WRITE_UE_MAX (bw, sps->log2_max_pic_order_cnt_lsb_minus4, 12);
377   } else if (sps->pic_order_cnt_type == 1) {
378     guint i;
379
380     WRITE_BITS (bw, sps->delta_pic_order_always_zero_flag, 1);
381     WRITE_SE (bw, sps->offset_for_non_ref_pic);
382     WRITE_SE (bw, sps->offset_for_top_to_bottom_field);
383     WRITE_UE_MAX (bw, sps->num_ref_frames_in_pic_order_cnt_cycle, 255);
384
385     for (i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++)
386       WRITE_SE (bw, sps->offset_for_ref_frame[i]);
387   }
388
389   WRITE_UE (bw, sps->num_ref_frames);
390   WRITE_BITS (bw, sps->gaps_in_frame_num_value_allowed_flag, 1);
391   WRITE_UE (bw, sps->pic_width_in_mbs_minus1);
392   WRITE_UE (bw, sps->pic_height_in_map_units_minus1);
393   WRITE_BITS (bw, sps->frame_mbs_only_flag, 1);
394
395   if (!sps->frame_mbs_only_flag)
396     WRITE_BITS (bw, sps->mb_adaptive_frame_field_flag, 1);
397
398   WRITE_BITS (bw, sps->direct_8x8_inference_flag, 1);
399   WRITE_BITS (bw, sps->frame_cropping_flag, 1);
400   if (sps->frame_cropping_flag) {
401     WRITE_UE (bw, sps->frame_crop_left_offset);
402     WRITE_UE (bw, sps->frame_crop_right_offset);
403     WRITE_UE (bw, sps->frame_crop_top_offset);
404     WRITE_UE (bw, sps->frame_crop_bottom_offset);
405   }
406
407   WRITE_BITS (bw, sps->vui_parameters_present_flag, 1);
408   if (sps->vui_parameters_present_flag)
409     if (!_h264_bit_writer_vui_parameters (sps, bw, &have_space))
410       goto error;
411
412   *space = TRUE;
413   return TRUE;
414
415 error:
416   GST_WARNING ("error to write sps");
417
418   *space = have_space;
419   return FALSE;
420 }
421
422 /**
423  * gst_h264_bit_writer_sps:
424  * @sps: the sps of #GstH264SPS to write
425  * @start_code: whether adding the nal start code
426  * @data: (out): the bit stream generated by the sps
427  * @size: (inout): the size in bytes of the input and output
428  *
429  * Generating the according h264 bit stream by providing the sps.
430  *
431  * Returns: a #GstH264BitWriterResult
432  *
433  * Since: 1.22
434  **/
435 GstH264BitWriterResult
436 gst_h264_bit_writer_sps (const GstH264SPS * sps, gboolean start_code,
437     guint8 * data, guint * size)
438 {
439   gboolean have_space = TRUE;
440   GstBitWriter bw;
441
442   g_return_val_if_fail (sps != NULL, GST_H264_BIT_WRITER_ERROR);
443   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
444   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
445   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
446
447   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
448
449   if (start_code)
450     WRITE_BITS (&bw, 0x00000001, 32);
451
452   /* nal header */
453   /* forbidden_zero_bit */
454   WRITE_BITS (&bw, 0, 1);
455   /* nal_ref_idc */
456   WRITE_BITS (&bw, 1, 2);
457   /* nal_unit_type */
458   WRITE_BITS (&bw, GST_H264_NAL_SPS, 5);
459
460   if (!_h264_bit_writer_sps (sps, &bw, &have_space))
461     goto error;
462
463   /* Add trailings. */
464   WRITE_BITS (&bw, 1, 1);
465   if (!gst_bit_writer_align_bytes (&bw, 0)) {
466     have_space = FALSE;
467     goto error;
468   }
469
470   *size = (gst_bit_writer_get_size (&bw)) / 8;
471   gst_bit_writer_reset (&bw);
472
473   return GST_H264_BIT_WRITER_OK;
474
475 error:
476   gst_bit_writer_reset (&bw);
477   *size = 0;
478
479   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
480       GST_H264_BIT_WRITER_NO_MORE_SPACE;
481 }
482
483 static gboolean
484 _h264_bit_writer_pps (const GstH264PPS * pps, GstBitWriter * bw,
485     gboolean * space)
486 {
487   gboolean have_space = TRUE;
488   gint qp_bd_offset;
489
490   GST_DEBUG ("writing SPS");
491
492   qp_bd_offset = 6 * (pps->sequence->bit_depth_luma_minus8 +
493       pps->sequence->separate_colour_plane_flag);
494
495   WRITE_UE_MAX (bw, pps->id, GST_H264_MAX_PPS_COUNT - 1);
496   WRITE_UE_MAX (bw, pps->sequence->id, GST_H264_MAX_SPS_COUNT - 1);
497
498   WRITE_BITS (bw, pps->entropy_coding_mode_flag, 1);
499   WRITE_BITS (bw, pps->pic_order_present_flag, 1);
500
501   WRITE_UE_MAX (bw, pps->num_slice_groups_minus1, 7);
502   if (pps->num_slice_groups_minus1 > 0) {
503     WRITE_UE_MAX (bw, pps->slice_group_map_type, 6);
504
505     if (pps->slice_group_map_type == 0) {
506       gint i;
507
508       for (i = 0; i <= pps->num_slice_groups_minus1; i++)
509         WRITE_UE (bw, pps->run_length_minus1[i]);
510     } else if (pps->slice_group_map_type == 2) {
511       gint i;
512
513       for (i = 0; i < pps->num_slice_groups_minus1; i++) {
514         WRITE_UE (bw, pps->top_left[i]);
515         WRITE_UE (bw, pps->bottom_right[i]);
516       }
517     } else if (pps->slice_group_map_type >= 3 && pps->slice_group_map_type <= 5) {
518       WRITE_BITS (bw, pps->slice_group_change_direction_flag, 1);
519       WRITE_UE (bw, pps->slice_group_change_rate_minus1);
520     } else if (pps->slice_group_map_type == 6) {
521       gint bits;
522       gint i;
523
524       WRITE_UE (bw, pps->pic_size_in_map_units_minus1);
525       bits = g_bit_storage (pps->num_slice_groups_minus1);
526
527       g_assert (pps->slice_group_id);
528       for (i = 0; i <= pps->pic_size_in_map_units_minus1; i++)
529         WRITE_BITS (bw, pps->slice_group_id[i], bits);
530     }
531   }
532
533   WRITE_UE_MAX (bw, pps->num_ref_idx_l0_active_minus1, 31);
534   WRITE_UE_MAX (bw, pps->num_ref_idx_l1_active_minus1, 31);
535   WRITE_BITS (bw, pps->weighted_pred_flag, 1);
536   WRITE_BITS (bw, pps->weighted_bipred_idc, 2);
537   WRITE_SE_RANGE (bw, pps->pic_init_qp_minus26, -(26 + qp_bd_offset), 25);
538   WRITE_SE_RANGE (bw, pps->pic_init_qs_minus26, -26, 25);
539   WRITE_SE_RANGE (bw, pps->chroma_qp_index_offset, -12, 12);
540
541   WRITE_BITS (bw, pps->deblocking_filter_control_present_flag, 1);
542   WRITE_BITS (bw, pps->constrained_intra_pred_flag, 1);
543   WRITE_BITS (bw, pps->redundant_pic_cnt_present_flag, 1);
544
545   /* A.2.1 Baseline profile, A.2.2 Main profile and
546      A.2.3 Extended profile:
547      The syntax elements transform_8x8_mode_flag,
548      pic_scaling_matrix_present_flag, second_chroma_qp_index_offset
549      shall not be present in picture parameter sets. */
550   if (pps->sequence->profile_idc == 66 ||
551       pps->sequence->profile_idc == 77 || pps->sequence->profile_idc == 88)
552     return TRUE;
553
554   WRITE_BITS (bw, pps->transform_8x8_mode_flag, 1);
555
556   WRITE_BITS (bw, pps->pic_scaling_matrix_present_flag, 1);
557
558   if (pps->pic_scaling_matrix_present_flag) {
559     guint8 n_lists;
560
561     n_lists = 6 + ((pps->sequence->chroma_format_idc != 3) ? 2 : 6) *
562         pps->transform_8x8_mode_flag;
563
564     if (pps->sequence->scaling_matrix_present_flag) {
565       if (!_h264_bit_writer_scaling_list (bw, &have_space,
566               pps->scaling_lists_4x4, pps->scaling_lists_8x8,
567               pps->sequence->scaling_lists_4x4[3],
568               pps->sequence->scaling_lists_4x4[0],
569               pps->sequence->scaling_lists_8x8[3],
570               pps->sequence->scaling_lists_8x8[0], n_lists))
571         goto error;
572     } else {
573       if (!_h264_bit_writer_scaling_list (bw, &have_space,
574               pps->scaling_lists_4x4, pps->scaling_lists_8x8,
575               default_4x4_inter, default_4x4_intra,
576               default_8x8_inter, default_8x8_intra, n_lists))
577         goto error;
578     }
579   }
580
581   WRITE_SE_RANGE (bw, ((gint) pps->second_chroma_qp_index_offset), -12, 12);
582
583   *space = TRUE;
584   return TRUE;
585
586 error:
587   GST_WARNING ("error to write pps");
588
589   *space = have_space;
590   return FALSE;
591 }
592
593 /**
594  * gst_h264_bit_writer_pps:
595  * @pps: the pps of #GstH264PPS to write
596  * @start_code: whether adding the nal start code
597  * @data: (out): the bit stream generated by the pps
598  * @size: (inout): the size in bytes of the input and output
599  *
600  * Generating the according h264 bit stream by providing the pps.
601  *
602  * Returns: a #GstH264BitWriterResult
603  *
604  * Since: 1.22
605  **/
606 GstH264BitWriterResult
607 gst_h264_bit_writer_pps (const GstH264PPS * pps, gboolean start_code,
608     guint8 * data, guint * size)
609 {
610   gboolean have_space = TRUE;
611   GstBitWriter bw;
612
613   g_return_val_if_fail (pps != NULL, GST_H264_BIT_WRITER_ERROR);
614   g_return_val_if_fail (pps->sequence != NULL, GST_H264_BIT_WRITER_ERROR);
615   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
616   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
617   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
618
619   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
620
621   if (start_code)
622     WRITE_BITS (&bw, 0x00000001, 32);
623
624   /* nal header */
625   /* forbidden_zero_bit */
626   WRITE_BITS (&bw, 0, 1);
627   /* nal_ref_idc */
628   WRITE_BITS (&bw, 1, 2);
629   /* nal_unit_type */
630   WRITE_BITS (&bw, GST_H264_NAL_PPS, 5);
631
632   if (!_h264_bit_writer_pps (pps, &bw, &have_space))
633     goto error;
634
635   /* Add trailings. */
636   WRITE_BITS (&bw, 1, 1);
637   if (!gst_bit_writer_align_bytes (&bw, 0)) {
638     have_space = FALSE;
639     goto error;
640   }
641
642   *size = (gst_bit_writer_get_size (&bw)) / 8;
643   gst_bit_writer_reset (&bw);
644   return GST_H264_BIT_WRITER_OK;
645
646 error:
647   gst_bit_writer_reset (&bw);
648   *size = 0;
649
650   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
651       GST_H264_BIT_WRITER_NO_MORE_SPACE;
652 }
653
654 static gboolean
655 _h264_slice_bit_writer_ref_pic_list_modification_1 (const GstH264SliceHdr *
656     slice, guint list, gboolean is_mvc, GstBitWriter * bw, gboolean * space)
657 {
658   gboolean have_space = TRUE;
659   const GstH264RefPicListModification *entries;
660   guint8 ref_pic_list_modification_flag = 0;
661   guint i;
662
663   if (list == 0) {
664     entries = slice->ref_pic_list_modification_l0;
665     ref_pic_list_modification_flag = slice->ref_pic_list_modification_flag_l0;
666   } else {
667     entries = slice->ref_pic_list_modification_l1;
668     ref_pic_list_modification_flag = slice->ref_pic_list_modification_flag_l1;
669   }
670
671   WRITE_BITS (bw, ref_pic_list_modification_flag, 1);
672   if (ref_pic_list_modification_flag) {
673     i = 0;
674     do {
675       g_assert (i < 32);
676
677       WRITE_UE (bw, entries[i].modification_of_pic_nums_idc);
678       if (entries[i].modification_of_pic_nums_idc == 0 ||
679           entries[i].modification_of_pic_nums_idc == 1) {
680         WRITE_UE_MAX (bw, entries[i].value.abs_diff_pic_num_minus1,
681             slice->max_pic_num - 1);
682       } else if (entries[i].modification_of_pic_nums_idc == 2) {
683         WRITE_UE (bw, entries[i].value.long_term_pic_num);
684       } else if (is_mvc && (entries[i].modification_of_pic_nums_idc == 4 ||
685               entries[i].modification_of_pic_nums_idc == 5)) {
686         WRITE_UE (bw, entries[i].value.abs_diff_view_idx_minus1);
687       }
688     } while (entries[i++].modification_of_pic_nums_idc != 3);
689   }
690
691   *space = TRUE;
692   return TRUE;
693
694 error:
695   GST_WARNING ("error to write \"Reference picture list %u modification\"",
696       list);
697
698   *space = have_space;
699   return FALSE;
700 }
701
702 static gboolean
703 _h264_slice_bit_writer_ref_pic_list_modification (const GstH264SliceHdr *
704     slice, gboolean is_mvc, GstBitWriter * bw, gboolean * space)
705 {
706   if (!GST_H264_IS_I_SLICE (slice) && !GST_H264_IS_SI_SLICE (slice)) {
707     if (!_h264_slice_bit_writer_ref_pic_list_modification_1 (slice, 0,
708             is_mvc, bw, space))
709       return FALSE;
710   }
711
712   if (GST_H264_IS_B_SLICE (slice)) {
713     if (!_h264_slice_bit_writer_ref_pic_list_modification_1 (slice, 1,
714             is_mvc, bw, space))
715       return FALSE;
716   }
717
718   *space = TRUE;
719   return TRUE;
720 }
721
722 static gboolean
723 _h264_slice_bit_writer_pred_weight_table (const GstH264SliceHdr * slice,
724     guint8 chroma_array_type, GstBitWriter * bw, gboolean * space)
725 {
726   gboolean have_space = TRUE;
727   const GstH264PredWeightTable *p;
728   gint i;
729   gint16 default_luma_weight, default_chroma_weight;
730
731   GST_DEBUG ("writing \"Prediction weight table\"");
732
733   p = &slice->pred_weight_table;
734   default_luma_weight = 1 << p->luma_log2_weight_denom;
735   default_chroma_weight = 1 << p->chroma_log2_weight_denom;
736
737   WRITE_UE_MAX (bw, p->luma_log2_weight_denom, 7);
738
739   if (chroma_array_type != 0)
740     WRITE_UE_MAX (bw, p->chroma_log2_weight_denom, 7);
741
742   for (i = 0; i <= slice->num_ref_idx_l0_active_minus1; i++) {
743     guint8 luma_weight_l0_flag = 0;
744
745     if (p->luma_weight_l0[i] != default_luma_weight ||
746         p->luma_offset_l0[i] != 0)
747       luma_weight_l0_flag = 1;
748
749     WRITE_BITS (bw, luma_weight_l0_flag, 1);
750     if (luma_weight_l0_flag) {
751       WRITE_SE_RANGE (bw, p->luma_weight_l0[i], -128, 127);
752       WRITE_SE_RANGE (bw, p->luma_offset_l0[i], -128, 127);
753     }
754     if (chroma_array_type != 0) {
755       guint8 chroma_weight_l0_flag = 0;
756       gint j;
757
758       for (j = 0; j < 2; j++) {
759         if (p->chroma_weight_l0[i][j] != default_chroma_weight ||
760             p->chroma_offset_l0[i][j] != 0)
761           chroma_weight_l0_flag = 1;
762       }
763
764       WRITE_BITS (bw, chroma_weight_l0_flag, 1);
765       if (chroma_weight_l0_flag) {
766         for (j = 0; j < 2; j++) {
767           WRITE_SE_RANGE (bw, p->chroma_weight_l0[i][j], -128, 127);
768           WRITE_SE_RANGE (bw, p->chroma_offset_l0[i][j], -128, 127);
769         }
770       }
771     }
772   }
773
774   if (GST_H264_IS_B_SLICE (slice)) {
775     for (i = 0; i <= slice->num_ref_idx_l1_active_minus1; i++) {
776       guint8 luma_weight_l1_flag = 0;
777
778       if (p->luma_weight_l1[i] != default_luma_weight ||
779           p->luma_offset_l1[i] != 0)
780         luma_weight_l1_flag = 1;
781
782       WRITE_BITS (bw, luma_weight_l1_flag, 1);
783       if (luma_weight_l1_flag) {
784         WRITE_SE_RANGE (bw, p->luma_weight_l1[i], -128, 127);
785         WRITE_SE_RANGE (bw, p->luma_offset_l1[i], -128, 127);
786       }
787       if (chroma_array_type != 0) {
788         guint8 chroma_weight_l1_flag = 0;
789         gint j;
790
791         for (j = 0; j < 2; j++) {
792           if (p->chroma_weight_l1[i][j] != default_chroma_weight ||
793               p->chroma_offset_l1[i][j] != 0)
794             chroma_weight_l1_flag = 1;
795         }
796
797         WRITE_BITS (bw, chroma_weight_l1_flag, 1);
798         if (chroma_weight_l1_flag) {
799           for (j = 0; j < 2; j++) {
800             WRITE_SE_RANGE (bw, p->chroma_weight_l1[i][j], -128, 127);
801             WRITE_SE_RANGE (bw, p->chroma_offset_l1[i][j], -128, 127);
802           }
803         }
804       }
805     }
806   }
807
808   *space = TRUE;
809   return TRUE;
810
811 error:
812   GST_WARNING ("error to write \"Prediction weight table\"");
813
814   *space = have_space;
815   return FALSE;
816 }
817
818 static gboolean
819 _h264_bit_writer_slice_dec_ref_pic_marking (const GstH264SliceHdr * slice,
820     guint32 nal_type, GstBitWriter * bw, gboolean * space)
821 {
822   gboolean have_space = TRUE;
823
824   GST_DEBUG ("writing \"Dec Ref Pic Marking\"");
825
826   if (nal_type == GST_H264_NAL_SLICE_IDR) {
827     WRITE_BITS (bw, slice->dec_ref_pic_marking.no_output_of_prior_pics_flag, 1);
828     WRITE_BITS (bw, slice->dec_ref_pic_marking.long_term_reference_flag, 1);
829   } else {
830     WRITE_BITS (bw,
831         slice->dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag, 1);
832
833     if (slice->dec_ref_pic_marking.adaptive_ref_pic_marking_mode_flag) {
834       const GstH264RefPicMarking *refpicmarking;
835       guint i;
836
837       for (i = 0; i < slice->dec_ref_pic_marking.n_ref_pic_marking; i++) {
838         refpicmarking = &slice->dec_ref_pic_marking.ref_pic_marking[i];
839
840         WRITE_UE_MAX (bw,
841             refpicmarking->memory_management_control_operation, 6);
842
843         if (refpicmarking->memory_management_control_operation == 0)
844           break;
845
846         if (refpicmarking->memory_management_control_operation == 1
847             || refpicmarking->memory_management_control_operation == 3)
848           WRITE_UE (bw, refpicmarking->difference_of_pic_nums_minus1);
849
850         if (refpicmarking->memory_management_control_operation == 2)
851           WRITE_UE (bw, refpicmarking->long_term_pic_num);
852
853         if (refpicmarking->memory_management_control_operation == 3
854             || refpicmarking->memory_management_control_operation == 6)
855           WRITE_UE (bw, refpicmarking->long_term_frame_idx);
856
857         if (refpicmarking->memory_management_control_operation == 4)
858           WRITE_UE (bw, refpicmarking->max_long_term_frame_idx_plus1);
859       }
860     }
861   }
862
863   *space = TRUE;
864   return TRUE;
865
866 error:
867   GST_WARNING ("error to write \"Dec Ref Pic Marking\"");
868
869   *space = have_space;
870   return FALSE;
871 }
872
873 static gboolean
874 _h264_bit_writer_slice_hdr (const GstH264SliceHdr * slice, guint32 nal_type,
875     guint32 ext_type, gboolean is_ref, GstBitWriter * bw, gboolean * space)
876 {
877   gboolean have_space = TRUE;
878
879   GST_DEBUG ("writing slice header");
880
881   WRITE_UE (bw, slice->first_mb_in_slice);
882   WRITE_UE (bw, slice->type);
883
884   WRITE_UE_MAX (bw, slice->pps->id, GST_H264_MAX_PPS_COUNT - 1);
885
886   if (slice->pps->sequence->separate_colour_plane_flag)
887     WRITE_BITS (bw, slice->colour_plane_id, 2);
888
889   WRITE_BITS (bw, slice->frame_num,
890       slice->pps->sequence->log2_max_frame_num_minus4 + 4);
891
892   if (!slice->pps->sequence->frame_mbs_only_flag) {
893     WRITE_BITS (bw, slice->field_pic_flag, 1);
894     if (slice->field_pic_flag)
895       WRITE_BITS (bw, slice->bottom_field_flag, 1);
896   }
897
898   if (nal_type == GST_H264_NAL_SLICE_IDR)
899     WRITE_UE_MAX (bw, slice->idr_pic_id, G_MAXUINT16);
900
901   if (slice->pps->sequence->pic_order_cnt_type == 0) {
902     WRITE_BITS (bw, slice->pic_order_cnt_lsb,
903         slice->pps->sequence->log2_max_pic_order_cnt_lsb_minus4 + 4);
904
905     if (slice->pps->pic_order_present_flag && !slice->field_pic_flag)
906       WRITE_SE (bw, slice->delta_pic_order_cnt_bottom);
907   }
908
909   if (slice->pps->sequence->pic_order_cnt_type == 1
910       && !slice->pps->sequence->delta_pic_order_always_zero_flag) {
911     WRITE_SE (bw, slice->delta_pic_order_cnt[0]);
912     if (slice->pps->pic_order_present_flag && !slice->field_pic_flag)
913       WRITE_SE (bw, slice->delta_pic_order_cnt[1]);
914   }
915
916   if (slice->pps->redundant_pic_cnt_present_flag)
917     WRITE_UE_MAX (bw, slice->redundant_pic_cnt, G_MAXINT8);
918
919   if (GST_H264_IS_B_SLICE (slice))
920     WRITE_BITS (bw, slice->direct_spatial_mv_pred_flag, 1);
921
922   if (GST_H264_IS_P_SLICE (slice) || GST_H264_IS_SP_SLICE (slice) ||
923       GST_H264_IS_B_SLICE (slice)) {
924     WRITE_BITS (bw, slice->num_ref_idx_active_override_flag, 1);
925     if (slice->num_ref_idx_active_override_flag) {
926       WRITE_UE_MAX (bw, slice->num_ref_idx_l0_active_minus1, 31);
927
928       if (GST_H264_IS_B_SLICE (slice))
929         WRITE_UE_MAX (bw, slice->num_ref_idx_l1_active_minus1, 31);
930     }
931   }
932
933   if (!_h264_slice_bit_writer_ref_pic_list_modification (slice,
934           ext_type == GST_H264_NAL_EXTENSION_MVC, bw, &have_space))
935     goto error;
936
937   if ((slice->pps->weighted_pred_flag && (GST_H264_IS_P_SLICE (slice)
938               || GST_H264_IS_SP_SLICE (slice)))
939       || (slice->pps->weighted_bipred_idc == 1 && GST_H264_IS_B_SLICE (slice))) {
940     if (!_h264_slice_bit_writer_pred_weight_table (slice,
941             slice->pps->sequence->chroma_array_type, bw, &have_space))
942       goto error;
943   }
944
945   if (is_ref) {
946     if (!_h264_bit_writer_slice_dec_ref_pic_marking (slice, nal_type, bw,
947             &have_space))
948       goto error;
949   }
950
951   if (slice->pps->entropy_coding_mode_flag && !GST_H264_IS_I_SLICE (slice) &&
952       !GST_H264_IS_SI_SLICE (slice))
953     WRITE_UE_MAX (bw, slice->cabac_init_idc, 2);
954
955   WRITE_SE_RANGE (bw, slice->slice_qp_delta, -87, 77);
956
957   if (GST_H264_IS_SP_SLICE (slice) || GST_H264_IS_SI_SLICE (slice)) {
958     if (GST_H264_IS_SP_SLICE (slice))
959       WRITE_BITS (bw, slice->sp_for_switch_flag, 1);
960
961     WRITE_SE_RANGE (bw, slice->slice_qs_delta, -51, 51);
962   }
963
964   if (slice->pps->deblocking_filter_control_present_flag) {
965     WRITE_UE_MAX (bw, slice->disable_deblocking_filter_idc, 2);
966     if (slice->disable_deblocking_filter_idc != 1) {
967       WRITE_SE_RANGE (bw, slice->slice_alpha_c0_offset_div2, -6, 6);
968       WRITE_SE_RANGE (bw, slice->slice_beta_offset_div2, -6, 6);
969     }
970   }
971
972   *space = TRUE;
973   return TRUE;
974
975 error:
976   GST_WARNING ("error to write slice header");
977
978   *space = have_space;
979   return FALSE;
980 }
981
982 /**
983  * gst_h264_bit_writer_slice_hdr:
984  * @slice: the slice header of #GstH264SliceHdr to write
985  * @start_code: whether adding the nal start code
986  * @nal_type: the slice's nal type of #GstH264NalUnitType
987  * @is_ref: whether the slice is a reference
988  * @data: (out): the bit stream generated by the slice header
989  * @size: (inout): the size in bytes of the input and output
990  * @trail_bits_num: (out): the trail bits number which is not byte aligned.
991  *
992  * Generating the according h264 bit stream by providing the slice header.
993  *
994  * Returns: a #GstH264BitWriterResult
995  *
996  * Since: 1.22
997  **/
998 GstH264BitWriterResult
999 gst_h264_bit_writer_slice_hdr (const GstH264SliceHdr * slice,
1000     gboolean start_code, GstH264NalUnitType nal_type, gboolean is_ref,
1001     guint8 * data, guint * size, guint * trail_bits_num)
1002 {
1003   gboolean have_space = TRUE;
1004   GstBitWriter bw;
1005
1006   g_return_val_if_fail (slice != NULL, GST_H264_BIT_WRITER_ERROR);
1007   g_return_val_if_fail (slice->pps != NULL, GST_H264_BIT_WRITER_ERROR);
1008   g_return_val_if_fail (slice->pps->sequence != NULL,
1009       GST_H264_BIT_WRITER_ERROR);
1010   g_return_val_if_fail (nal_type >= GST_H264_NAL_SLICE
1011       && nal_type <= GST_H264_NAL_SLICE_IDR, GST_H264_BIT_WRITER_ERROR);
1012   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
1013   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
1014   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
1015   g_return_val_if_fail (trail_bits_num != NULL, GST_H264_BIT_WRITER_ERROR);
1016
1017   if (nal_type == GST_H264_NAL_SLICE_IDR)
1018     g_return_val_if_fail (is_ref, GST_H264_BIT_WRITER_ERROR);
1019
1020   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
1021
1022   if (start_code)
1023     WRITE_BITS (&bw, 0x00000001, 32);
1024
1025   /* nal header */
1026   /* forbidden_zero_bit */
1027   WRITE_BITS (&bw, 0, 1);
1028   /* nal_ref_idc, zero for non-reference picture */
1029   WRITE_BITS (&bw, is_ref, 2);
1030   /* nal_unit_type */
1031   WRITE_BITS (&bw, nal_type, 5);
1032
1033   if (!_h264_bit_writer_slice_hdr (slice, nal_type,
1034           GST_H264_NAL_EXTENSION_NONE, is_ref, &bw, &have_space))
1035     goto error;
1036
1037   /* We do not add trailing bits here, the slice data should follow it. */
1038
1039   *size = gst_bit_writer_get_size (&bw) / 8;
1040   *trail_bits_num = gst_bit_writer_get_size (&bw) % 8;
1041   gst_bit_writer_reset (&bw);
1042   return GST_H264_BIT_WRITER_OK;
1043
1044 error:
1045   gst_bit_writer_reset (&bw);
1046   *size = 0;
1047
1048   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1049       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1050 }
1051
1052 static gboolean
1053 _h264_bit_writer_sei_registered_user_data (const GstH264RegisteredUserData *
1054     rud, GstBitWriter * bw, gboolean * space)
1055 {
1056   gboolean have_space = TRUE;
1057
1058   GST_DEBUG ("Writing \"Registered user data\"");
1059
1060   WRITE_BITS (bw, rud->country_code, 8);
1061   if (rud->country_code == 0xff)
1062     WRITE_BITS (bw, rud->country_code_extension, 8);
1063
1064   WRITE_BYTES (bw, rud->data, rud->size);
1065
1066   *space = TRUE;
1067   return TRUE;
1068
1069 error:GST_WARNING ("Failed to write \"Registered user data\"");
1070
1071   *space = have_space;
1072   return FALSE;
1073 }
1074
1075 static gboolean
1076 _h264_bit_writer_sei_frame_packing (const GstH264FramePacking *
1077     frame_packing, GstBitWriter * bw, gboolean * space)
1078 {
1079   gboolean have_space = TRUE;
1080
1081   GST_DEBUG ("Writing \"Frame packing\"");
1082
1083   WRITE_UE (bw, frame_packing->frame_packing_id);
1084   WRITE_BITS (bw, frame_packing->frame_packing_cancel_flag, 1);
1085
1086   if (!frame_packing->frame_packing_cancel_flag) {
1087     WRITE_BITS (bw, frame_packing->frame_packing_type, 7);
1088     WRITE_BITS (bw, frame_packing->quincunx_sampling_flag, 1);
1089     WRITE_BITS (bw, frame_packing->content_interpretation_type, 6);
1090     WRITE_BITS (bw, frame_packing->spatial_flipping_flag, 1);
1091     WRITE_BITS (bw, frame_packing->frame0_flipped_flag, 1);
1092     WRITE_BITS (bw, frame_packing->field_views_flag, 1);
1093     WRITE_BITS (bw, frame_packing->current_frame_is_frame0_flag, 1);
1094     WRITE_BITS (bw, frame_packing->frame0_self_contained_flag, 1);
1095     WRITE_BITS (bw, frame_packing->frame1_self_contained_flag, 1);
1096
1097     if (!frame_packing->quincunx_sampling_flag &&
1098         frame_packing->frame_packing_type !=
1099         GST_H264_FRAME_PACKING_TEMPORAL_INTERLEAVING) {
1100       WRITE_BITS (bw, frame_packing->frame0_grid_position_x, 4);
1101       WRITE_BITS (bw, frame_packing->frame0_grid_position_y, 4);
1102       WRITE_BITS (bw, frame_packing->frame1_grid_position_x, 4);
1103       WRITE_BITS (bw, frame_packing->frame1_grid_position_y, 4);
1104     }
1105
1106     /* frame_packing_arrangement_reserved_byte */
1107     WRITE_BITS (bw, 0, 8);
1108     WRITE_UE (bw, frame_packing->frame_packing_repetition_period);
1109   }
1110
1111   /* frame_packing_arrangement_extension_flag */
1112   WRITE_BITS (bw, 0, 1);
1113
1114   *space = TRUE;
1115   return TRUE;
1116
1117 error:
1118   GST_WARNING ("Failed to write \"Frame packing\"");
1119
1120   *space = have_space;
1121   return FALSE;
1122 }
1123
1124 static gboolean
1125 _h264_bit_writer_sei_mastering_display_colour_volume (const
1126     GstH264MasteringDisplayColourVolume * mdcv, GstBitWriter * bw,
1127     gboolean * space)
1128 {
1129   gboolean have_space = TRUE;
1130   gint i;
1131
1132   GST_DEBUG ("Wrtiting \"Mastering display colour volume\"");
1133
1134   for (i = 0; i < 3; i++) {
1135     WRITE_BITS (bw, mdcv->display_primaries_x[i], 16);
1136     WRITE_BITS (bw, mdcv->display_primaries_y[i], 16);
1137   }
1138
1139   WRITE_BITS (bw, mdcv->white_point_x, 16);
1140   WRITE_BITS (bw, mdcv->white_point_y, 16);
1141   WRITE_BITS (bw, mdcv->max_display_mastering_luminance, 32);
1142   WRITE_BITS (bw, mdcv->min_display_mastering_luminance, 32);
1143
1144   *space = TRUE;
1145   return TRUE;
1146
1147 error:
1148   GST_WARNING ("Failed to write \"Mastering display colour volume\"");
1149
1150   *space = have_space;
1151   return FALSE;
1152 }
1153
1154 static gboolean
1155 _h264_bit_writer_sei_content_light_level_info (const
1156     GstH264ContentLightLevel * cll, GstBitWriter * bw, gboolean * space)
1157 {
1158   gboolean have_space = TRUE;
1159
1160   GST_DEBUG ("Writing \"Content light level\"");
1161
1162   WRITE_BITS (bw, cll->max_content_light_level, 16);
1163   WRITE_BITS (bw, cll->max_pic_average_light_level, 16);
1164
1165   *space = TRUE;
1166   return TRUE;
1167
1168 error:
1169   GST_WARNING ("Failed to write \"Content light level\"");
1170
1171   *space = have_space;
1172   return FALSE;
1173 }
1174
1175 static gboolean
1176 _h264_bit_writer_sei_pic_timing (const GstH264PicTiming * tim,
1177     GstBitWriter * bw, gboolean * space)
1178 {
1179   gboolean have_space = TRUE;
1180
1181   GST_DEBUG ("Writing \"Picture timing\"");
1182
1183   if (tim->CpbDpbDelaysPresentFlag) {
1184     WRITE_BITS (bw, tim->cpb_removal_delay,
1185         tim->cpb_removal_delay_length_minus1 + 1);
1186     WRITE_BITS (bw, tim->dpb_output_delay,
1187         tim->dpb_output_delay_length_minus1 + 1);
1188   }
1189
1190   if (tim->pic_struct_present_flag) {
1191     const guint8 num_clock_ts_table[9] = {
1192       1, 1, 1, 2, 2, 3, 3, 2, 3
1193     };
1194     guint8 num_clock_num_ts;
1195     guint i;
1196
1197     WRITE_BITS (bw, tim->pic_struct, 4);
1198
1199     num_clock_num_ts = num_clock_ts_table[tim->pic_struct];
1200     for (i = 0; i < num_clock_num_ts; i++) {
1201       WRITE_BITS (bw, tim->clock_timestamp_flag[i], 1);
1202       if (tim->clock_timestamp_flag[i]) {
1203         const GstH264ClockTimestamp *timestamp = &tim->clock_timestamp[i];
1204
1205         WRITE_BITS (bw, timestamp->ct_type, 2);
1206         WRITE_BITS (bw, timestamp->nuit_field_based_flag, 1);
1207         WRITE_BITS (bw, timestamp->counting_type, 5);
1208         WRITE_BITS (bw, timestamp->full_timestamp_flag, 1);
1209         WRITE_BITS (bw, timestamp->discontinuity_flag, 1);
1210         WRITE_BITS (bw, timestamp->cnt_dropped_flag, 1);
1211         WRITE_BITS (bw, timestamp->n_frames, 8);
1212
1213         if (timestamp->full_timestamp_flag) {
1214           if (!timestamp->seconds_flag || !timestamp->minutes_flag
1215               || !timestamp->hours_flag)
1216             goto error;
1217
1218           WRITE_BITS (bw, timestamp->seconds_value, 6);
1219           WRITE_BITS (bw, timestamp->minutes_value, 6);
1220           WRITE_BITS (bw, timestamp->hours_value, 5);
1221         } else {
1222           WRITE_BITS (bw, timestamp->seconds_flag, 1);
1223           if (timestamp->seconds_flag) {
1224             WRITE_BITS (bw, timestamp->seconds_value, 6);
1225             WRITE_BITS (bw, timestamp->minutes_flag, 1);
1226             if (timestamp->minutes_flag) {
1227               WRITE_BITS (bw, timestamp->minutes_value, 6);
1228               WRITE_BITS (bw, timestamp->hours_flag, 1);
1229               if (timestamp->hours_flag)
1230                 WRITE_BITS (bw, timestamp->hours_value, 5);
1231             }
1232           }
1233         }
1234
1235         if (tim->time_offset_length > 0) {
1236           WRITE_BITS (bw, timestamp->time_offset, tim->time_offset_length);
1237         }
1238       }
1239     }
1240   }
1241
1242   *space = TRUE;
1243   return TRUE;
1244
1245 error:
1246   GST_WARNING ("Failed to write \"Picture timing\"");
1247
1248   *space = have_space;
1249   return FALSE;
1250 }
1251
1252 static gboolean
1253 _h264_bit_writer_sei_buffering_period (const GstH264BufferingPeriod * per,
1254     GstBitWriter * bw, gboolean * space)
1255 {
1256   gboolean have_space = TRUE;
1257
1258   GST_DEBUG ("Writing \"Buffering period\"");
1259
1260   if (!per->sps)
1261     goto error;
1262
1263   WRITE_UE_MAX (bw, per->sps->id, GST_H264_MAX_SPS_COUNT - 1);
1264
1265   if (per->sps->vui_parameters_present_flag) {
1266     GstH264VUIParams *vui = &per->sps->vui_parameters;
1267
1268     if (vui->nal_hrd_parameters_present_flag) {
1269       GstH264HRDParams *hrd = &vui->nal_hrd_parameters;
1270       const guint8 nbits = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1271       guint8 sched_sel_idx;
1272
1273       for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1;
1274           sched_sel_idx++) {
1275         WRITE_BITS (bw, per->nal_initial_cpb_removal_delay[sched_sel_idx],
1276             nbits);
1277         WRITE_BITS (bw,
1278             per->nal_initial_cpb_removal_delay_offset[sched_sel_idx], nbits);
1279       }
1280     }
1281
1282     if (vui->vcl_hrd_parameters_present_flag) {
1283       GstH264HRDParams *hrd = &vui->vcl_hrd_parameters;
1284       const guint8 nbits = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1285       guint8 sched_sel_idx;
1286
1287       for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1;
1288           sched_sel_idx++) {
1289         WRITE_BITS (bw, per->vcl_initial_cpb_removal_delay[sched_sel_idx],
1290             nbits);
1291         WRITE_BITS (bw,
1292             per->vcl_initial_cpb_removal_delay_offset[sched_sel_idx], nbits);
1293       }
1294     }
1295   }
1296
1297   *space = TRUE;
1298   return TRUE;
1299
1300 error:
1301   GST_WARNING ("Failed to write \"Buffering period\"");
1302
1303   *space = have_space;
1304   return FALSE;
1305 }
1306
1307 static gboolean
1308 _h264_bit_writer_sei_message (const GstH264SEIMessage * msg,
1309     GstBitWriter * bw, gboolean * space)
1310 {
1311   gboolean have_space = TRUE;
1312
1313   GST_DEBUG ("writing SEI message");
1314
1315   switch (msg->payloadType) {
1316     case GST_H264_SEI_REGISTERED_USER_DATA:
1317       if (!_h264_bit_writer_sei_registered_user_data
1318           (&msg->payload.registered_user_data, bw, &have_space))
1319         goto error;
1320       break;
1321     case GST_H264_SEI_FRAME_PACKING:
1322       if (!_h264_bit_writer_sei_frame_packing
1323           (&msg->payload.frame_packing, bw, &have_space))
1324         goto error;
1325       break;
1326     case GST_H264_SEI_MASTERING_DISPLAY_COLOUR_VOLUME:
1327       if (!_h264_bit_writer_sei_mastering_display_colour_volume
1328           (&msg->payload.mastering_display_colour_volume, bw, &have_space))
1329         goto error;
1330       break;
1331     case GST_H264_SEI_CONTENT_LIGHT_LEVEL:
1332       if (!_h264_bit_writer_sei_content_light_level_info
1333           (&msg->payload.content_light_level, bw, &have_space))
1334         goto error;
1335       break;
1336     case GST_H264_SEI_PIC_TIMING:
1337       if (!_h264_bit_writer_sei_pic_timing (&msg->payload.pic_timing, bw,
1338               &have_space))
1339         goto error;
1340       break;
1341     case GST_H264_SEI_BUF_PERIOD:
1342       if (!_h264_bit_writer_sei_buffering_period
1343           (&msg->payload.buffering_period, bw, &have_space))
1344         goto error;
1345       break;
1346     default:
1347       break;
1348   }
1349
1350   /* Add trailings. */
1351   WRITE_BITS (bw, 1, 1);
1352   gst_bit_writer_align_bytes_unchecked (bw, 0);
1353
1354   *space = TRUE;
1355
1356   return TRUE;
1357
1358 error:
1359   GST_WARNING ("error to write SEI message");
1360
1361   *space = have_space;
1362   return FALSE;
1363 }
1364
1365 /**
1366  * gst_h264_bit_writer_sei:
1367  * @sei_messages: An array of #GstH264SEIMessage to write
1368  * @start_code: whether adding the nal start code
1369  * @data: (out): the bit stream generated by the sei messages
1370  * @size: (inout): the size in bytes of the input and output
1371  *
1372  * Generating the according h264 bit stream by providing sei messages.
1373  *
1374  * Returns: a #GstH264BitWriterResult
1375  *
1376  * Since: 1.22
1377  **/
1378 GstH264BitWriterResult
1379 gst_h264_bit_writer_sei (GArray * sei_messages, gboolean start_code,
1380     guint8 * data, guint * size)
1381 {
1382   gboolean have_space = TRUE;
1383   GstBitWriter bw;
1384   GstBitWriter bw_msg;
1385   GstH264SEIMessage *sei;
1386   gboolean have_written_data = FALSE;
1387   guint i;
1388
1389   g_return_val_if_fail (sei_messages != NULL, GST_H264_BIT_WRITER_ERROR);
1390   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
1391   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
1392   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
1393
1394   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
1395
1396   if (start_code)
1397     WRITE_BITS (&bw, 0x00000001, 32);
1398
1399   /* nal header */
1400   /* forbidden_zero_bit */
1401   WRITE_BITS (&bw, 0, 1);
1402   /* nal_ref_idc, zero for sei nalu */
1403   WRITE_BITS (&bw, 0, 2);
1404   /* nal_unit_type */
1405   WRITE_BITS (&bw, GST_H264_NAL_SEI, 5);
1406
1407   for (i = 0; i < sei_messages->len; i++) {
1408     guint32 payload_size_data;
1409     guint32 payload_type_data;
1410     guint32 sz;
1411
1412     gst_bit_writer_init (&bw_msg);
1413
1414     sei = &g_array_index (sei_messages, GstH264SEIMessage, i);
1415     if (!_h264_bit_writer_sei_message (sei, &bw_msg, &have_space))
1416       goto error;
1417
1418     if (gst_bit_writer_get_size (&bw_msg) == 0) {
1419       GST_FIXME ("Unsupported SEI type %d", sei->payloadType);
1420       continue;
1421     }
1422
1423     have_written_data = TRUE;
1424
1425     g_assert (gst_bit_writer_get_size (&bw_msg) % 8 == 0);
1426     payload_size_data = gst_bit_writer_get_size (&bw_msg) / 8;
1427     payload_type_data = sei->payloadType;
1428
1429     /* write payload type bytes */
1430     while (payload_type_data >= 0xff) {
1431       WRITE_BITS (&bw, 0xff, 8);
1432       payload_type_data -= 0xff;
1433     }
1434     WRITE_BITS (&bw, payload_type_data, 8);
1435
1436     /* write payload size bytes */
1437     sz = payload_size_data;
1438     while (sz >= 0xff) {
1439       WRITE_BITS (&bw, 0xff, 8);
1440       sz -= 0xff;
1441     }
1442     WRITE_BITS (&bw, sz, 8);
1443
1444     if (payload_size_data > 0)
1445       WRITE_BYTES (&bw, gst_bit_writer_get_data (&bw_msg), payload_size_data);
1446
1447     gst_bit_writer_reset (&bw_msg);
1448   }
1449
1450   if (!have_written_data) {
1451     GST_WARNING ("No written sei data");
1452     goto error;
1453   }
1454
1455   /* Add trailings. */
1456   WRITE_BITS (&bw, 1, 1);
1457   if (!gst_bit_writer_align_bytes (&bw, 0)) {
1458     have_space = FALSE;
1459     goto error;
1460   }
1461
1462   *size = (gst_bit_writer_get_size (&bw)) / 8;
1463   gst_bit_writer_reset (&bw);
1464   return GST_H264_BIT_WRITER_OK;
1465
1466 error:
1467   gst_bit_writer_reset (&bw);
1468   *size = 0;
1469
1470   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1471       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1472 }
1473
1474 /**
1475  * gst_h264_bit_writer_aud:
1476  * @primary_pic_type: indicate the possible slice types list just
1477  *   as the H264 spec defines
1478  * @start_code: whether adding the nal start code
1479  * @data: (out): the bit stream generated by the aud
1480  * @size: (inout): the size in bytes of the input and output
1481  *
1482  * Generating the according h264 bit stream of an aud.
1483  *
1484  * Returns: a #GstH264BitWriterResult
1485  *
1486  * Since: 1.22
1487  **/
1488 GstH264BitWriterResult
1489 gst_h264_bit_writer_aud (guint8 primary_pic_type, gboolean start_code,
1490     guint8 * data, guint * size)
1491 {
1492   gboolean have_space = TRUE;
1493   GstBitWriter bw;
1494
1495   g_return_val_if_fail (primary_pic_type <= 7, GST_H264_BIT_WRITER_ERROR);
1496   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
1497   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
1498   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
1499
1500   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
1501
1502   if (start_code)
1503     WRITE_BITS (&bw, 0x00000001, 32);
1504
1505   /* nal header */
1506   /* forbidden_zero_bit */
1507   WRITE_BITS (&bw, 0, 1);
1508   /* nal_ref_idc */
1509   WRITE_BITS (&bw, 0, 2);
1510   /* nal_unit_type */
1511   WRITE_BITS (&bw, GST_H264_NAL_AU_DELIMITER, 5);
1512
1513   WRITE_BITS (&bw, primary_pic_type, 3);
1514
1515   /* Add trailings. */
1516   WRITE_BITS (&bw, 1, 1);
1517   if (!gst_bit_writer_align_bytes (&bw, 0)) {
1518     goto error;
1519   }
1520
1521   *size = (gst_bit_writer_get_size (&bw)) / 8;
1522   gst_bit_writer_reset (&bw);
1523
1524   return GST_H264_BIT_WRITER_OK;
1525
1526 error:
1527   gst_bit_writer_reset (&bw);
1528   *size = 0;
1529
1530   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1531       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1532 }
1533
1534 /**
1535  * gst_h264_bit_writer_convert_to_nal:
1536  * @nal_prefix_size: the size in bytes for the prefix of a nal, may
1537  *   be 2, 3 or 4
1538  * @packetized: whether to write the bit stream in packetized format,
1539  *   which does not have the start code but has a @nal_prefix_size bytes'
1540  *   size prepending to the real nal data
1541  * @has_startcode: whether the input already has a start code
1542  * @add_trailings: whether to add rbsp trailing bits to make the output
1543  *   aligned to byte
1544  * @raw_data: the input bit stream
1545  * @raw_size: the size in bits of the input bit stream
1546  * @nal_data: (out): the output bit stream converted to a real nal
1547  * @nal_size: (inout): the size in bytes of the output
1548  *
1549  * Converting a bit stream into a real nal packet. If the bit stream already
1550  * has a start code, it will be replaced by the new one specified by the
1551  * @nal_prefix_size and @packetized. It is assured that the output aligns to
1552  * the byte and the all the emulations are inserted.
1553  *
1554  * Returns: a #GstH264BitWriterResult
1555  *
1556  * Since: 1.22
1557  **/
1558 GstH264BitWriterResult
1559 gst_h264_bit_writer_convert_to_nal (guint nal_prefix_size, gboolean packetized,
1560     gboolean has_startcode, gboolean add_trailings, const guint8 * raw_data,
1561     gsize raw_size, guint8 * nal_data, guint * nal_size)
1562 {
1563   NalWriter nw;
1564   guint8 *data;
1565   guint32 size = 0;
1566   gboolean need_more_space = FALSE;
1567
1568   g_return_val_if_fail (
1569       (packetized && nal_prefix_size > 1 && nal_prefix_size < 5) ||
1570       (!packetized && (nal_prefix_size == 3 || nal_prefix_size == 4)),
1571       GST_H264_BIT_WRITER_ERROR);
1572   g_return_val_if_fail (raw_data != NULL, GST_H264_BIT_WRITER_ERROR);
1573   g_return_val_if_fail (raw_size > 0, GST_H264_BIT_WRITER_ERROR);
1574   g_return_val_if_fail (nal_data != NULL, GST_H264_BIT_WRITER_ERROR);
1575   g_return_val_if_fail (nal_size != NULL, GST_H264_BIT_WRITER_ERROR);
1576   g_return_val_if_fail (*nal_size > 0, GST_H264_BIT_WRITER_ERROR);
1577
1578   if (has_startcode) {
1579     /* Skip the start code, the NalWriter will add it automatically. */
1580     if (raw_size >= 4 && raw_data[0] == 0
1581         && raw_data[1] == 0 && raw_data[2] == 0 && raw_data[3] == 0x01) {
1582       raw_data += 4;
1583       raw_size -= 4 * 8;
1584     } else if (raw_size >= 3 && raw_data[0] == 0 && raw_data[1] == 0
1585         && raw_data[2] == 0x01) {
1586       raw_data += 3;
1587       raw_size -= 3 * 8;
1588     } else {
1589       /* Fail to find the start code. */
1590       g_return_val_if_reached (GST_H264_BIT_WRITER_ERROR);
1591     }
1592   }
1593
1594   /* If no RBSP trailing needed, it must align to byte. We assume
1595      that the rbsp trailing bits are already added. */
1596   if (!add_trailings)
1597     g_return_val_if_fail (raw_size % 8 == 0, GST_H264_BIT_WRITER_ERROR);
1598
1599   nal_writer_init (&nw, nal_prefix_size, packetized);
1600
1601   if (!nal_writer_put_bytes (&nw, raw_data, raw_size / 8))
1602     goto error;
1603
1604   if (raw_size % 8) {
1605     guint8 data = *(raw_data + raw_size / 8);
1606
1607     if (!nal_writer_put_bits_uint8 (&nw,
1608             data >> (8 - raw_size % 8), raw_size % 8))
1609       goto error;
1610   }
1611
1612   if (add_trailings) {
1613     if (!nal_writer_do_rbsp_trailing_bits (&nw))
1614       goto error;
1615   }
1616
1617   data = nal_writer_reset_and_get_data (&nw, &size);
1618   if (!data)
1619     goto error;
1620
1621   if (size > *nal_size) {
1622     need_more_space = TRUE;
1623     g_free (data);
1624     goto error;
1625   }
1626
1627   memcpy (nal_data, data, size);
1628   *nal_size = size;
1629   g_free (data);
1630   nal_writer_reset (&nw);
1631   return GST_H264_BIT_WRITER_OK;
1632
1633 error:
1634   nal_writer_reset (&nw);
1635   *nal_size = 0;
1636
1637   GST_WARNING ("Failed to convert nal data");
1638
1639   return need_more_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1640       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1641 }