1 /*
2  * gstvp8parser.c - VP8 parser
3  *
4  * Copyright (C) 2013-2014 Intel Corporation
5  *   Author: Halley Zhao <halley.zhao@intel.com>
6  *   Author: Gwenole Beauchesne <gwenole.beauchesne@intel.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 
24 /**
25  * SECTION:gstvp8parser
26  * @title: GstVp8Parser
27  * @short_description: Convenience library for parsing vp8 video bitstream.
28  *
29  * For more details about the structures, you can refer to the
30  * specifications: VP8-rfc6386.pdf
31  */
32 
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36 #include <string.h>
37 #include <gst/base/gstbytereader.h>
38 #include "gstvp8parser.h"
39 #include "gstvp8rangedecoder.h"
40 #include "vp8utils.h"
41 
42 GST_DEBUG_CATEGORY_STATIC (vp8_parser_debug);
43 #define GST_CAT_DEFAULT vp8_parser_debug
44 
45 #define INITIALIZE_DEBUG_CATEGORY ensure_debug_category ()
46 static void
ensure_debug_category(void)47 ensure_debug_category (void)
48 {
49 #ifndef GST_DISABLE_GST_DEBUG
50   static gsize is_initialized;
51 
52   if (g_once_init_enter (&is_initialized)) {
53     GST_DEBUG_CATEGORY_INIT (vp8_parser_debug, "codecparsers_vp8", 0,
54         "vp8 parser library");
55     g_once_init_leave (&is_initialized, TRUE);
56   }
57 #endif
58 }
59 
60 static GstVp8MvProbs vp8_mv_update_probs;
61 static GstVp8TokenProbs vp8_token_update_probs;
62 
63 static void
ensure_prob_tables(void)64 ensure_prob_tables (void)
65 {
66   static gsize is_initialized;
67 
68   if (g_once_init_enter (&is_initialized)) {
69     gst_vp8_mv_update_probs_init (&vp8_mv_update_probs);
70     gst_vp8_token_update_probs_init (&vp8_token_update_probs);
71     g_once_init_leave (&is_initialized, TRUE);
72   }
73 }
74 
75 #define READ_BOOL(rd, val, field_name) \
76   val = vp8_read_bool ((rd))
77 #define READ_UINT(rd, val, nbits, field_name) \
78   val = vp8_read_uint ((rd), (nbits))
79 #define READ_SINT(rd, val, nbits, field_name) \
80   val = vp8_read_sint ((rd), (nbits))
81 
82 static inline gboolean
vp8_read_bool(GstVp8RangeDecoder * rd)83 vp8_read_bool (GstVp8RangeDecoder * rd)
84 {
85   return (gboolean) gst_vp8_range_decoder_read_literal (rd, 1);
86 }
87 
88 static inline guint
vp8_read_uint(GstVp8RangeDecoder * rd,guint nbits)89 vp8_read_uint (GstVp8RangeDecoder * rd, guint nbits)
90 {
91   return (guint) gst_vp8_range_decoder_read_literal (rd, nbits);
92 }
93 
94 static inline gint
vp8_read_sint(GstVp8RangeDecoder * rd,guint nbits)95 vp8_read_sint (GstVp8RangeDecoder * rd, guint nbits)
96 {
97   gint v;
98 
99   v = gst_vp8_range_decoder_read_literal (rd, nbits);
100   if (gst_vp8_range_decoder_read_literal (rd, 1))
101     v = -v;
102   return v;
103 }
104 
105 /* Parse update_segmentation() */
106 static gboolean
parse_update_segmentation(GstVp8RangeDecoder * rd,GstVp8Segmentation * seg)107 parse_update_segmentation (GstVp8RangeDecoder * rd, GstVp8Segmentation * seg)
108 {
109   gboolean update;
110   gint i;
111 
112   seg->update_mb_segmentation_map = FALSE;
113   seg->update_segment_feature_data = FALSE;
114 
115   READ_BOOL (rd, seg->segmentation_enabled, "segmentation_enabled");
116   if (!seg->segmentation_enabled)
117     return TRUE;
118 
119   READ_BOOL (rd, seg->update_mb_segmentation_map, "update_mb_segmentation_map");
120   READ_BOOL (rd, seg->update_segment_feature_data,
121       "update_segment_feature_data");
122 
123   if (seg->update_segment_feature_data) {
124     READ_UINT (rd, seg->segment_feature_mode, 1, "segment_feature_mode");
125 
126     /* quantizer_update_value defaults to zero if update flag is zero
127        (Section 9.3, 4.b) */
128     for (i = 0; i < 4; i++) {
129       READ_BOOL (rd, update, "quantizer_update");
130       if (update) {
131         READ_SINT (rd, seg->quantizer_update_value[i], 7,
132             "quantizer_update_value");
133       } else
134         seg->quantizer_update_value[i] = 0;
135     }
136 
137     /* lf_update_value defaults to zero if update flag is zero
138        (Section 9.3, 4.b) */
139     for (i = 0; i < 4; i++) {
140       READ_BOOL (rd, update, "loop_filter_update");
141       if (update) {
142         READ_SINT (rd, seg->lf_update_value[i], 6, "lf_update_value");
143       } else
144         seg->lf_update_value[i] = 0;
145     }
146   }
147 
148   /* segment_prob defaults to 255 if update flag is zero
149      (Section 9.3, 5) */
150   if (seg->update_mb_segmentation_map) {
151     for (i = 0; i < 3; i++) {
152       READ_BOOL (rd, update, "segment_prob_update");
153       if (update) {
154         READ_UINT (rd, seg->segment_prob[i], 8, "segment_prob");
155       } else
156         seg->segment_prob[i] = 255;
157     }
158   }
159   return TRUE;
160 }
161 
162 /* Parse mb_lf_adjustments() to update loop filter delta adjustments */
163 static gboolean
parse_mb_lf_adjustments(GstVp8RangeDecoder * rd,GstVp8MbLfAdjustments * adj)164 parse_mb_lf_adjustments (GstVp8RangeDecoder * rd, GstVp8MbLfAdjustments * adj)
165 {
166   gboolean update;
167   gint i;
168 
169   adj->mode_ref_lf_delta_update = FALSE;
170 
171   READ_BOOL (rd, adj->loop_filter_adj_enable, "loop_filter_adj_enable");
172   if (!adj->loop_filter_adj_enable)
173     return TRUE;
174 
175   READ_BOOL (rd, adj->mode_ref_lf_delta_update, "mode_ref_lf_delta_update");
176   if (!adj->mode_ref_lf_delta_update)
177     return TRUE;
178 
179   for (i = 0; i < 4; i++) {
180     READ_BOOL (rd, update, "ref_frame_delta_update_flag");
181     if (update) {
182       READ_SINT (rd, adj->ref_frame_delta[i], 6, "ref_frame_delta_magniture");
183     }
184   }
185 
186   for (i = 0; i < 4; i++) {
187     READ_BOOL (rd, update, "mb_mode_delta_update_flag");
188     if (update) {
189       READ_SINT (rd, adj->mb_mode_delta[i], 6, "mb_mode_delta_magnitude");
190     }
191   }
192   return TRUE;
193 }
194 
195 /* Parse quant_indices() */
196 static gboolean
parse_quant_indices(GstVp8RangeDecoder * rd,GstVp8QuantIndices * qip)197 parse_quant_indices (GstVp8RangeDecoder * rd, GstVp8QuantIndices * qip)
198 {
199   gboolean update;
200 
201   READ_UINT (rd, qip->y_ac_qi, 7, "y_ac_qi");
202 
203   READ_BOOL (rd, update, "y_dc_delta_present");
204   if (update) {
205     READ_SINT (rd, qip->y_dc_delta, 4, "y_dc_delta_magnitude");
206   } else
207     qip->y_dc_delta = 0;
208 
209   READ_BOOL (rd, update, "y2_dc_delta_present");
210   if (update) {
211     READ_SINT (rd, qip->y2_dc_delta, 4, "y2_dc_delta_magnitude");
212   } else
213     qip->y2_dc_delta = 0;
214 
215   READ_BOOL (rd, update, "y2_ac_delta_present");
216   if (update) {
217     READ_SINT (rd, qip->y2_ac_delta, 4, "y2_ac_delta_magnitude");
218   } else
219     qip->y2_ac_delta = 0;
220 
221   READ_BOOL (rd, update, "uv_dc_delta_present");
222   if (update) {
223     READ_SINT (rd, qip->uv_dc_delta, 4, "uv_dc_delta_magnitude");
224   } else
225     qip->uv_dc_delta = 0;
226 
227   READ_BOOL (rd, update, "uv_ac_delta_present");
228   if (update) {
229     READ_SINT (rd, qip->uv_ac_delta, 4, "uv_ac_delta_magnitude");
230   } else
231     qip->uv_ac_delta = 0;
232 
233   return TRUE;
234 }
235 
236 /* Parse token_prob_update() to update persistent token probabilities */
237 static gboolean
parse_token_prob_update(GstVp8RangeDecoder * rd,GstVp8TokenProbs * probs)238 parse_token_prob_update (GstVp8RangeDecoder * rd, GstVp8TokenProbs * probs)
239 {
240   gint i, j, k, l;
241   guint8 prob;
242 
243   for (i = 0; i < 4; i++) {
244     for (j = 0; j < 8; j++) {
245       for (k = 0; k < 3; k++) {
246         for (l = 0; l < 11; l++) {
247           if (gst_vp8_range_decoder_read (rd,
248                   vp8_token_update_probs.prob[i][j][k][l])) {
249             READ_UINT (rd, prob, 8, "token_prob_update");
250             probs->prob[i][j][k][l] = prob;
251           }
252         }
253       }
254     }
255   }
256   return TRUE;
257 }
258 
259 /* Parse prob_update() to update probabilities used for MV decoding */
260 static gboolean
parse_mv_prob_update(GstVp8RangeDecoder * rd,GstVp8MvProbs * probs)261 parse_mv_prob_update (GstVp8RangeDecoder * rd, GstVp8MvProbs * probs)
262 {
263   gint i, j;
264   guint8 prob;
265 
266   for (i = 0; i < 2; i++) {
267     for (j = 0; j < 19; j++) {
268       if (gst_vp8_range_decoder_read (rd, vp8_mv_update_probs.prob[i][j])) {
269         READ_UINT (rd, prob, 7, "mv_prob_update");
270         probs->prob[i][j] = prob ? (prob << 1) : 1;
271       }
272     }
273   }
274   return TRUE;
275 }
276 
277 /* Calculate partition sizes */
278 static gboolean
calc_partition_sizes(GstVp8FrameHdr * frame_hdr,const guint8 * data,guint size)279 calc_partition_sizes (GstVp8FrameHdr * frame_hdr, const guint8 * data,
280     guint size)
281 {
282   const guint num_partitions = 1 << frame_hdr->log2_nbr_of_dct_partitions;
283   guint i, ofs, part_size, part_size_ofs = frame_hdr->first_part_size;
284 
285   ofs = part_size_ofs + 3 * (num_partitions - 1);
286   if (ofs > size) {
287     GST_ERROR ("not enough bytes left to parse partition sizes");
288     return FALSE;
289   }
290 
291   /* The size of the last partition is not specified (9.5) */
292   for (i = 0; i < num_partitions - 1; i++) {
293     part_size = (guint32) data[part_size_ofs + 0] |
294         ((guint32) data[part_size_ofs + 1] << 8) |
295         ((guint32) data[part_size_ofs + 2] << 16);
296     part_size_ofs += 3;
297 
298     frame_hdr->partition_size[i] = part_size;
299     ofs += part_size;
300   }
301 
302   if (ofs > size) {
303     GST_ERROR ("not enough bytes left to determine the last partition size");
304     return FALSE;
305   }
306   frame_hdr->partition_size[i] = size - ofs;
307 
308   while (++i < G_N_ELEMENTS (frame_hdr->partition_size))
309     frame_hdr->partition_size[i] = 0;
310   return TRUE;
311 }
312 
313 /* Parse uncompressed data chunk (19.1) */
314 static GstVp8ParserResult
parse_uncompressed_data_chunk(GstVp8Parser * parser,GstByteReader * br,GstVp8FrameHdr * frame_hdr)315 parse_uncompressed_data_chunk (GstVp8Parser * parser, GstByteReader * br,
316     GstVp8FrameHdr * frame_hdr)
317 {
318   guint32 frame_tag, start_code;
319   guint16 size_code;
320 
321   GST_DEBUG ("parsing \"Uncompressed Data Chunk\"");
322 
323   if (!gst_byte_reader_get_uint24_le (br, &frame_tag))
324     goto error;
325 
326   frame_hdr->key_frame = !(frame_tag & 0x01);
327   frame_hdr->version = (frame_tag >> 1) & 0x07;
328   frame_hdr->show_frame = (frame_tag >> 4) & 0x01;
329   frame_hdr->first_part_size = (frame_tag >> 5) & 0x7ffff;
330 
331   if (frame_hdr->key_frame) {
332     if (!gst_byte_reader_get_uint24_be (br, &start_code))
333       goto error;
334     if (start_code != 0x9d012a)
335       GST_WARNING ("vp8 parser: invalid start code in frame header");
336 
337     if (!gst_byte_reader_get_uint16_le (br, &size_code))
338       goto error;
339     frame_hdr->width = size_code & 0x3fff;
340     frame_hdr->horiz_scale_code = size_code >> 14;
341 
342     if (!gst_byte_reader_get_uint16_le (br, &size_code)) {
343       goto error;
344     }
345     frame_hdr->height = size_code & 0x3fff;
346     frame_hdr->vert_scale_code = (size_code >> 14);
347 
348     /* Reset parser state on key frames */
349     gst_vp8_parser_init (parser);
350   } else {
351     frame_hdr->width = 0;
352     frame_hdr->height = 0;
353     frame_hdr->horiz_scale_code = 0;
354     frame_hdr->vert_scale_code = 0;
355   }
356 
357   /* Calculated values */
358   frame_hdr->data_chunk_size = gst_byte_reader_get_pos (br);
359   return GST_VP8_PARSER_OK;
360 
361 error:
362   GST_WARNING ("error parsing \"Uncompressed Data Chunk\"");
363   return GST_VP8_PARSER_ERROR;
364 }
365 
366 /* Parse Frame Header (19.2) */
367 static GstVp8ParserResult
parse_frame_header(GstVp8Parser * parser,GstVp8RangeDecoder * rd,GstVp8FrameHdr * frame_hdr)368 parse_frame_header (GstVp8Parser * parser, GstVp8RangeDecoder * rd,
369     GstVp8FrameHdr * frame_hdr)
370 {
371   gboolean update;
372   guint i;
373 
374   GST_DEBUG ("parsing \"Frame Header\"");
375 
376   if (frame_hdr->key_frame) {
377     READ_UINT (rd, frame_hdr->color_space, 1, "color_space");
378     READ_UINT (rd, frame_hdr->clamping_type, 1, "clamping_type");
379   }
380 
381   if (!parse_update_segmentation (rd, &parser->segmentation))
382     goto error;
383 
384   READ_UINT (rd, frame_hdr->filter_type, 1, "filter_type");
385   READ_UINT (rd, frame_hdr->loop_filter_level, 6, "loop_filter_level");
386   READ_UINT (rd, frame_hdr->sharpness_level, 3, "sharpness_level");
387 
388   if (!parse_mb_lf_adjustments (rd, &parser->mb_lf_adjust))
389     goto error;
390 
391   READ_UINT (rd, frame_hdr->log2_nbr_of_dct_partitions, 2,
392       "log2_nbr_of_dct_partitions");
393 
394   if (!parse_quant_indices (rd, &frame_hdr->quant_indices))
395     goto error;
396 
397   frame_hdr->copy_buffer_to_golden = 0;
398   frame_hdr->copy_buffer_to_alternate = 0;
399   if (frame_hdr->key_frame) {
400     READ_BOOL (rd, frame_hdr->refresh_entropy_probs, "refresh_entropy_probs");
401 
402     frame_hdr->refresh_last = TRUE;
403     frame_hdr->refresh_golden_frame = TRUE;
404     frame_hdr->refresh_alternate_frame = TRUE;
405 
406     gst_vp8_mode_probs_init_defaults (&frame_hdr->mode_probs, TRUE);
407   } else {
408     READ_BOOL (rd, frame_hdr->refresh_golden_frame, "refresh_golden_frame");
409     READ_BOOL (rd, frame_hdr->refresh_alternate_frame,
410         "refresh_alternate_frame");
411 
412     if (!frame_hdr->refresh_golden_frame) {
413       READ_UINT (rd, frame_hdr->copy_buffer_to_golden, 2,
414           "copy_buffer_to_golden");
415     }
416 
417     if (!frame_hdr->refresh_alternate_frame) {
418       READ_UINT (rd, frame_hdr->copy_buffer_to_alternate, 2,
419           "copy_buffer_to_alternate");
420     }
421 
422     READ_UINT (rd, frame_hdr->sign_bias_golden, 1, "sign_bias_golden");
423     READ_UINT (rd, frame_hdr->sign_bias_alternate, 1, "sign_bias_alternate");
424     READ_BOOL (rd, frame_hdr->refresh_entropy_probs, "refresh_entropy_probs");
425     READ_BOOL (rd, frame_hdr->refresh_last, "refresh_last");
426 
427     memcpy (&frame_hdr->mode_probs, &parser->mode_probs,
428         sizeof (parser->mode_probs));
429   }
430   memcpy (&frame_hdr->token_probs, &parser->token_probs,
431       sizeof (parser->token_probs));
432   memcpy (&frame_hdr->mv_probs, &parser->mv_probs, sizeof (parser->mv_probs));
433 
434   if (!parse_token_prob_update (rd, &frame_hdr->token_probs))
435     goto error;
436 
437   READ_BOOL (rd, frame_hdr->mb_no_skip_coeff, "mb_no_skip_coeff");
438   if (frame_hdr->mb_no_skip_coeff) {
439     READ_UINT (rd, frame_hdr->prob_skip_false, 8, "prob_skip_false");
440   }
441 
442   if (!frame_hdr->key_frame) {
443     READ_UINT (rd, frame_hdr->prob_intra, 8, "prob_intra");
444     READ_UINT (rd, frame_hdr->prob_last, 8, "prob_last");
445     READ_UINT (rd, frame_hdr->prob_gf, 8, "prob_gf");
446 
447     READ_BOOL (rd, update, "intra_16x16_prob_update_flag");
448     if (update) {
449       for (i = 0; i < 4; i++) {
450         READ_UINT (rd, frame_hdr->mode_probs.y_prob[i], 8, "intra_16x16_prob");
451       }
452     }
453 
454     READ_BOOL (rd, update, "intra_chroma_prob_update_flag");
455     if (update) {
456       for (i = 0; i < 3; i++) {
457         READ_UINT (rd, frame_hdr->mode_probs.uv_prob[i], 8,
458             "intra_chroma_prob");
459       }
460     }
461 
462     if (!parse_mv_prob_update (rd, &frame_hdr->mv_probs))
463       goto error;
464   }
465 
466   /* Refresh entropy probabilities */
467   if (frame_hdr->refresh_entropy_probs) {
468     memcpy (&parser->token_probs, &frame_hdr->token_probs,
469         sizeof (frame_hdr->token_probs));
470     memcpy (&parser->mv_probs, &frame_hdr->mv_probs,
471         sizeof (frame_hdr->mv_probs));
472     if (!frame_hdr->key_frame)
473       memcpy (&parser->mode_probs, &frame_hdr->mode_probs,
474           sizeof (frame_hdr->mode_probs));
475   }
476 
477   /* Calculated values */
478   frame_hdr->header_size = gst_vp8_range_decoder_get_pos (rd);
479   return GST_VP8_PARSER_OK;
480 
481 error:
482   GST_WARNING ("error parsing \"Frame Header\"");
483   return GST_VP8_PARSER_ERROR;
484 }
485 
486 /**** API ****/
487 /**
488  * gst_vp8_parser_init:
489  * @parser: The #GstVp8Parser to initialize
490  *
491  * Initializes the supplied @parser structure with its default values.
492  *
493  * Since: 1.4
494  */
495 void
gst_vp8_parser_init(GstVp8Parser * parser)496 gst_vp8_parser_init (GstVp8Parser * parser)
497 {
498   g_return_if_fail (parser != NULL);
499 
500   memset (&parser->segmentation, 0, sizeof (parser->segmentation));
501   memset (&parser->mb_lf_adjust, 0, sizeof (parser->mb_lf_adjust));
502   gst_vp8_token_probs_init_defaults (&parser->token_probs);
503   gst_vp8_mv_probs_init_defaults (&parser->mv_probs);
504   gst_vp8_mode_probs_init_defaults (&parser->mode_probs, FALSE);
505 }
506 
507 /**
508  * gst_vp8_parser_parse_frame_header:
509  * @parser: The #GstVp8Parser
510  * @frame_hdr: The #GstVp8FrameHdr to fill
511  * @data: The data to parse
512  * @size: The size of the @data to parse
513  *
514  * Parses the VP8 bitstream contained in @data, and fills in @frame_hdr
515  * with the information. The supplied @data shall point to a complete
516  * frame since there is no sync code specified for VP8 bitstreams. Thus,
517  * the @size argument shall represent the whole frame size.
518  *
519  * Returns: a #GstVp8ParserResult
520  *
521  * Since: 1.4
522  */
523 GstVp8ParserResult
gst_vp8_parser_parse_frame_header(GstVp8Parser * parser,GstVp8FrameHdr * frame_hdr,const guint8 * data,gsize size)524 gst_vp8_parser_parse_frame_header (GstVp8Parser * parser,
525     GstVp8FrameHdr * frame_hdr, const guint8 * data, gsize size)
526 {
527   GstByteReader br;
528   GstVp8RangeDecoder rd;
529   GstVp8RangeDecoderState rd_state;
530   GstVp8ParserResult result;
531 
532   ensure_debug_category ();
533   ensure_prob_tables ();
534 
535   g_return_val_if_fail (frame_hdr != NULL, GST_VP8_PARSER_ERROR);
536   g_return_val_if_fail (parser != NULL, GST_VP8_PARSER_ERROR);
537 
538   /* Uncompressed Data Chunk */
539   gst_byte_reader_init (&br, data, size);
540 
541   result = parse_uncompressed_data_chunk (parser, &br, frame_hdr);
542   if (result != GST_VP8_PARSER_OK)
543     return result;
544 
545   /* Frame Header */
546   if (frame_hdr->data_chunk_size + frame_hdr->first_part_size > size)
547     return GST_VP8_PARSER_BROKEN_DATA;
548 
549   data += frame_hdr->data_chunk_size;
550   size -= frame_hdr->data_chunk_size;
551   if (!gst_vp8_range_decoder_init (&rd, data, size))
552     return GST_VP8_PARSER_BROKEN_DATA;
553 
554   result = parse_frame_header (parser, &rd, frame_hdr);
555   if (result != GST_VP8_PARSER_OK)
556     return result;
557 
558   /* Calculate partition sizes */
559   if (!calc_partition_sizes (frame_hdr, data, size))
560     return GST_VP8_PARSER_BROKEN_DATA;
561 
562   /* Sync range decoder state */
563   gst_vp8_range_decoder_get_state (&rd, &rd_state);
564   frame_hdr->rd_range = rd_state.range;
565   frame_hdr->rd_value = rd_state.value;
566   frame_hdr->rd_count = rd_state.count;
567   return GST_VP8_PARSER_OK;
568 }
569