]> granicus.if.org Git - libvpx/blob - vp9/vp9_dx_iface.c
Merge "Move integral projection motion search to vp9_mcomp.c"
[libvpx] / vp9 / vp9_dx_iface.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "./vpx_config.h"
15 #include "./vpx_version.h"
16
17 #include "vpx/internal/vpx_codec_internal.h"
18 #include "vpx/vp8dx.h"
19 #include "vpx/vpx_decoder.h"
20
21 #include "vp9/common/vp9_alloccommon.h"
22 #include "vp9/common/vp9_frame_buffers.h"
23 #include "vp9/common/vp9_thread.h"
24
25 #include "vp9/decoder/vp9_decoder.h"
26 #include "vp9/decoder/vp9_decodeframe.h"
27 #include "vp9/decoder/vp9_read_bit_buffer.h"
28
29 #include "vp9/vp9_iface_common.h"
30
31 #define VP9_CAP_POSTPROC (CONFIG_VP9_POSTPROC ? VPX_CODEC_CAP_POSTPROC : 0)
32
33 typedef vpx_codec_stream_info_t vp9_stream_info_t;
34
35 // This limit is due to framebuffer numbers.
36 // TODO(hkuang): Remove this limit after implementing ondemand framebuffers.
37 #define FRAME_CACHE_SIZE 6   // Cache maximum 6 decoded frames.
38
39 typedef struct cache_frame {
40   int fb_idx;
41   vpx_image_t img;
42 } cache_frame;
43
44 struct vpx_codec_alg_priv {
45   vpx_codec_priv_t        base;
46   vpx_codec_dec_cfg_t     cfg;
47   vp9_stream_info_t       si;
48   int                     postproc_cfg_set;
49   vp8_postproc_cfg_t      postproc_cfg;
50   vpx_decrypt_cb          decrypt_cb;
51   void                    *decrypt_state;
52   vpx_image_t             img;
53   int                     img_avail;
54   int                     flushed;
55   int                     invert_tile_order;
56   int                     last_show_frame;  // Index of last output frame.
57   int                     byte_alignment;
58
59   // Frame parallel related.
60   int                     frame_parallel_decode;  // frame-based threading.
61   VP9Worker               *frame_workers;
62   int                     num_frame_workers;
63   int                     next_submit_worker_id;
64   int                     last_submit_worker_id;
65   int                     next_output_worker_id;
66   int                     available_threads;
67   cache_frame             frame_cache[FRAME_CACHE_SIZE];
68   int                     frame_cache_write;
69   int                     frame_cache_read;
70   int                     num_cache_frames;
71   int                     need_resync;      // wait for key/intra-only frame
72   // BufferPool that holds all reference frames. Shared by all the FrameWorkers.
73   BufferPool              *buffer_pool;
74
75   // External frame buffer info to save for VP9 common.
76   void *ext_priv;  // Private data associated with the external frame buffers.
77   vpx_get_frame_buffer_cb_fn_t get_ext_fb_cb;
78   vpx_release_frame_buffer_cb_fn_t release_ext_fb_cb;
79 };
80
81 static vpx_codec_err_t decoder_init(vpx_codec_ctx_t *ctx,
82                                     vpx_codec_priv_enc_mr_cfg_t *data) {
83   // This function only allocates space for the vpx_codec_alg_priv_t
84   // structure. More memory may be required at the time the stream
85   // information becomes known.
86   (void)data;
87
88   if (!ctx->priv) {
89     vpx_codec_alg_priv_t *const priv = vpx_calloc(1, sizeof(*priv));
90     if (priv == NULL)
91       return VPX_CODEC_MEM_ERROR;
92
93     ctx->priv = (vpx_codec_priv_t *)priv;
94     ctx->priv->init_flags = ctx->init_flags;
95     priv->si.sz = sizeof(priv->si);
96     priv->flushed = 0;
97     // Only do frame parallel decode when threads > 1.
98     priv->frame_parallel_decode =
99         (ctx->config.dec && (ctx->config.dec->threads > 1) &&
100          (ctx->init_flags & VPX_CODEC_USE_FRAME_THREADING)) ? 1 : 0;
101     if (ctx->config.dec) {
102       priv->cfg = *ctx->config.dec;
103       ctx->config.dec = &priv->cfg;
104     }
105   }
106
107   return VPX_CODEC_OK;
108 }
109
110 static vpx_codec_err_t decoder_destroy(vpx_codec_alg_priv_t *ctx) {
111   if (ctx->frame_workers != NULL) {
112     int i;
113     for (i = 0; i < ctx->num_frame_workers; ++i) {
114       VP9Worker *const worker = &ctx->frame_workers[i];
115       FrameWorkerData *const frame_worker_data =
116           (FrameWorkerData *)worker->data1;
117       vp9_get_worker_interface()->end(worker);
118       vp9_remove_common(&frame_worker_data->pbi->common);
119       vp9_decoder_remove(frame_worker_data->pbi);
120       vpx_free(frame_worker_data->scratch_buffer);
121 #if CONFIG_MULTITHREAD
122       pthread_mutex_destroy(&frame_worker_data->stats_mutex);
123       pthread_cond_destroy(&frame_worker_data->stats_cond);
124 #endif
125       vpx_free(frame_worker_data);
126     }
127 #if CONFIG_MULTITHREAD
128     pthread_mutex_destroy(&ctx->buffer_pool->pool_mutex);
129 #endif
130   }
131
132   if (ctx->buffer_pool)
133     vp9_free_internal_frame_buffers(&ctx->buffer_pool->int_frame_buffers);
134
135   vpx_free(ctx->frame_workers);
136   vpx_free(ctx->buffer_pool);
137   vpx_free(ctx);
138   return VPX_CODEC_OK;
139 }
140
141 static int parse_bitdepth_colorspace_sampling(
142     BITSTREAM_PROFILE profile, struct vp9_read_bit_buffer *rb) {
143   vpx_color_space_t color_space;
144   if (profile >= PROFILE_2)
145     rb->bit_offset += 1;  // Bit-depth 10 or 12.
146   color_space = (vpx_color_space_t)vp9_rb_read_literal(rb, 3);
147   if (color_space != VPX_CS_SRGB) {
148     rb->bit_offset += 1;  // [16,235] (including xvycc) vs [0,255] range.
149     if (profile == PROFILE_1 || profile == PROFILE_3) {
150       rb->bit_offset += 2;  // subsampling x/y.
151       rb->bit_offset += 1;  // unused.
152     }
153   } else {
154     if (profile == PROFILE_1 || profile == PROFILE_3) {
155       rb->bit_offset += 1;  // unused
156     } else {
157       // RGB is only available in version 1.
158       return 0;
159     }
160   }
161   return 1;
162 }
163
164 static vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data,
165                                                 unsigned int data_sz,
166                                                 vpx_codec_stream_info_t *si,
167                                                 int *is_intra_only,
168                                                 vpx_decrypt_cb decrypt_cb,
169                                                 void *decrypt_state) {
170   int intra_only_flag = 0;
171   uint8_t clear_buffer[9];
172
173   if (data + data_sz <= data)
174     return VPX_CODEC_INVALID_PARAM;
175
176   si->is_kf = 0;
177   si->w = si->h = 0;
178
179   if (decrypt_cb) {
180     data_sz = MIN(sizeof(clear_buffer), data_sz);
181     decrypt_cb(decrypt_state, data, clear_buffer, data_sz);
182     data = clear_buffer;
183   }
184
185   {
186     int show_frame;
187     int error_resilient;
188     struct vp9_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL };
189     const int frame_marker = vp9_rb_read_literal(&rb, 2);
190     const BITSTREAM_PROFILE profile = vp9_read_profile(&rb);
191
192     if (frame_marker != VP9_FRAME_MARKER)
193       return VPX_CODEC_UNSUP_BITSTREAM;
194
195     if (profile >= MAX_PROFILES)
196       return VPX_CODEC_UNSUP_BITSTREAM;
197
198     if ((profile >= 2 && data_sz <= 1) || data_sz < 1)
199       return VPX_CODEC_UNSUP_BITSTREAM;
200
201     if (vp9_rb_read_bit(&rb)) {  // show an existing frame
202       vp9_rb_read_literal(&rb, 3);  // Frame buffer to show.
203       return VPX_CODEC_OK;
204     }
205
206     if (data_sz <= 8)
207       return VPX_CODEC_UNSUP_BITSTREAM;
208
209     si->is_kf = !vp9_rb_read_bit(&rb);
210     show_frame = vp9_rb_read_bit(&rb);
211     error_resilient = vp9_rb_read_bit(&rb);
212
213     if (si->is_kf) {
214       if (!vp9_read_sync_code(&rb))
215         return VPX_CODEC_UNSUP_BITSTREAM;
216
217       if (!parse_bitdepth_colorspace_sampling(profile, &rb))
218         return VPX_CODEC_UNSUP_BITSTREAM;
219       vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
220     } else {
221       intra_only_flag = show_frame ? 0 : vp9_rb_read_bit(&rb);
222
223       rb.bit_offset += error_resilient ? 0 : 2;  // reset_frame_context
224
225       if (intra_only_flag) {
226         if (!vp9_read_sync_code(&rb))
227           return VPX_CODEC_UNSUP_BITSTREAM;
228         if (profile > PROFILE_0) {
229           if (!parse_bitdepth_colorspace_sampling(profile, &rb))
230             return VPX_CODEC_UNSUP_BITSTREAM;
231         }
232         rb.bit_offset += REF_FRAMES;  // refresh_frame_flags
233         vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h);
234       }
235     }
236   }
237   if (is_intra_only != NULL)
238     *is_intra_only = intra_only_flag;
239   return VPX_CODEC_OK;
240 }
241
242 static vpx_codec_err_t decoder_peek_si(const uint8_t *data,
243                                        unsigned int data_sz,
244                                        vpx_codec_stream_info_t *si) {
245   return decoder_peek_si_internal(data, data_sz, si, NULL, NULL, NULL);
246 }
247
248 static vpx_codec_err_t decoder_get_si(vpx_codec_alg_priv_t *ctx,
249                                       vpx_codec_stream_info_t *si) {
250   const size_t sz = (si->sz >= sizeof(vp9_stream_info_t))
251                        ? sizeof(vp9_stream_info_t)
252                        : sizeof(vpx_codec_stream_info_t);
253   memcpy(si, &ctx->si, sz);
254   si->sz = (unsigned int)sz;
255
256   return VPX_CODEC_OK;
257 }
258
259 static void set_error_detail(vpx_codec_alg_priv_t *ctx,
260                              const char *const error) {
261   ctx->base.err_detail = error;
262 }
263
264 static vpx_codec_err_t update_error_state(vpx_codec_alg_priv_t *ctx,
265                            const struct vpx_internal_error_info *error) {
266   if (error->error_code)
267     set_error_detail(ctx, error->has_detail ? error->detail : NULL);
268
269   return error->error_code;
270 }
271
272 static void init_buffer_callbacks(vpx_codec_alg_priv_t *ctx) {
273   int i;
274
275   for (i = 0; i < ctx->num_frame_workers; ++i) {
276     VP9Worker *const worker = &ctx->frame_workers[i];
277     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
278     VP9_COMMON *const cm = &frame_worker_data->pbi->common;
279     BufferPool *const pool = cm->buffer_pool;
280
281     cm->new_fb_idx = INVALID_IDX;
282     cm->byte_alignment = ctx->byte_alignment;
283
284     if (ctx->get_ext_fb_cb != NULL && ctx->release_ext_fb_cb != NULL) {
285       pool->get_fb_cb = ctx->get_ext_fb_cb;
286       pool->release_fb_cb = ctx->release_ext_fb_cb;
287       pool->cb_priv = ctx->ext_priv;
288     } else {
289       pool->get_fb_cb = vp9_get_frame_buffer;
290       pool->release_fb_cb = vp9_release_frame_buffer;
291
292       if (vp9_alloc_internal_frame_buffers(&pool->int_frame_buffers))
293         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
294                            "Failed to initialize internal frame buffers");
295
296       pool->cb_priv = &pool->int_frame_buffers;
297     }
298   }
299 }
300
301 static void set_default_ppflags(vp8_postproc_cfg_t *cfg) {
302   cfg->post_proc_flag = VP8_DEBLOCK | VP8_DEMACROBLOCK;
303   cfg->deblocking_level = 4;
304   cfg->noise_level = 0;
305 }
306
307 static void set_ppflags(const vpx_codec_alg_priv_t *ctx,
308                         vp9_ppflags_t *flags) {
309   flags->post_proc_flag =
310       ctx->postproc_cfg.post_proc_flag;
311
312   flags->deblocking_level = ctx->postproc_cfg.deblocking_level;
313   flags->noise_level = ctx->postproc_cfg.noise_level;
314 }
315
316 static int frame_worker_hook(void *arg1, void *arg2) {
317   FrameWorkerData *const frame_worker_data = (FrameWorkerData *)arg1;
318   const uint8_t *data = frame_worker_data->data;
319   (void)arg2;
320
321   frame_worker_data->result =
322       vp9_receive_compressed_data(frame_worker_data->pbi,
323                                   frame_worker_data->data_size,
324                                   &data);
325   frame_worker_data->data_end = data;
326
327   if (frame_worker_data->pbi->frame_parallel_decode) {
328     // In frame parallel decoding, a worker thread must successfully decode all
329     // the compressed data.
330     if (frame_worker_data->result != 0 ||
331         frame_worker_data->data + frame_worker_data->data_size - 1 > data) {
332       VP9Worker *const worker = frame_worker_data->pbi->frame_worker_owner;
333       BufferPool *const pool = frame_worker_data->pbi->common.buffer_pool;
334       // Signal all the other threads that are waiting for this frame.
335       vp9_frameworker_lock_stats(worker);
336       frame_worker_data->frame_context_ready = 1;
337       lock_buffer_pool(pool);
338       frame_worker_data->pbi->cur_buf->buf.corrupted = 1;
339       unlock_buffer_pool(pool);
340       frame_worker_data->pbi->need_resync = 1;
341       vp9_frameworker_signal_stats(worker);
342       vp9_frameworker_unlock_stats(worker);
343       return 0;
344     }
345   } else if (frame_worker_data->result != 0) {
346     // Check decode result in serial decode.
347     frame_worker_data->pbi->cur_buf->buf.corrupted = 1;
348     frame_worker_data->pbi->need_resync = 1;
349   }
350   return !frame_worker_data->result;
351 }
352
353 static vpx_codec_err_t init_decoder(vpx_codec_alg_priv_t *ctx) {
354   int i;
355   const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
356
357   ctx->last_show_frame = -1;
358   ctx->next_submit_worker_id = 0;
359   ctx->last_submit_worker_id = 0;
360   ctx->next_output_worker_id = 0;
361   ctx->frame_cache_read = 0;
362   ctx->frame_cache_write = 0;
363   ctx->num_cache_frames = 0;
364   ctx->need_resync = 1;
365   ctx->num_frame_workers =
366       (ctx->frame_parallel_decode == 1) ? ctx->cfg.threads: 1;
367   if (ctx->num_frame_workers > MAX_DECODE_THREADS)
368     ctx->num_frame_workers = MAX_DECODE_THREADS;
369   ctx->available_threads = ctx->num_frame_workers;
370   ctx->flushed = 0;
371
372   ctx->buffer_pool = (BufferPool *)vpx_calloc(1, sizeof(BufferPool));
373   if (ctx->buffer_pool == NULL)
374     return VPX_CODEC_MEM_ERROR;
375
376 #if CONFIG_MULTITHREAD
377     if (pthread_mutex_init(&ctx->buffer_pool->pool_mutex, NULL)) {
378       set_error_detail(ctx, "Failed to allocate buffer pool mutex");
379       return VPX_CODEC_MEM_ERROR;
380     }
381 #endif
382
383   ctx->frame_workers = (VP9Worker *)
384       vpx_malloc(ctx->num_frame_workers * sizeof(*ctx->frame_workers));
385   if (ctx->frame_workers == NULL) {
386     set_error_detail(ctx, "Failed to allocate frame_workers");
387     return VPX_CODEC_MEM_ERROR;
388   }
389
390   for (i = 0; i < ctx->num_frame_workers; ++i) {
391     VP9Worker *const worker = &ctx->frame_workers[i];
392     FrameWorkerData *frame_worker_data = NULL;
393     winterface->init(worker);
394     worker->data1 = vpx_memalign(32, sizeof(FrameWorkerData));
395     if (worker->data1 == NULL) {
396       set_error_detail(ctx, "Failed to allocate frame_worker_data");
397       return VPX_CODEC_MEM_ERROR;
398     }
399     frame_worker_data = (FrameWorkerData *)worker->data1;
400     frame_worker_data->pbi = vp9_decoder_create(ctx->buffer_pool);
401     if (frame_worker_data->pbi == NULL) {
402       set_error_detail(ctx, "Failed to allocate frame_worker_data");
403       return VPX_CODEC_MEM_ERROR;
404     }
405     frame_worker_data->pbi->frame_worker_owner = worker;
406     frame_worker_data->worker_id = i;
407     frame_worker_data->scratch_buffer = NULL;
408     frame_worker_data->scratch_buffer_size = 0;
409     frame_worker_data->frame_context_ready = 0;
410     frame_worker_data->received_frame = 0;
411 #if CONFIG_MULTITHREAD
412     if (pthread_mutex_init(&frame_worker_data->stats_mutex, NULL)) {
413       set_error_detail(ctx, "Failed to allocate frame_worker_data mutex");
414       return VPX_CODEC_MEM_ERROR;
415     }
416
417     if (pthread_cond_init(&frame_worker_data->stats_cond, NULL)) {
418       set_error_detail(ctx, "Failed to allocate frame_worker_data cond");
419       return VPX_CODEC_MEM_ERROR;
420     }
421 #endif
422     // If decoding in serial mode, FrameWorker thread could create tile worker
423     // thread or loopfilter thread.
424     frame_worker_data->pbi->max_threads =
425         (ctx->frame_parallel_decode == 0) ? ctx->cfg.threads : 0;
426
427     frame_worker_data->pbi->inv_tile_order = ctx->invert_tile_order;
428     frame_worker_data->pbi->frame_parallel_decode = ctx->frame_parallel_decode;
429     frame_worker_data->pbi->common.frame_parallel_decode =
430         ctx->frame_parallel_decode;
431     worker->hook = (VP9WorkerHook)frame_worker_hook;
432     if (!winterface->reset(worker)) {
433       set_error_detail(ctx, "Frame Worker thread creation failed");
434       return VPX_CODEC_MEM_ERROR;
435     }
436   }
437
438   // If postprocessing was enabled by the application and a
439   // configuration has not been provided, default it.
440   if (!ctx->postproc_cfg_set &&
441       (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC))
442     set_default_ppflags(&ctx->postproc_cfg);
443
444   init_buffer_callbacks(ctx);
445
446   return VPX_CODEC_OK;
447 }
448
449 static INLINE void check_resync(vpx_codec_alg_priv_t *const ctx,
450                                 const VP9Decoder *const pbi) {
451   // Clear resync flag if worker got a key frame or intra only frame.
452   if (ctx->need_resync == 1 && pbi->need_resync == 0 &&
453       (pbi->common.intra_only || pbi->common.frame_type == KEY_FRAME))
454     ctx->need_resync = 0;
455 }
456
457 static vpx_codec_err_t decode_one(vpx_codec_alg_priv_t *ctx,
458                                   const uint8_t **data, unsigned int data_sz,
459                                   void *user_priv, int64_t deadline) {
460   vp9_ppflags_t flags = {0, 0, 0};
461   const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
462   (void)deadline;
463
464   // Determine the stream parameters. Note that we rely on peek_si to
465   // validate that we have a buffer that does not wrap around the top
466   // of the heap.
467   if (!ctx->si.h) {
468     int is_intra_only = 0;
469     const vpx_codec_err_t res =
470         decoder_peek_si_internal(*data, data_sz, &ctx->si, &is_intra_only,
471                                  ctx->decrypt_cb, ctx->decrypt_state);
472     if (res != VPX_CODEC_OK)
473       return res;
474
475     if (!ctx->si.is_kf && !is_intra_only)
476       return VPX_CODEC_ERROR;
477   }
478
479   if (!ctx->frame_parallel_decode) {
480     VP9Worker *const worker = ctx->frame_workers;
481     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
482     frame_worker_data->data = *data;
483     frame_worker_data->data_size = data_sz;
484     frame_worker_data->user_priv = user_priv;
485     frame_worker_data->received_frame = 1;
486
487     // Set these even if already initialized.  The caller may have changed the
488     // decrypt config between frames.
489     frame_worker_data->pbi->decrypt_cb = ctx->decrypt_cb;
490     frame_worker_data->pbi->decrypt_state = ctx->decrypt_state;
491
492     worker->had_error = 0;
493     winterface->execute(worker);
494
495     // Update data pointer after decode.
496     *data = frame_worker_data->data_end;
497
498     if (worker->had_error)
499       return update_error_state(ctx, &frame_worker_data->pbi->common.error);
500
501     check_resync(ctx, frame_worker_data->pbi);
502   } else {
503     VP9Worker *const worker = &ctx->frame_workers[ctx->next_submit_worker_id];
504     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
505     // Copy context from last worker thread to next worker thread.
506     if (ctx->next_submit_worker_id != ctx->last_submit_worker_id)
507       vp9_frameworker_copy_context(
508           &ctx->frame_workers[ctx->next_submit_worker_id],
509           &ctx->frame_workers[ctx->last_submit_worker_id]);
510
511     frame_worker_data->pbi->ready_for_new_data = 0;
512     // Copy the compressed data into worker's internal buffer.
513     // TODO(hkuang): Will all the workers allocate the same size
514     // as the size of the first intra frame be better? This will
515     // avoid too many deallocate and allocate.
516     if (frame_worker_data->scratch_buffer_size < data_sz) {
517       frame_worker_data->scratch_buffer =
518           (uint8_t *)vpx_realloc(frame_worker_data->scratch_buffer, data_sz);
519       if (frame_worker_data->scratch_buffer == NULL) {
520         set_error_detail(ctx, "Failed to reallocate scratch buffer");
521         return VPX_CODEC_MEM_ERROR;
522       }
523       frame_worker_data->scratch_buffer_size = data_sz;
524     }
525     frame_worker_data->data_size = data_sz;
526     vpx_memcpy(frame_worker_data->scratch_buffer, *data, data_sz);
527
528     frame_worker_data->frame_decoded = 0;
529     frame_worker_data->frame_context_ready = 0;
530     frame_worker_data->received_frame = 1;
531     frame_worker_data->data = frame_worker_data->scratch_buffer;
532     frame_worker_data->user_priv = user_priv;
533
534     if (ctx->next_submit_worker_id != ctx->last_submit_worker_id)
535       ctx->last_submit_worker_id =
536           (ctx->last_submit_worker_id + 1) % ctx->num_frame_workers;
537
538     ctx->next_submit_worker_id =
539         (ctx->next_submit_worker_id + 1) % ctx->num_frame_workers;
540     --ctx->available_threads;
541     worker->had_error = 0;
542     winterface->launch(worker);
543   }
544
545   if (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC)
546     set_ppflags(ctx, &flags);
547
548   return VPX_CODEC_OK;
549 }
550
551 static void wait_worker_and_cache_frame(vpx_codec_alg_priv_t *ctx) {
552   YV12_BUFFER_CONFIG sd;
553   vp9_ppflags_t flags = {0, 0, 0};
554   const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
555   VP9Worker *const worker = &ctx->frame_workers[ctx->next_output_worker_id];
556   FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
557   ctx->next_output_worker_id =
558       (ctx->next_output_worker_id + 1) % ctx->num_frame_workers;
559   // TODO(hkuang): Add worker error handling here.
560   winterface->sync(worker);
561   frame_worker_data->received_frame = 0;
562   ++ctx->available_threads;
563
564   check_resync(ctx, frame_worker_data->pbi);
565
566   if (vp9_get_raw_frame(frame_worker_data->pbi, &sd, &flags) == 0) {
567     VP9_COMMON *const cm = &frame_worker_data->pbi->common;
568     RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
569     ctx->frame_cache[ctx->frame_cache_write].fb_idx = cm->new_fb_idx;
570     yuvconfig2image(&ctx->frame_cache[ctx->frame_cache_write].img, &sd,
571                     frame_worker_data->user_priv);
572     ctx->frame_cache[ctx->frame_cache_write].img.fb_priv =
573         frame_bufs[cm->new_fb_idx].raw_frame_buffer.priv;
574     ctx->frame_cache_write =
575         (ctx->frame_cache_write + 1) % FRAME_CACHE_SIZE;
576     ++ctx->num_cache_frames;
577   }
578 }
579
580 static vpx_codec_err_t decoder_decode(vpx_codec_alg_priv_t *ctx,
581                                       const uint8_t *data, unsigned int data_sz,
582                                       void *user_priv, long deadline) {
583   const uint8_t *data_start = data;
584   const uint8_t * const data_end = data + data_sz;
585   vpx_codec_err_t res;
586   uint32_t frame_sizes[8];
587   int frame_count;
588
589   if (data == NULL && data_sz == 0) {
590     ctx->flushed = 1;
591     return VPX_CODEC_OK;
592   }
593
594   // Reset flushed when receiving a valid frame.
595   ctx->flushed = 0;
596
597   // Initialize the decoder workers on the first frame.
598   if (ctx->frame_workers == NULL) {
599     const vpx_codec_err_t res = init_decoder(ctx);
600     if (res != VPX_CODEC_OK)
601       return res;
602   }
603
604   res = vp9_parse_superframe_index(data, data_sz, frame_sizes, &frame_count,
605                                    ctx->decrypt_cb, ctx->decrypt_state);
606   if (res != VPX_CODEC_OK)
607     return res;
608
609   if (ctx->frame_parallel_decode) {
610     // Decode in frame parallel mode. When decoding in this mode, the frame
611     // passed to the decoder must be either a normal frame or a superframe with
612     // superframe index so the decoder could get each frame's start position
613     // in the superframe.
614     if (frame_count > 0) {
615       int i;
616
617       for (i = 0; i < frame_count; ++i) {
618         const uint8_t *data_start_copy = data_start;
619         const uint32_t frame_size = frame_sizes[i];
620         if (data_start < data
621             || frame_size > (uint32_t) (data_end - data_start)) {
622           set_error_detail(ctx, "Invalid frame size in index");
623           return VPX_CODEC_CORRUPT_FRAME;
624         }
625
626         if (ctx->available_threads == 0) {
627           // No more threads for decoding. Wait until the next output worker
628           // finishes decoding. Then copy the decoded frame into cache.
629           if (ctx->num_cache_frames < FRAME_CACHE_SIZE) {
630             wait_worker_and_cache_frame(ctx);
631           } else {
632             // TODO(hkuang): Add unit test to test this path.
633             set_error_detail(ctx, "Frame output cache is full.");
634             return VPX_CODEC_ERROR;
635           }
636         }
637
638         res = decode_one(ctx, &data_start_copy, frame_size, user_priv,
639                          deadline);
640         if (res != VPX_CODEC_OK)
641           return res;
642         data_start += frame_size;
643       }
644     } else {
645       if (ctx->available_threads == 0) {
646         // No more threads for decoding. Wait until the next output worker
647         // finishes decoding. Then copy the decoded frame into cache.
648         if (ctx->num_cache_frames < FRAME_CACHE_SIZE) {
649           wait_worker_and_cache_frame(ctx);
650         } else {
651           // TODO(hkuang): Add unit test to test this path.
652           set_error_detail(ctx, "Frame output cache is full.");
653           return VPX_CODEC_ERROR;
654         }
655       }
656
657       res = decode_one(ctx, &data, data_sz, user_priv, deadline);
658       if (res != VPX_CODEC_OK)
659         return res;
660     }
661   } else {
662     // Decode in serial mode.
663     if (frame_count > 0) {
664       int i;
665
666       for (i = 0; i < frame_count; ++i) {
667         const uint8_t *data_start_copy = data_start;
668         const uint32_t frame_size = frame_sizes[i];
669         vpx_codec_err_t res;
670         if (data_start < data
671             || frame_size > (uint32_t) (data_end - data_start)) {
672           set_error_detail(ctx, "Invalid frame size in index");
673           return VPX_CODEC_CORRUPT_FRAME;
674         }
675
676         res = decode_one(ctx, &data_start_copy, frame_size, user_priv,
677                          deadline);
678         if (res != VPX_CODEC_OK)
679           return res;
680
681         data_start += frame_size;
682       }
683     } else {
684       while (data_start < data_end) {
685         const uint32_t frame_size = (uint32_t) (data_end - data_start);
686         const vpx_codec_err_t res = decode_one(ctx, &data_start, frame_size,
687                                                user_priv, deadline);
688         if (res != VPX_CODEC_OK)
689           return res;
690
691         // Account for suboptimal termination by the encoder.
692         while (data_start < data_end) {
693           const uint8_t marker = read_marker(ctx->decrypt_cb,
694                                              ctx->decrypt_state, data_start);
695           if (marker)
696             break;
697           ++data_start;
698         }
699       }
700     }
701   }
702
703   return res;
704 }
705
706 static void release_last_output_frame(vpx_codec_alg_priv_t *ctx) {
707   RefCntBuffer *const frame_bufs = ctx->buffer_pool->frame_bufs;
708   // Decrease reference count of last output frame in frame parallel mode.
709   if (ctx->frame_parallel_decode && ctx->last_show_frame >= 0) {
710     BufferPool *const pool = ctx->buffer_pool;
711     lock_buffer_pool(pool);
712     decrease_ref_count(ctx->last_show_frame, frame_bufs, pool);
713     unlock_buffer_pool(pool);
714   }
715 }
716
717 static vpx_image_t *decoder_get_frame(vpx_codec_alg_priv_t *ctx,
718                                       vpx_codec_iter_t *iter) {
719   vpx_image_t *img = NULL;
720
721   // Only return frame when all the cpu are busy or
722   // application fluhsed the decoder in frame parallel decode.
723   if (ctx->frame_parallel_decode && ctx->available_threads > 0 &&
724       !ctx->flushed) {
725     return NULL;
726   }
727
728   // Output the frames in the cache first.
729   if (ctx->num_cache_frames > 0) {
730     release_last_output_frame(ctx);
731     ctx->last_show_frame  = ctx->frame_cache[ctx->frame_cache_read].fb_idx;
732     if (ctx->need_resync)
733       return NULL;
734     img = &ctx->frame_cache[ctx->frame_cache_read].img;
735     ctx->frame_cache_read = (ctx->frame_cache_read + 1) % FRAME_CACHE_SIZE;
736     --ctx->num_cache_frames;
737     return img;
738   }
739
740   // iter acts as a flip flop, so an image is only returned on the first
741   // call to get_frame.
742   if (*iter == NULL && ctx->frame_workers != NULL) {
743     do {
744       YV12_BUFFER_CONFIG sd;
745       vp9_ppflags_t flags = {0, 0, 0};
746       const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
747       VP9Worker *const worker =
748           &ctx->frame_workers[ctx->next_output_worker_id];
749       FrameWorkerData *const frame_worker_data =
750           (FrameWorkerData *)worker->data1;
751       ctx->next_output_worker_id =
752           (ctx->next_output_worker_id + 1) % ctx->num_frame_workers;
753       // Wait for the frame from worker thread.
754       if (winterface->sync(worker)) {
755         // Check if worker has received any frames.
756         if (frame_worker_data->received_frame == 1) {
757           ++ctx->available_threads;
758           frame_worker_data->received_frame = 0;
759           check_resync(ctx, frame_worker_data->pbi);
760         }
761         if (vp9_get_raw_frame(frame_worker_data->pbi, &sd, &flags) == 0) {
762           VP9_COMMON *const cm = &frame_worker_data->pbi->common;
763           RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
764           release_last_output_frame(ctx);
765           ctx->last_show_frame = frame_worker_data->pbi->common.new_fb_idx;
766           if (ctx->need_resync)
767             return NULL;
768           yuvconfig2image(&ctx->img, &sd, frame_worker_data->user_priv);
769           ctx->img.fb_priv = frame_bufs[cm->new_fb_idx].raw_frame_buffer.priv;
770           img = &ctx->img;
771           return img;
772         }
773       } else {
774         // Decoding failed. Release the worker thread.
775         frame_worker_data->received_frame = 0;
776         ++ctx->available_threads;
777         ctx->need_resync = 1;
778         if (ctx->flushed != 1)
779           return NULL;
780       }
781     } while (ctx->next_output_worker_id != ctx->next_submit_worker_id);
782   }
783   return NULL;
784 }
785
786 static vpx_codec_err_t decoder_set_fb_fn(
787     vpx_codec_alg_priv_t *ctx,
788     vpx_get_frame_buffer_cb_fn_t cb_get,
789     vpx_release_frame_buffer_cb_fn_t cb_release, void *cb_priv) {
790   if (cb_get == NULL || cb_release == NULL) {
791     return VPX_CODEC_INVALID_PARAM;
792   } else if (ctx->frame_workers == NULL) {
793     // If the decoder has already been initialized, do not accept changes to
794     // the frame buffer functions.
795     ctx->get_ext_fb_cb = cb_get;
796     ctx->release_ext_fb_cb = cb_release;
797     ctx->ext_priv = cb_priv;
798     return VPX_CODEC_OK;
799   }
800
801   return VPX_CODEC_ERROR;
802 }
803
804 static vpx_codec_err_t ctrl_set_reference(vpx_codec_alg_priv_t *ctx,
805                                           va_list args) {
806   vpx_ref_frame_t *const data = va_arg(args, vpx_ref_frame_t *);
807
808   // Only support this function in serial decode.
809   if (ctx->frame_parallel_decode) {
810     set_error_detail(ctx, "Not supported in frame parallel decode");
811     return VPX_CODEC_INCAPABLE;
812   }
813
814   if (data) {
815     vpx_ref_frame_t *const frame = (vpx_ref_frame_t *)data;
816     YV12_BUFFER_CONFIG sd;
817     VP9Worker *const worker = ctx->frame_workers;
818     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
819     image2yuvconfig(&frame->img, &sd);
820     return vp9_set_reference_dec(&frame_worker_data->pbi->common,
821                                  (VP9_REFFRAME)frame->frame_type, &sd);
822   } else {
823     return VPX_CODEC_INVALID_PARAM;
824   }
825 }
826
827 static vpx_codec_err_t ctrl_copy_reference(vpx_codec_alg_priv_t *ctx,
828                                            va_list args) {
829   vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
830
831   // Only support this function in serial decode.
832   if (ctx->frame_parallel_decode) {
833     set_error_detail(ctx, "Not supported in frame parallel decode");
834     return VPX_CODEC_INCAPABLE;
835   }
836
837   if (data) {
838     vpx_ref_frame_t *frame = (vpx_ref_frame_t *) data;
839     YV12_BUFFER_CONFIG sd;
840     VP9Worker *const worker = ctx->frame_workers;
841     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
842     image2yuvconfig(&frame->img, &sd);
843     return vp9_copy_reference_dec(frame_worker_data->pbi,
844                                   (VP9_REFFRAME)frame->frame_type, &sd);
845   } else {
846     return VPX_CODEC_INVALID_PARAM;
847   }
848 }
849
850 static vpx_codec_err_t ctrl_get_reference(vpx_codec_alg_priv_t *ctx,
851                                           va_list args) {
852   vp9_ref_frame_t *data = va_arg(args, vp9_ref_frame_t *);
853
854   // Only support this function in serial decode.
855   if (ctx->frame_parallel_decode) {
856     set_error_detail(ctx, "Not supported in frame parallel decode");
857     return VPX_CODEC_INCAPABLE;
858   }
859
860   if (data) {
861     YV12_BUFFER_CONFIG* fb;
862     VP9Worker *const worker = ctx->frame_workers;
863     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
864     fb = get_ref_frame(&frame_worker_data->pbi->common, data->idx);
865     if (fb == NULL) return VPX_CODEC_ERROR;
866     yuvconfig2image(&data->img, fb, NULL);
867     return VPX_CODEC_OK;
868   } else {
869     return VPX_CODEC_INVALID_PARAM;
870   }
871 }
872
873 static vpx_codec_err_t ctrl_set_postproc(vpx_codec_alg_priv_t *ctx,
874                                          va_list args) {
875 #if CONFIG_VP9_POSTPROC
876   vp8_postproc_cfg_t *data = va_arg(args, vp8_postproc_cfg_t *);
877
878   if (data) {
879     ctx->postproc_cfg_set = 1;
880     ctx->postproc_cfg = *((vp8_postproc_cfg_t *)data);
881     return VPX_CODEC_OK;
882   } else {
883     return VPX_CODEC_INVALID_PARAM;
884   }
885 #else
886   (void)ctx;
887   (void)args;
888   return VPX_CODEC_INCAPABLE;
889 #endif
890 }
891
892 static vpx_codec_err_t ctrl_set_dbg_options(vpx_codec_alg_priv_t *ctx,
893                                             va_list args) {
894   (void)ctx;
895   (void)args;
896   return VPX_CODEC_INCAPABLE;
897 }
898
899 static vpx_codec_err_t ctrl_get_last_ref_updates(vpx_codec_alg_priv_t *ctx,
900                                                  va_list args) {
901   int *const update_info = va_arg(args, int *);
902
903   // Only support this function in serial decode.
904   if (ctx->frame_parallel_decode) {
905     set_error_detail(ctx, "Not supported in frame parallel decode");
906     return VPX_CODEC_INCAPABLE;
907   }
908
909   if (update_info) {
910     if (ctx->frame_workers) {
911       VP9Worker *const worker = ctx->frame_workers;
912       FrameWorkerData *const frame_worker_data =
913           (FrameWorkerData *)worker->data1;
914       *update_info = frame_worker_data->pbi->refresh_frame_flags;
915       return VPX_CODEC_OK;
916     } else {
917       return VPX_CODEC_ERROR;
918     }
919   }
920
921   return VPX_CODEC_INVALID_PARAM;
922 }
923
924 static vpx_codec_err_t ctrl_get_frame_corrupted(vpx_codec_alg_priv_t *ctx,
925                                                 va_list args) {
926   int *corrupted = va_arg(args, int *);
927
928   if (corrupted) {
929     if (ctx->frame_workers) {
930       VP9Worker *const worker = ctx->frame_workers;
931       FrameWorkerData *const frame_worker_data =
932           (FrameWorkerData *)worker->data1;
933       RefCntBuffer *const frame_bufs =
934           frame_worker_data->pbi->common.buffer_pool->frame_bufs;
935       if (frame_worker_data->pbi->common.frame_to_show == NULL)
936         return VPX_CODEC_ERROR;
937       *corrupted = frame_bufs[ctx->last_show_frame].buf.corrupted;
938       return VPX_CODEC_OK;
939     } else {
940       return VPX_CODEC_ERROR;
941     }
942   }
943
944   return VPX_CODEC_INVALID_PARAM;
945 }
946
947 static vpx_codec_err_t ctrl_get_frame_size(vpx_codec_alg_priv_t *ctx,
948                                            va_list args) {
949   int *const frame_size = va_arg(args, int *);
950
951   // Only support this function in serial decode.
952   if (ctx->frame_parallel_decode) {
953     set_error_detail(ctx, "Not supported in frame parallel decode");
954     return VPX_CODEC_INCAPABLE;
955   }
956
957   if (frame_size) {
958     if (ctx->frame_workers) {
959       VP9Worker *const worker = ctx->frame_workers;
960       FrameWorkerData *const frame_worker_data =
961           (FrameWorkerData *)worker->data1;
962       const VP9_COMMON *const cm = &frame_worker_data->pbi->common;
963       frame_size[0] = cm->width;
964       frame_size[1] = cm->height;
965       return VPX_CODEC_OK;
966     } else {
967       return VPX_CODEC_ERROR;
968     }
969   }
970
971   return VPX_CODEC_INVALID_PARAM;
972 }
973
974 static vpx_codec_err_t ctrl_get_display_size(vpx_codec_alg_priv_t *ctx,
975                                              va_list args) {
976   int *const display_size = va_arg(args, int *);
977
978   // Only support this function in serial decode.
979   if (ctx->frame_parallel_decode) {
980     set_error_detail(ctx, "Not supported in frame parallel decode");
981     return VPX_CODEC_INCAPABLE;
982   }
983
984   if (display_size) {
985     if (ctx->frame_workers) {
986       VP9Worker *const worker = ctx->frame_workers;
987       FrameWorkerData *const frame_worker_data =
988           (FrameWorkerData *)worker->data1;
989       const VP9_COMMON *const cm = &frame_worker_data->pbi->common;
990       display_size[0] = cm->display_width;
991       display_size[1] = cm->display_height;
992       return VPX_CODEC_OK;
993     } else {
994       return VPX_CODEC_ERROR;
995     }
996   }
997
998   return VPX_CODEC_INVALID_PARAM;
999 }
1000
1001 static vpx_codec_err_t ctrl_get_bit_depth(vpx_codec_alg_priv_t *ctx,
1002                                           va_list args) {
1003   unsigned int *const bit_depth = va_arg(args, unsigned int *);
1004   VP9Worker *const worker = &ctx->frame_workers[ctx->next_output_worker_id];
1005
1006   if (bit_depth) {
1007     if (worker) {
1008       FrameWorkerData *const frame_worker_data =
1009           (FrameWorkerData *)worker->data1;
1010       const VP9_COMMON *const cm = &frame_worker_data->pbi->common;
1011       *bit_depth = cm->bit_depth;
1012       return VPX_CODEC_OK;
1013     } else {
1014       return VPX_CODEC_ERROR;
1015     }
1016   }
1017
1018   return VPX_CODEC_INVALID_PARAM;
1019 }
1020
1021 static vpx_codec_err_t ctrl_set_invert_tile_order(vpx_codec_alg_priv_t *ctx,
1022                                                   va_list args) {
1023   ctx->invert_tile_order = va_arg(args, int);
1024   return VPX_CODEC_OK;
1025 }
1026
1027 static vpx_codec_err_t ctrl_set_decryptor(vpx_codec_alg_priv_t *ctx,
1028                                           va_list args) {
1029   vpx_decrypt_init *init = va_arg(args, vpx_decrypt_init *);
1030   ctx->decrypt_cb = init ? init->decrypt_cb : NULL;
1031   ctx->decrypt_state = init ? init->decrypt_state : NULL;
1032   return VPX_CODEC_OK;
1033 }
1034
1035 static vpx_codec_err_t ctrl_set_byte_alignment(vpx_codec_alg_priv_t *ctx,
1036                                                va_list args) {
1037   const int legacy_byte_alignment = 0;
1038   const int min_byte_alignment = 32;
1039   const int max_byte_alignment = 1024;
1040   const int byte_alignment = va_arg(args, int);
1041
1042   if (byte_alignment != legacy_byte_alignment &&
1043       (byte_alignment < min_byte_alignment ||
1044        byte_alignment > max_byte_alignment ||
1045        (byte_alignment & (byte_alignment - 1)) != 0))
1046     return VPX_CODEC_INVALID_PARAM;
1047
1048   ctx->byte_alignment = byte_alignment;
1049   if (ctx->frame_workers) {
1050     VP9Worker *const worker = ctx->frame_workers;
1051     FrameWorkerData *const frame_worker_data =
1052         (FrameWorkerData *)worker->data1;
1053     frame_worker_data->pbi->common.byte_alignment = byte_alignment;
1054   }
1055   return VPX_CODEC_OK;
1056 }
1057
1058 static vpx_codec_ctrl_fn_map_t decoder_ctrl_maps[] = {
1059   {VP8_COPY_REFERENCE,            ctrl_copy_reference},
1060
1061   // Setters
1062   {VP8_SET_REFERENCE,             ctrl_set_reference},
1063   {VP8_SET_POSTPROC,              ctrl_set_postproc},
1064   {VP8_SET_DBG_COLOR_REF_FRAME,   ctrl_set_dbg_options},
1065   {VP8_SET_DBG_COLOR_MB_MODES,    ctrl_set_dbg_options},
1066   {VP8_SET_DBG_COLOR_B_MODES,     ctrl_set_dbg_options},
1067   {VP8_SET_DBG_DISPLAY_MV,        ctrl_set_dbg_options},
1068   {VP9_INVERT_TILE_DECODE_ORDER,  ctrl_set_invert_tile_order},
1069   {VPXD_SET_DECRYPTOR,            ctrl_set_decryptor},
1070   {VP9_SET_BYTE_ALIGNMENT,        ctrl_set_byte_alignment},
1071
1072   // Getters
1073   {VP8D_GET_LAST_REF_UPDATES,     ctrl_get_last_ref_updates},
1074   {VP8D_GET_FRAME_CORRUPTED,      ctrl_get_frame_corrupted},
1075   {VP9_GET_REFERENCE,             ctrl_get_reference},
1076   {VP9D_GET_DISPLAY_SIZE,         ctrl_get_display_size},
1077   {VP9D_GET_BIT_DEPTH,            ctrl_get_bit_depth},
1078   {VP9D_GET_FRAME_SIZE,           ctrl_get_frame_size},
1079
1080   { -1, NULL},
1081 };
1082
1083 #ifndef VERSION_STRING
1084 #define VERSION_STRING
1085 #endif
1086 CODEC_INTERFACE(vpx_codec_vp9_dx) = {
1087   "WebM Project VP9 Decoder" VERSION_STRING,
1088   VPX_CODEC_INTERNAL_ABI_VERSION,
1089   VPX_CODEC_CAP_DECODER | VP9_CAP_POSTPROC |
1090       VPX_CODEC_CAP_EXTERNAL_FRAME_BUFFER,  // vpx_codec_caps_t
1091   decoder_init,       // vpx_codec_init_fn_t
1092   decoder_destroy,    // vpx_codec_destroy_fn_t
1093   decoder_ctrl_maps,  // vpx_codec_ctrl_fn_map_t
1094   { // NOLINT
1095     decoder_peek_si,    // vpx_codec_peek_si_fn_t
1096     decoder_get_si,     // vpx_codec_get_si_fn_t
1097     decoder_decode,     // vpx_codec_decode_fn_t
1098     decoder_get_frame,  // vpx_codec_frame_get_fn_t
1099     decoder_set_fb_fn,  // vpx_codec_set_fb_fn_t
1100   },
1101   { // NOLINT
1102     0,
1103     NULL,  // vpx_codec_enc_cfg_map_t
1104     NULL,  // vpx_codec_encode_fn_t
1105     NULL,  // vpx_codec_get_cx_data_fn_t
1106     NULL,  // vpx_codec_enc_config_set_fn_t
1107     NULL,  // vpx_codec_get_global_headers_fn_t
1108     NULL,  // vpx_codec_get_preview_frame_fn_t
1109     NULL   // vpx_codec_enc_mr_get_mem_loc_fn_t
1110   }
1111 };