7233c1fe9a3dcfe9e672936986d4ea456b346c7c
[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 bits of the 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, gsize * 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);
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 bits of the 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, gsize * 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);
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 bits of the output
990  *
991  * Generating the according h264 bit stream by providing the slice header.
992  *
993  * Returns: a #GstH264BitWriterResult
994  *
995  * Since: 1.22
996  **/
997 GstH264BitWriterResult
998 gst_h264_bit_writer_slice_hdr (const GstH264SliceHdr * slice,
999     gboolean start_code, GstH264NalUnitType nal_type, gboolean is_ref,
1000     guint8 * data, gsize * size)
1001 {
1002   gboolean have_space = TRUE;
1003   GstBitWriter bw;
1004
1005   g_return_val_if_fail (slice != NULL, GST_H264_BIT_WRITER_ERROR);
1006   g_return_val_if_fail (slice->pps != NULL, GST_H264_BIT_WRITER_ERROR);
1007   g_return_val_if_fail (slice->pps->sequence != NULL,
1008       GST_H264_BIT_WRITER_ERROR);
1009   g_return_val_if_fail (nal_type >= GST_H264_NAL_SLICE
1010       && nal_type <= GST_H264_NAL_SLICE_IDR, GST_H264_BIT_WRITER_ERROR);
1011   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
1012   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
1013   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
1014
1015   if (nal_type == GST_H264_NAL_SLICE_IDR)
1016     g_return_val_if_fail (is_ref, GST_H264_BIT_WRITER_ERROR);
1017
1018   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
1019
1020   if (start_code)
1021     WRITE_BITS (&bw, 0x00000001, 32);
1022
1023   /* nal header */
1024   /* forbidden_zero_bit */
1025   WRITE_BITS (&bw, 0, 1);
1026   /* nal_ref_idc, zero for non-reference picture */
1027   WRITE_BITS (&bw, is_ref, 2);
1028   /* nal_unit_type */
1029   WRITE_BITS (&bw, nal_type, 5);
1030
1031   if (!_h264_bit_writer_slice_hdr (slice, nal_type,
1032           GST_H264_NAL_EXTENSION_NONE, is_ref, &bw, &have_space))
1033     goto error;
1034
1035   /* We do not add trailing bits here, the slice data should follow it. */
1036
1037   *size = gst_bit_writer_get_size (&bw);
1038   gst_bit_writer_reset (&bw);
1039   return GST_H264_BIT_WRITER_OK;
1040
1041 error:
1042   gst_bit_writer_reset (&bw);
1043   *size = 0;
1044
1045   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1046       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1047 }
1048
1049 static gboolean
1050 _h264_bit_writer_sei_registered_user_data (const GstH264RegisteredUserData *
1051     rud, GstBitWriter * bw, gboolean * space)
1052 {
1053   gboolean have_space = TRUE;
1054
1055   GST_DEBUG ("Writing \"Registered user data\"");
1056
1057   WRITE_BITS (bw, rud->country_code, 8);
1058   if (rud->country_code == 0xff)
1059     WRITE_BITS (bw, rud->country_code_extension, 8);
1060
1061   WRITE_BYTES (bw, rud->data, rud->size);
1062
1063   *space = TRUE;
1064   return TRUE;
1065
1066 error:GST_WARNING ("Failed to write \"Registered user data\"");
1067
1068   *space = have_space;
1069   return FALSE;
1070 }
1071
1072 static gboolean
1073 _h264_bit_writer_sei_frame_packing (const GstH264FramePacking *
1074     frame_packing, GstBitWriter * bw, gboolean * space)
1075 {
1076   gboolean have_space = TRUE;
1077
1078   GST_DEBUG ("Writing \"Frame packing\"");
1079
1080   WRITE_UE (bw, frame_packing->frame_packing_id);
1081   WRITE_BITS (bw, frame_packing->frame_packing_cancel_flag, 1);
1082
1083   if (!frame_packing->frame_packing_cancel_flag) {
1084     WRITE_BITS (bw, frame_packing->frame_packing_type, 7);
1085     WRITE_BITS (bw, frame_packing->quincunx_sampling_flag, 1);
1086     WRITE_BITS (bw, frame_packing->content_interpretation_type, 6);
1087     WRITE_BITS (bw, frame_packing->spatial_flipping_flag, 1);
1088     WRITE_BITS (bw, frame_packing->frame0_flipped_flag, 1);
1089     WRITE_BITS (bw, frame_packing->field_views_flag, 1);
1090     WRITE_BITS (bw, frame_packing->current_frame_is_frame0_flag, 1);
1091     WRITE_BITS (bw, frame_packing->frame0_self_contained_flag, 1);
1092     WRITE_BITS (bw, frame_packing->frame1_self_contained_flag, 1);
1093
1094     if (!frame_packing->quincunx_sampling_flag &&
1095         frame_packing->frame_packing_type !=
1096         GST_H264_FRAME_PACKING_TEMPORAL_INTERLEAVING) {
1097       WRITE_BITS (bw, frame_packing->frame0_grid_position_x, 4);
1098       WRITE_BITS (bw, frame_packing->frame0_grid_position_y, 4);
1099       WRITE_BITS (bw, frame_packing->frame1_grid_position_x, 4);
1100       WRITE_BITS (bw, frame_packing->frame1_grid_position_y, 4);
1101     }
1102
1103     /* frame_packing_arrangement_reserved_byte */
1104     WRITE_BITS (bw, 0, 8);
1105     WRITE_UE (bw, frame_packing->frame_packing_repetition_period);
1106   }
1107
1108   /* frame_packing_arrangement_extension_flag */
1109   WRITE_BITS (bw, 0, 1);
1110
1111   *space = TRUE;
1112   return TRUE;
1113
1114 error:
1115   GST_WARNING ("Failed to write \"Frame packing\"");
1116
1117   *space = have_space;
1118   return FALSE;
1119 }
1120
1121 static gboolean
1122 _h264_bit_writer_sei_mastering_display_colour_volume (const
1123     GstH264MasteringDisplayColourVolume * mdcv, GstBitWriter * bw,
1124     gboolean * space)
1125 {
1126   gboolean have_space = TRUE;
1127   gint i;
1128
1129   GST_DEBUG ("Wrtiting \"Mastering display colour volume\"");
1130
1131   for (i = 0; i < 3; i++) {
1132     WRITE_BITS (bw, mdcv->display_primaries_x[i], 16);
1133     WRITE_BITS (bw, mdcv->display_primaries_y[i], 16);
1134   }
1135
1136   WRITE_BITS (bw, mdcv->white_point_x, 16);
1137   WRITE_BITS (bw, mdcv->white_point_y, 16);
1138   WRITE_BITS (bw, mdcv->max_display_mastering_luminance, 32);
1139   WRITE_BITS (bw, mdcv->min_display_mastering_luminance, 32);
1140
1141   *space = TRUE;
1142   return TRUE;
1143
1144 error:
1145   GST_WARNING ("Failed to write \"Mastering display colour volume\"");
1146
1147   *space = have_space;
1148   return FALSE;
1149 }
1150
1151 static gboolean
1152 _h264_bit_writer_sei_content_light_level_info (const
1153     GstH264ContentLightLevel * cll, GstBitWriter * bw, gboolean * space)
1154 {
1155   gboolean have_space = TRUE;
1156
1157   GST_DEBUG ("Writing \"Content light level\"");
1158
1159   WRITE_BITS (bw, cll->max_content_light_level, 16);
1160   WRITE_BITS (bw, cll->max_pic_average_light_level, 16);
1161
1162   *space = TRUE;
1163   return TRUE;
1164
1165 error:
1166   GST_WARNING ("Failed to write \"Content light level\"");
1167
1168   *space = have_space;
1169   return FALSE;
1170 }
1171
1172 static gboolean
1173 _h264_bit_writer_sei_pic_timing (const GstH264PicTiming * tim,
1174     GstBitWriter * bw, gboolean * space)
1175 {
1176   gboolean have_space = TRUE;
1177
1178   GST_DEBUG ("Writing \"Picture timing\"");
1179
1180   if (tim->CpbDpbDelaysPresentFlag) {
1181     WRITE_BITS (bw, tim->cpb_removal_delay,
1182         tim->cpb_removal_delay_length_minus1 + 1);
1183     WRITE_BITS (bw, tim->dpb_output_delay,
1184         tim->dpb_output_delay_length_minus1 + 1);
1185   }
1186
1187   if (tim->pic_struct_present_flag) {
1188     const guint8 num_clock_ts_table[9] = {
1189       1, 1, 1, 2, 2, 3, 3, 2, 3
1190     };
1191     guint8 num_clock_num_ts;
1192     guint i;
1193
1194     WRITE_BITS (bw, tim->pic_struct, 4);
1195
1196     num_clock_num_ts = num_clock_ts_table[tim->pic_struct];
1197     for (i = 0; i < num_clock_num_ts; i++) {
1198       WRITE_BITS (bw, tim->clock_timestamp_flag[i], 1);
1199       if (tim->clock_timestamp_flag[i]) {
1200         const GstH264ClockTimestamp *timestamp = &tim->clock_timestamp[i];
1201
1202         WRITE_BITS (bw, timestamp->ct_type, 2);
1203         WRITE_BITS (bw, timestamp->nuit_field_based_flag, 1);
1204         WRITE_BITS (bw, timestamp->counting_type, 5);
1205         WRITE_BITS (bw, timestamp->full_timestamp_flag, 1);
1206         WRITE_BITS (bw, timestamp->discontinuity_flag, 1);
1207         WRITE_BITS (bw, timestamp->cnt_dropped_flag, 1);
1208         WRITE_BITS (bw, timestamp->n_frames, 8);
1209
1210         if (timestamp->full_timestamp_flag) {
1211           if (!timestamp->seconds_flag || !timestamp->minutes_flag
1212               || !timestamp->hours_flag)
1213             goto error;
1214
1215           WRITE_BITS (bw, timestamp->seconds_value, 6);
1216           WRITE_BITS (bw, timestamp->minutes_value, 6);
1217           WRITE_BITS (bw, timestamp->hours_value, 5);
1218         } else {
1219           WRITE_BITS (bw, timestamp->seconds_flag, 1);
1220           if (timestamp->seconds_flag) {
1221             WRITE_BITS (bw, timestamp->seconds_value, 6);
1222             WRITE_BITS (bw, timestamp->minutes_flag, 1);
1223             if (timestamp->minutes_flag) {
1224               WRITE_BITS (bw, timestamp->minutes_value, 6);
1225               WRITE_BITS (bw, timestamp->hours_flag, 1);
1226               if (timestamp->hours_flag)
1227                 WRITE_BITS (bw, timestamp->hours_value, 5);
1228             }
1229           }
1230         }
1231
1232         if (tim->time_offset_length > 0) {
1233           WRITE_BITS (bw, timestamp->time_offset, tim->time_offset_length);
1234         }
1235       }
1236     }
1237   }
1238
1239   *space = TRUE;
1240   return TRUE;
1241
1242 error:
1243   GST_WARNING ("Failed to write \"Picture timing\"");
1244
1245   *space = have_space;
1246   return FALSE;
1247 }
1248
1249 static gboolean
1250 _h264_bit_writer_sei_buffering_period (const GstH264BufferingPeriod * per,
1251     GstBitWriter * bw, gboolean * space)
1252 {
1253   gboolean have_space = TRUE;
1254
1255   GST_DEBUG ("Writing \"Buffering period\"");
1256
1257   if (!per->sps)
1258     goto error;
1259
1260   WRITE_UE_MAX (bw, per->sps->id, GST_H264_MAX_SPS_COUNT - 1);
1261
1262   if (per->sps->vui_parameters_present_flag) {
1263     GstH264VUIParams *vui = &per->sps->vui_parameters;
1264
1265     if (vui->nal_hrd_parameters_present_flag) {
1266       GstH264HRDParams *hrd = &vui->nal_hrd_parameters;
1267       const guint8 nbits = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1268       guint8 sched_sel_idx;
1269
1270       for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1;
1271           sched_sel_idx++) {
1272         WRITE_BITS (bw, per->nal_initial_cpb_removal_delay[sched_sel_idx],
1273             nbits);
1274         WRITE_BITS (bw,
1275             per->nal_initial_cpb_removal_delay_offset[sched_sel_idx], nbits);
1276       }
1277     }
1278
1279     if (vui->vcl_hrd_parameters_present_flag) {
1280       GstH264HRDParams *hrd = &vui->vcl_hrd_parameters;
1281       const guint8 nbits = hrd->initial_cpb_removal_delay_length_minus1 + 1;
1282       guint8 sched_sel_idx;
1283
1284       for (sched_sel_idx = 0; sched_sel_idx <= hrd->cpb_cnt_minus1;
1285           sched_sel_idx++) {
1286         WRITE_BITS (bw, per->vcl_initial_cpb_removal_delay[sched_sel_idx],
1287             nbits);
1288         WRITE_BITS (bw,
1289             per->vcl_initial_cpb_removal_delay_offset[sched_sel_idx], nbits);
1290       }
1291     }
1292   }
1293
1294   *space = TRUE;
1295   return TRUE;
1296
1297 error:
1298   GST_WARNING ("Failed to write \"Buffering period\"");
1299
1300   *space = have_space;
1301   return FALSE;
1302 }
1303
1304 static gboolean
1305 _h264_bit_writer_sei_message (const GstH264SEIMessage * msg,
1306     GstBitWriter * bw, gboolean * space)
1307 {
1308   gboolean have_space = TRUE;
1309
1310   GST_DEBUG ("writing SEI message");
1311
1312   switch (msg->payloadType) {
1313     case GST_H264_SEI_REGISTERED_USER_DATA:
1314       if (!_h264_bit_writer_sei_registered_user_data
1315           (&msg->payload.registered_user_data, bw, &have_space))
1316         goto error;
1317       break;
1318     case GST_H264_SEI_FRAME_PACKING:
1319       if (!_h264_bit_writer_sei_frame_packing
1320           (&msg->payload.frame_packing, bw, &have_space))
1321         goto error;
1322       break;
1323     case GST_H264_SEI_MASTERING_DISPLAY_COLOUR_VOLUME:
1324       if (!_h264_bit_writer_sei_mastering_display_colour_volume
1325           (&msg->payload.mastering_display_colour_volume, bw, &have_space))
1326         goto error;
1327       break;
1328     case GST_H264_SEI_CONTENT_LIGHT_LEVEL:
1329       if (!_h264_bit_writer_sei_content_light_level_info
1330           (&msg->payload.content_light_level, bw, &have_space))
1331         goto error;
1332       break;
1333     case GST_H264_SEI_PIC_TIMING:
1334       if (!_h264_bit_writer_sei_pic_timing (&msg->payload.pic_timing, bw,
1335               &have_space))
1336         goto error;
1337       break;
1338     case GST_H264_SEI_BUF_PERIOD:
1339       if (!_h264_bit_writer_sei_buffering_period
1340           (&msg->payload.buffering_period, bw, &have_space))
1341         goto error;
1342       break;
1343     default:
1344       break;
1345   }
1346
1347   /* Add trailings. */
1348   WRITE_BITS (bw, 1, 1);
1349   gst_bit_writer_align_bytes_unchecked (bw, 0);
1350
1351   *space = TRUE;
1352
1353   return TRUE;
1354
1355 error:
1356   GST_WARNING ("error to write SEI message");
1357
1358   *space = have_space;
1359   return FALSE;
1360 }
1361
1362 /**
1363  * gst_h264_bit_writer_sei:
1364  * @sei_messages: An array of #GstH264SEIMessage to write
1365  * @start_code: whether adding the nal start code
1366  * @data: (out): the bit stream generated by the sei messages
1367  * @size: (inout): the size in bits of the output
1368  *
1369  * Generating the according h264 bit stream by providing sei messages.
1370  *
1371  * Returns: a #GstH264BitWriterResult
1372  *
1373  * Since: 1.22
1374  **/
1375 GstH264BitWriterResult
1376 gst_h264_bit_writer_sei (GArray * sei_messages, gboolean start_code,
1377     guint8 * data, gsize * size)
1378 {
1379   gboolean have_space = TRUE;
1380   GstBitWriter bw;
1381   GstBitWriter bw_msg;
1382   GstH264SEIMessage *sei;
1383   gboolean have_written_data = FALSE;
1384   guint i;
1385
1386   g_return_val_if_fail (sei_messages != NULL, GST_H264_BIT_WRITER_ERROR);
1387   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
1388   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
1389   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
1390
1391   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
1392
1393   if (start_code)
1394     WRITE_BITS (&bw, 0x00000001, 32);
1395
1396   /* nal header */
1397   /* forbidden_zero_bit */
1398   WRITE_BITS (&bw, 0, 1);
1399   /* nal_ref_idc, zero for sei nalu */
1400   WRITE_BITS (&bw, 0, 2);
1401   /* nal_unit_type */
1402   WRITE_BITS (&bw, GST_H264_NAL_SEI, 5);
1403
1404   for (i = 0; i < sei_messages->len; i++) {
1405     guint32 payload_size_data;
1406     guint32 payload_type_data;
1407     guint32 sz;
1408
1409     gst_bit_writer_init (&bw_msg);
1410
1411     sei = &g_array_index (sei_messages, GstH264SEIMessage, i);
1412     if (!_h264_bit_writer_sei_message (sei, &bw_msg, &have_space))
1413       goto error;
1414
1415     if (gst_bit_writer_get_size (&bw_msg) == 0) {
1416       GST_FIXME ("Unsupported SEI type %d", sei->payloadType);
1417       continue;
1418     }
1419
1420     have_written_data = TRUE;
1421
1422     g_assert (gst_bit_writer_get_size (&bw_msg) % 8 == 0);
1423     payload_size_data = gst_bit_writer_get_size (&bw_msg) / 8;
1424     payload_type_data = sei->payloadType;
1425
1426     /* write payload type bytes */
1427     while (payload_type_data >= 0xff) {
1428       WRITE_BITS (&bw, 0xff, 8);
1429       payload_type_data -= 0xff;
1430     }
1431     WRITE_BITS (&bw, payload_type_data, 8);
1432
1433     /* write payload size bytes */
1434     sz = payload_size_data;
1435     while (sz >= 0xff) {
1436       WRITE_BITS (&bw, 0xff, 8);
1437       sz -= 0xff;
1438     }
1439     WRITE_BITS (&bw, sz, 8);
1440
1441     if (payload_size_data > 0)
1442       WRITE_BYTES (&bw, gst_bit_writer_get_data (&bw_msg), payload_size_data);
1443
1444     gst_bit_writer_reset (&bw_msg);
1445   }
1446
1447   if (!have_written_data) {
1448     GST_WARNING ("No written sei data");
1449     goto error;
1450   }
1451
1452   /* Add trailings. */
1453   WRITE_BITS (&bw, 1, 1);
1454   if (!gst_bit_writer_align_bytes (&bw, 0)) {
1455     have_space = FALSE;
1456     goto error;
1457   }
1458
1459   *size = gst_bit_writer_get_size (&bw);
1460   gst_bit_writer_reset (&bw);
1461   return GST_H264_BIT_WRITER_OK;
1462
1463 error:
1464   gst_bit_writer_reset (&bw);
1465   *size = 0;
1466
1467   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1468       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1469 }
1470
1471 /**
1472  * gst_h264_bit_writer_aud:
1473  * @primary_pic_type: indicate the possible slice types list just
1474  *   as the H264 spec defines
1475  * @start_code: whether adding the nal start code
1476  * @data: (out): the bit stream generated by the aud
1477  * @size: (inout): the size in bits of the output
1478  *
1479  * Generating the according h264 bit stream of an aud.
1480  *
1481  * Returns: a #GstH264BitWriterResult
1482  *
1483  * Since: 1.22
1484  **/
1485 GstH264BitWriterResult
1486 gst_h264_bit_writer_aud (guint8 primary_pic_type, gboolean start_code,
1487     guint8 * data, gsize * size)
1488 {
1489   gboolean have_space = TRUE;
1490   GstBitWriter bw;
1491
1492   g_return_val_if_fail (primary_pic_type >= 0
1493       && primary_pic_type <= 7, GST_H264_BIT_WRITER_ERROR);
1494   g_return_val_if_fail (data != NULL, GST_H264_BIT_WRITER_ERROR);
1495   g_return_val_if_fail (size != NULL, GST_H264_BIT_WRITER_ERROR);
1496   g_return_val_if_fail (*size > 0, GST_H264_BIT_WRITER_ERROR);
1497
1498   gst_bit_writer_init_with_data (&bw, data, *size, FALSE);
1499
1500   if (start_code)
1501     WRITE_BITS (&bw, 0x00000001, 32);
1502
1503   /* nal header */
1504   /* forbidden_zero_bit */
1505   WRITE_BITS (&bw, 0, 1);
1506   /* nal_ref_idc */
1507   WRITE_BITS (&bw, 0, 2);
1508   /* nal_unit_type */
1509   WRITE_BITS (&bw, GST_H264_NAL_AU_DELIMITER, 5);
1510
1511   WRITE_BITS (&bw, primary_pic_type, 3);
1512
1513   /* Add trailings. */
1514   WRITE_BITS (&bw, 1, 1);
1515   if (!gst_bit_writer_align_bytes (&bw, 0)) {
1516     goto error;
1517   }
1518
1519   *size = gst_bit_writer_get_size (&bw);
1520   gst_bit_writer_reset (&bw);
1521
1522   return GST_H264_BIT_WRITER_OK;
1523
1524 error:
1525   gst_bit_writer_reset (&bw);
1526   *size = 0;
1527
1528   return have_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1529       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1530 }
1531
1532 /**
1533  * gst_h264_bit_writer_convert_to_nal:
1534  * @nal_prefix_size: the size in bytes for the prefix of a nal, may
1535  *   be 2, 3 or 4
1536  * @packetized: whether to write the bit stream in packetized format,
1537  *   which does not have the start code but has a @nal_prefix_size bytes'
1538  *   size prepending to the real nal data
1539  * @has_startcode: whether the input already has a start code
1540  * @add_trailings: whether to add rbsp trailing bits to make the output
1541  *   aligned to byte
1542  * @raw_data: the input bit stream
1543  * @raw_size: the size in bits of the input bit stream
1544  * @nal_data: (out): the output bit stream converted to a real nal
1545  * @nal_size: (inout): the size in bytes of the output
1546  *
1547  * Converting a bit stream into a real nal packet. If the bit stream already
1548  * has a start code, it will be replaced by the new one specified by the
1549  * @nal_prefix_size and @packetized. It is assured that the output aligns to
1550  * the byte and the all the emulations are inserted.
1551  *
1552  * Returns: a #GstH264BitWriterResult
1553  *
1554  * Since: 1.22
1555  **/
1556 GstH264BitWriterResult
1557 gst_h264_bit_writer_convert_to_nal (guint nal_prefix_size, gboolean packetized,
1558     gboolean has_startcode, gboolean add_trailings, const guint8 * raw_data,
1559     gsize raw_size, guint8 * nal_data, guint32 * nal_size)
1560 {
1561   NalWriter nw;
1562   guint8 *data;
1563   guint32 size = 0;
1564   gboolean need_more_space = FALSE;
1565
1566   g_return_val_if_fail (
1567       (packetized && nal_prefix_size > 1 && nal_prefix_size < 5) ||
1568       (!packetized && (nal_prefix_size == 3 || nal_prefix_size == 4)),
1569       GST_H264_BIT_WRITER_ERROR);
1570   g_return_val_if_fail (raw_data != NULL, GST_H264_BIT_WRITER_ERROR);
1571   g_return_val_if_fail (raw_size > 0, GST_H264_BIT_WRITER_ERROR);
1572   g_return_val_if_fail (nal_data != NULL, GST_H264_BIT_WRITER_ERROR);
1573   g_return_val_if_fail (nal_size != NULL, GST_H264_BIT_WRITER_ERROR);
1574   g_return_val_if_fail (*nal_size > 0, GST_H264_BIT_WRITER_ERROR);
1575
1576   if (has_startcode) {
1577     /* Skip the start code, the NalWriter will add it automatically. */
1578     if (raw_size >= 4 && raw_data[0] == 0
1579         && raw_data[1] == 0 && raw_data[2] == 0 && raw_data[3] == 0x01) {
1580       raw_data += 4;
1581       raw_size -= 4 * 8;
1582     } else if (raw_size >= 3 && raw_data[0] == 0 && raw_data[1] == 0
1583         && raw_data[2] == 0x01) {
1584       raw_data += 3;
1585       raw_size -= 3 * 8;
1586     } else {
1587       /* Fail to find the start code. */
1588       g_return_val_if_reached (GST_H264_BIT_WRITER_ERROR);
1589     }
1590   }
1591
1592   /* If no RBSP trailing needed, it must align to byte. We assume
1593      that the rbsp trailing bits are already added. */
1594   if (!add_trailings)
1595     g_return_val_if_fail (raw_size % 8 == 0, GST_H264_BIT_WRITER_ERROR);
1596
1597   nal_writer_init (&nw, nal_prefix_size, packetized);
1598
1599   if (!nal_writer_put_bytes (&nw, raw_data, raw_size / 8))
1600     goto error;
1601
1602   if (raw_size % 8) {
1603     guint8 data = *(raw_data + raw_size / 8);
1604
1605     if (!nal_writer_put_bits_uint8 (&nw,
1606             data >> (8 - raw_size % 8), raw_size % 8))
1607       goto error;
1608   }
1609
1610   if (add_trailings) {
1611     if (!nal_writer_do_rbsp_trailing_bits (&nw))
1612       goto error;
1613   }
1614
1615   data = nal_writer_reset_and_get_data (&nw, &size);
1616   if (!data)
1617     goto error;
1618
1619   if (size > *nal_size) {
1620     need_more_space = TRUE;
1621     g_free (data);
1622     goto error;
1623   }
1624
1625   memcpy (nal_data, data, size);
1626   *nal_size = size;
1627   g_free (data);
1628   nal_writer_reset (&nw);
1629   return GST_H264_BIT_WRITER_OK;
1630
1631 error:
1632   nal_writer_reset (&nw);
1633   *nal_size = 0;
1634
1635   GST_WARNING ("Failed to convert nal data");
1636
1637   return need_more_space ? GST_H264_BIT_WRITER_INVALID_DATA :
1638       GST_H264_BIT_WRITER_NO_MORE_SPACE;
1639 }