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