DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs
h264_parser.h
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // This file contains an implementation of an H264 Annex-B video stream parser.
6 
7 #ifndef MEDIA_FILTERS_H264_PARSER_H_
8 #define MEDIA_FILTERS_H264_PARSER_H_
9 
10 #include <stdint.h>
11 #include <sys/types.h>
12 
13 #include <map>
14 
15 #include "packager/media/filters/h264_bit_reader.h"
16 
17 namespace edash_packager {
18 namespace media {
19 
20 // |avc_decoder_config_data| must be AVCDecoderConfigurationRecord specified
21 // in ISO/IEC 14496-15.
22 // On success, |coded_width| and |coded_height| contains coded resolution after
23 // cropping; |pixel_width:pixel_height| contains pixel aspect ratio, 1:1 is
24 // assigned if it is not present.
25 bool ExtractResolutionFromDecoderConfig(const uint8_t* avc_decoder_config_data,
26  size_t avc_decoder_config_data_size,
27  uint32_t* coded_width,
28  uint32_t* coded_height,
29  uint32_t* pixel_width,
30  uint32_t* pixel_height);
31 
32 // |sps_data| must be a valid SPS specified in ISO/IEC 14496-10.
33 // On success, |coded_width| and |coded_height| contains coded resolution after
34 // cropping; |pixel_width:pixel_height| contains pixel aspect ratio, 1:1 is
35 // assigned if it is not present in SPS.
36 bool ExtractResolutionFromSpsData(const uint8_t* sps_data,
37  size_t sps_data_size,
38  uint32_t* coded_width,
39  uint32_t* coded_height,
40  uint32_t* pixel_width,
41  uint32_t* pixel_height);
42 struct H264SPS;
43 bool ExtractResolutionFromSps(const H264SPS& sps,
44  uint32_t* coded_width,
45  uint32_t* coded_height,
46  uint32_t* pixel_width,
47  uint32_t* pixel_height);
48 
49 // For explanations of each struct and its members, see H.264 specification
50 // at http://www.itu.int/rec/T-REC-H.264.
51 struct H264NALU {
52  H264NALU();
53 
54  enum Type {
55  kUnspecified = 0,
56  kNonIDRSlice = 1,
57  kIDRSlice = 5,
58  kSEIMessage = 6,
59  kSPS = 7,
60  kPPS = 8,
61  kAUD = 9,
62  kEOSeq = 10,
63  kEOStream = 11,
64  kCodedSliceExtension = 20,
65  };
66 
67  // After (without) start code; we don't own the underlying memory
68  // and a shallow copy should be made when copying this struct.
69  const uint8_t* data;
70  off_t size; // From after start code to start code of next NALU (or EOS).
71 
72  int nal_ref_idc;
73  int nal_unit_type;
74 };
75 
76 enum {
77  kH264ScalingList4x4Length = 16,
78  kH264ScalingList8x8Length = 64,
79 };
80 
81 struct H264SPS {
82  H264SPS();
83 
84  int profile_idc;
85  bool constraint_set0_flag;
86  bool constraint_set1_flag;
87  bool constraint_set2_flag;
88  bool constraint_set3_flag;
89  bool constraint_set4_flag;
90  bool constraint_set5_flag;
91  int level_idc;
92  int seq_parameter_set_id;
93 
94  int chroma_format_idc;
95  bool separate_colour_plane_flag;
96  int bit_depth_luma_minus8;
97  int bit_depth_chroma_minus8;
98  bool qpprime_y_zero_transform_bypass_flag;
99 
100  bool seq_scaling_matrix_present_flag;
101  int scaling_list4x4[6][kH264ScalingList4x4Length];
102  int scaling_list8x8[6][kH264ScalingList8x8Length];
103 
104  int log2_max_frame_num_minus4;
105  int pic_order_cnt_type;
106  int log2_max_pic_order_cnt_lsb_minus4;
107  bool delta_pic_order_always_zero_flag;
108  int offset_for_non_ref_pic;
109  int offset_for_top_to_bottom_field;
110  int num_ref_frames_in_pic_order_cnt_cycle;
111  int expected_delta_per_pic_order_cnt_cycle; // calculated
112  int offset_for_ref_frame[255];
113  int max_num_ref_frames;
114  bool gaps_in_frame_num_value_allowed_flag;
115  int pic_width_in_mbs_minus1;
116  int pic_height_in_map_units_minus1;
117  bool frame_mbs_only_flag;
118  bool mb_adaptive_frame_field_flag;
119  bool direct_8x8_inference_flag;
120  bool frame_cropping_flag;
121  int frame_crop_left_offset;
122  int frame_crop_right_offset;
123  int frame_crop_top_offset;
124  int frame_crop_bottom_offset;
125 
126  bool vui_parameters_present_flag;
127  int sar_width; // Set to 0 when not specified.
128  int sar_height; // Set to 0 when not specified.
129  bool bitstream_restriction_flag;
130  int max_num_reorder_frames;
131  int max_dec_frame_buffering;
132 
133  int chroma_array_type;
134 };
135 
136 struct H264PPS {
137  H264PPS();
138 
139  int pic_parameter_set_id;
140  int seq_parameter_set_id;
141  bool entropy_coding_mode_flag;
142  bool bottom_field_pic_order_in_frame_present_flag;
143  int num_slice_groups_minus1;
144  int num_ref_idx_l0_default_active_minus1;
145  int num_ref_idx_l1_default_active_minus1;
146  bool weighted_pred_flag;
147  int weighted_bipred_idc;
148  int pic_init_qp_minus26;
149  int pic_init_qs_minus26;
150  int chroma_qp_index_offset;
151  bool deblocking_filter_control_present_flag;
152  bool constrained_intra_pred_flag;
153  bool redundant_pic_cnt_present_flag;
154  bool transform_8x8_mode_flag;
155 
156  bool pic_scaling_matrix_present_flag;
157  int scaling_list4x4[6][kH264ScalingList4x4Length];
158  int scaling_list8x8[6][kH264ScalingList8x8Length];
159 
160  int second_chroma_qp_index_offset;
161 };
162 
164  int modification_of_pic_nums_idc;
165  union {
166  int abs_diff_pic_num_minus1;
167  int long_term_pic_num;
168  };
169 };
170 
172  bool luma_weight_flag;
173  bool chroma_weight_flag;
174  int luma_weight[32];
175  int luma_offset[32];
176  int chroma_weight[32][2];
177  int chroma_offset[32][2];
178 };
179 
181  int memory_mgmnt_control_operation;
182  int difference_of_pic_nums_minus1;
183  int long_term_pic_num;
184  int long_term_frame_idx;
185  int max_long_term_frame_idx_plus1;
186 };
187 
189  H264SliceHeader();
190 
191  enum {
192  kRefListSize = 32,
193  kRefListModSize = kRefListSize
194  };
195 
196  enum Type {
197  kPSlice = 0,
198  kBSlice = 1,
199  kISlice = 2,
200  kSPSlice = 3,
201  kSISlice = 4,
202  };
203 
204  bool IsPSlice() const;
205  bool IsBSlice() const;
206  bool IsISlice() const;
207  bool IsSPSlice() const;
208  bool IsSISlice() const;
209 
210  bool idr_pic_flag; // from NAL header
211  int nal_ref_idc; // from NAL header
212  const uint8_t* nalu_data; // from NAL header
213  off_t nalu_size; // from NAL header
214  off_t header_bit_size; // calculated
215 
216  int first_mb_in_slice;
217  int slice_type;
218  int pic_parameter_set_id;
219  int colour_plane_id;
220  int frame_num;
221  bool field_pic_flag;
222  bool bottom_field_flag;
223  int idr_pic_id;
224  int pic_order_cnt_lsb;
225  int delta_pic_order_cnt_bottom;
226  int delta_pic_order_cnt[2];
227  int redundant_pic_cnt;
228  bool direct_spatial_mv_pred_flag;
229 
230  bool num_ref_idx_active_override_flag;
231  int num_ref_idx_l0_active_minus1;
232  int num_ref_idx_l1_active_minus1;
233  bool ref_pic_list_modification_flag_l0;
234  bool ref_pic_list_modification_flag_l1;
235  H264ModificationOfPicNum ref_list_l0_modifications[kRefListModSize];
236  H264ModificationOfPicNum ref_list_l1_modifications[kRefListModSize];
237 
238  int luma_log2_weight_denom;
239  int chroma_log2_weight_denom;
240 
241  bool luma_weight_l0_flag;
242  bool chroma_weight_l0_flag;
243  H264WeightingFactors pred_weight_table_l0;
244 
245  bool luma_weight_l1_flag;
246  bool chroma_weight_l1_flag;
247  H264WeightingFactors pred_weight_table_l1;
248 
249  bool no_output_of_prior_pics_flag;
250  bool long_term_reference_flag;
251 
252  bool adaptive_ref_pic_marking_mode_flag;
253  H264DecRefPicMarking ref_pic_marking[kRefListSize];
254 
255  int cabac_init_idc;
256  int slice_qp_delta;
257  bool sp_for_switch_flag;
258  int slice_qs_delta;
259  int disable_deblocking_filter_idc;
260  int slice_alpha_c0_offset_div2;
261  int slice_beta_offset_div2;
262 };
263 
265  int recovery_frame_cnt;
266  bool exact_match_flag;
267  bool broken_link_flag;
268  int changing_slice_group_idc;
269 };
270 
272  H264SEIMessage();
273 
274  enum Type {
275  kSEIRecoveryPoint = 6,
276  };
277 
278  int type;
279  int payload_size;
280  union {
281  // Placeholder; in future more supported types will contribute to more
282  // union members here.
283  H264SEIRecoveryPoint recovery_point;
284  };
285 };
286 
287 // Class to parse an Annex-B H.264 stream,
288 // as specified in chapters 7 and Annex B of the H.264 spec.
289 class H264Parser {
290  public:
291  enum Result {
292  kOk,
293  kInvalidStream, // error in stream
294  kUnsupportedStream, // stream not supported by the parser
295  kEOStream, // end of stream
296  };
297 
298  // Find offset from start of data to next NALU start code
299  // and size of found start code (3 or 4 bytes).
300  // If no start code is found, offset is pointing to the first unprocessed byte
301  // (i.e. the first byte that was not considered as a possible start of a start
302  // code) and |*start_code_size| is set to 0.
303  // Preconditions:
304  // - |data_size| >= 0
305  // Postconditions:
306  // - |*offset| is between 0 and |data_size| included.
307  // It is strictly less than |data_size| if |data_size| > 0.
308  // - |*start_code_size| is either 0, 3 or 4.
309  static bool FindStartCode(const uint8_t* data,
310  off_t data_size,
311  off_t* offset,
312  off_t* start_code_size);
313 
314  H264Parser();
315  ~H264Parser();
316 
317  void Reset();
318  // Set current stream pointer to |stream| of |stream_size| in bytes,
319  // |stream| owned by caller.
320  void SetStream(const uint8_t* stream, off_t stream_size);
321 
322  // Read the stream to find the next NALU, identify it and return
323  // that information in |*nalu|. This advances the stream to the beginning
324  // of this NALU, but not past it, so subsequent calls to NALU-specific
325  // parsing functions (ParseSPS, etc.) will parse this NALU.
326  // If the caller wishes to skip the current NALU, it can call this function
327  // again, instead of any NALU-type specific parse functions below.
328  Result AdvanceToNextNALU(H264NALU* nalu);
329 
330  // NALU-specific parsing functions.
331  // These should be called after AdvanceToNextNALU().
332 
333  // SPSes and PPSes are owned by the parser class and the memory for their
334  // structures is managed here, not by the caller, as they are reused
335  // across NALUs.
336  //
337  // Parse an SPS/PPS NALU and save their data in the parser, returning id
338  // of the parsed structure in |*pps_id|/|*sps_id|.
339  // To get a pointer to a given SPS/PPS structure, use GetSPS()/GetPPS(),
340  // passing the returned |*sps_id|/|*pps_id| as parameter.
341  // methods with a scoped_ptr and adding an AtEOS() function to check for EOS
342  // if Parse*() return NULL.
343  Result ParseSPS(int* sps_id);
344  Result ParsePPS(int* pps_id);
345 
346  // Samme as ParseSPS but instead uses |sps_data|.
347  Result ParseSPSFromArray(const uint8_t* sps_data,
348  size_t sps_data_size,
349  int* sps_id);
350 
351  // Return a pointer to SPS/PPS with given |sps_id|/|pps_id| or NULL if not
352  // present.
353  const H264SPS* GetSPS(int sps_id);
354  const H264PPS* GetPPS(int pps_id);
355 
356  // Slice headers and SEI messages are not used across NALUs by the parser
357  // and can be discarded after current NALU, so the parser does not store
358  // them, nor does it manage their memory.
359  // The caller has to provide and manage it instead.
360 
361  // Parse a slice header, returning it in |*shdr|. |*nalu| must be set to
362  // the NALU returned from AdvanceToNextNALU() and corresponding to |*shdr|.
363  Result ParseSliceHeader(const H264NALU& nalu, H264SliceHeader* shdr);
364 
365  // Parse a SEI message, returning it in |*sei_msg|, provided and managed
366  // by the caller.
367  Result ParseSEI(H264SEIMessage* sei_msg);
368 
369  private:
370  // Move the stream pointer to the beginning of the next NALU,
371  // i.e. pointing at the next start code.
372  // Return true if a NALU has been found.
373  // If a NALU is found:
374  // - its size in bytes is returned in |*nalu_size| and includes
375  // the start code as well as the trailing zero bits.
376  // - the size in bytes of the start code is returned in |*start_code_size|.
377  bool LocateNALU(off_t* nalu_size, off_t* start_code_size);
378 
379  // Exp-Golomb code parsing as specified in chapter 9.1 of the spec.
380  // Read one unsigned exp-Golomb code from the stream and return in |*val|.
381  Result ReadUE(int* val);
382 
383  // Read one signed exp-Golomb code from the stream and return in |*val|.
384  Result ReadSE(int* val);
385 
386  // Parse scaling lists (see spec).
387  Result ParseScalingList(int size, int* scaling_list, bool* use_default);
388  Result ParseSPSScalingLists(H264SPS* sps);
389  Result ParsePPSScalingLists(const H264SPS& sps, H264PPS* pps);
390 
391  // Parse optional VUI parameters in SPS (see spec).
392  Result ParseVUIParameters(H264SPS* sps);
393  // Set |hrd_parameters_present| to true only if they are present.
394  Result ParseAndIgnoreHRDParameters(bool* hrd_parameters_present);
395 
396  // Parse reference picture lists' modifications (see spec).
397  Result ParseRefPicListModifications(H264SliceHeader* shdr);
398  Result ParseRefPicListModification(int num_ref_idx_active_minus1,
399  H264ModificationOfPicNum* ref_list_mods);
400 
401  // Parse prediction weight table (see spec).
402  Result ParsePredWeightTable(const H264SPS& sps, H264SliceHeader* shdr);
403 
404  // Parse weighting factors (see spec).
405  Result ParseWeightingFactors(int num_ref_idx_active_minus1,
406  int chroma_array_type,
407  int luma_log2_weight_denom,
408  int chroma_log2_weight_denom,
409  H264WeightingFactors* w_facts);
410 
411  // Parse decoded reference picture marking information (see spec).
412  Result ParseDecRefPicMarking(H264SliceHeader* shdr);
413 
414  // Pointer to the current NALU in the stream.
415  const uint8_t* stream_;
416 
417  // Bytes left in the stream after the current NALU.
418  off_t bytes_left_;
419 
420  H264BitReader br_;
421 
422  // PPSes and SPSes stored for future reference.
423  typedef std::map<int, H264SPS*> SPSById;
424  typedef std::map<int, H264PPS*> PPSById;
425  SPSById active_SPSes_;
426  PPSById active_PPSes_;
427 
428  DISALLOW_COPY_AND_ASSIGN(H264Parser);
429 };
430 
431 } // namespace media
432 } // namespace edash_packager
433 
434 #endif // MEDIA_FILTERS_H264_PARSER_H_