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