Simplify effective src_diff address computation
[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       // Wait for the frame from worker thread.
759       if (winterface->sync(worker)) {
760         // Check if worker has received any frames.
761         if (frame_worker_data->received_frame == 1) {
762           ++ctx->available_threads;
763           frame_worker_data->received_frame = 0;
764           check_resync(ctx, frame_worker_data->pbi);
765         }
766         if (vp9_get_raw_frame(frame_worker_data->pbi, &sd, &flags) == 0) {
767           VP9_COMMON *const cm = &frame_worker_data->pbi->common;
768           RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
769           release_last_output_frame(ctx);
770           ctx->last_show_frame = frame_worker_data->pbi->common.new_fb_idx;
771           if (ctx->need_resync)
772             return NULL;
773           yuvconfig2image(&ctx->img, &sd, frame_worker_data->user_priv);
774           ctx->img.fb_priv = frame_bufs[cm->new_fb_idx].raw_frame_buffer.priv;
775           img = &ctx->img;
776           return img;
777         }
778       } else {
779         // Decoding failed. Release the worker thread.
780         frame_worker_data->received_frame = 0;
781         ++ctx->available_threads;
782         ctx->need_resync = 1;
783         if (ctx->flushed != 1)
784           return NULL;
785       }
786     } while (ctx->next_output_worker_id != ctx->next_submit_worker_id);
787   }
788   return NULL;
789 }
790
791 static vpx_codec_err_t decoder_set_fb_fn(
792     vpx_codec_alg_priv_t *ctx,
793     vpx_get_frame_buffer_cb_fn_t cb_get,
794     vpx_release_frame_buffer_cb_fn_t cb_release, void *cb_priv) {
795   if (cb_get == NULL || cb_release == NULL) {
796     return VPX_CODEC_INVALID_PARAM;
797   } else if (ctx->frame_workers == NULL) {
798     // If the decoder has already been initialized, do not accept changes to
799     // the frame buffer functions.
800     ctx->get_ext_fb_cb = cb_get;
801     ctx->release_ext_fb_cb = cb_release;
802     ctx->ext_priv = cb_priv;
803     return VPX_CODEC_OK;
804   }
805
806   return VPX_CODEC_ERROR;
807 }
808
809 static vpx_codec_err_t ctrl_set_reference(vpx_codec_alg_priv_t *ctx,
810                                           va_list args) {
811   vpx_ref_frame_t *const data = va_arg(args, vpx_ref_frame_t *);
812
813   // Only support this function in serial decode.
814   if (ctx->frame_parallel_decode) {
815     set_error_detail(ctx, "Not supported in frame parallel decode");
816     return VPX_CODEC_INCAPABLE;
817   }
818
819   if (data) {
820     vpx_ref_frame_t *const frame = (vpx_ref_frame_t *)data;
821     YV12_BUFFER_CONFIG sd;
822     VP9Worker *const worker = ctx->frame_workers;
823     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
824     image2yuvconfig(&frame->img, &sd);
825     return vp9_set_reference_dec(&frame_worker_data->pbi->common,
826                                  (VP9_REFFRAME)frame->frame_type, &sd);
827   } else {
828     return VPX_CODEC_INVALID_PARAM;
829   }
830 }
831
832 static vpx_codec_err_t ctrl_copy_reference(vpx_codec_alg_priv_t *ctx,
833                                            va_list args) {
834   vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
835
836   // Only support this function in serial decode.
837   if (ctx->frame_parallel_decode) {
838     set_error_detail(ctx, "Not supported in frame parallel decode");
839     return VPX_CODEC_INCAPABLE;
840   }
841
842   if (data) {
843     vpx_ref_frame_t *frame = (vpx_ref_frame_t *) data;
844     YV12_BUFFER_CONFIG sd;
845     VP9Worker *const worker = ctx->frame_workers;
846     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
847     image2yuvconfig(&frame->img, &sd);
848     return vp9_copy_reference_dec(frame_worker_data->pbi,
849                                   (VP9_REFFRAME)frame->frame_type, &sd);
850   } else {
851     return VPX_CODEC_INVALID_PARAM;
852   }
853 }
854
855 static vpx_codec_err_t ctrl_get_reference(vpx_codec_alg_priv_t *ctx,
856                                           va_list args) {
857   vp9_ref_frame_t *data = va_arg(args, vp9_ref_frame_t *);
858
859   // Only support this function in serial decode.
860   if (ctx->frame_parallel_decode) {
861     set_error_detail(ctx, "Not supported in frame parallel decode");
862     return VPX_CODEC_INCAPABLE;
863   }
864
865   if (data) {
866     YV12_BUFFER_CONFIG* fb;
867     VP9Worker *const worker = ctx->frame_workers;
868     FrameWorkerData *const frame_worker_data = (FrameWorkerData *)worker->data1;
869     fb = get_ref_frame(&frame_worker_data->pbi->common, data->idx);
870     if (fb == NULL) return VPX_CODEC_ERROR;
871     yuvconfig2image(&data->img, fb, NULL);
872     return VPX_CODEC_OK;
873   } else {
874     return VPX_CODEC_INVALID_PARAM;
875   }
876 }
877
878 static vpx_codec_err_t ctrl_set_postproc(vpx_codec_alg_priv_t *ctx,
879                                          va_list args) {
880 #if CONFIG_VP9_POSTPROC
881   vp8_postproc_cfg_t *data = va_arg(args, vp8_postproc_cfg_t *);
882
883   if (data) {
884     ctx->postproc_cfg_set = 1;
885     ctx->postproc_cfg = *((vp8_postproc_cfg_t *)data);
886     return VPX_CODEC_OK;
887   } else {
888     return VPX_CODEC_INVALID_PARAM;
889   }
890 #else
891   (void)ctx;
892   (void)args;
893   return VPX_CODEC_INCAPABLE;
894 #endif
895 }
896
897 static vpx_codec_err_t ctrl_set_dbg_options(vpx_codec_alg_priv_t *ctx,
898                                             va_list args) {
899   (void)ctx;
900   (void)args;
901   return VPX_CODEC_INCAPABLE;
902 }
903
904 static vpx_codec_err_t ctrl_get_last_ref_updates(vpx_codec_alg_priv_t *ctx,
905                                                  va_list args) {
906   int *const update_info = va_arg(args, int *);
907
908   // Only support this function in serial decode.
909   if (ctx->frame_parallel_decode) {
910     set_error_detail(ctx, "Not supported in frame parallel decode");
911     return VPX_CODEC_INCAPABLE;
912   }
913
914   if (update_info) {
915     if (ctx->frame_workers) {
916       VP9Worker *const worker = ctx->frame_workers;
917       FrameWorkerData *const frame_worker_data =
918           (FrameWorkerData *)worker->data1;
919       *update_info = frame_worker_data->pbi->refresh_frame_flags;
920       return VPX_CODEC_OK;
921     } else {
922       return VPX_CODEC_ERROR;
923     }
924   }
925
926   return VPX_CODEC_INVALID_PARAM;
927 }
928
929 static vpx_codec_err_t ctrl_get_frame_corrupted(vpx_codec_alg_priv_t *ctx,
930                                                 va_list args) {
931   int *corrupted = va_arg(args, int *);
932
933   if (corrupted) {
934     if (ctx->frame_workers) {
935       VP9Worker *const worker = ctx->frame_workers;
936       FrameWorkerData *const frame_worker_data =
937           (FrameWorkerData *)worker->data1;
938       RefCntBuffer *const frame_bufs =
939           frame_worker_data->pbi->common.buffer_pool->frame_bufs;
940       if (frame_worker_data->pbi->common.frame_to_show == NULL)
941         return VPX_CODEC_ERROR;
942       *corrupted = frame_bufs[ctx->last_show_frame].buf.corrupted;
943       return VPX_CODEC_OK;
944     } else {
945       return VPX_CODEC_ERROR;
946     }
947   }
948
949   return VPX_CODEC_INVALID_PARAM;
950 }
951
952 static vpx_codec_err_t ctrl_get_frame_size(vpx_codec_alg_priv_t *ctx,
953                                            va_list args) {
954   int *const frame_size = va_arg(args, int *);
955
956   // Only support this function in serial decode.
957   if (ctx->frame_parallel_decode) {
958     set_error_detail(ctx, "Not supported in frame parallel decode");
959     return VPX_CODEC_INCAPABLE;
960   }
961
962   if (frame_size) {
963     if (ctx->frame_workers) {
964       VP9Worker *const worker = ctx->frame_workers;
965       FrameWorkerData *const frame_worker_data =
966           (FrameWorkerData *)worker->data1;
967       const VP9_COMMON *const cm = &frame_worker_data->pbi->common;
968       frame_size[0] = cm->width;
969       frame_size[1] = cm->height;
970       return VPX_CODEC_OK;
971     } else {
972       return VPX_CODEC_ERROR;
973     }
974   }
975
976   return VPX_CODEC_INVALID_PARAM;
977 }
978
979 static vpx_codec_err_t ctrl_get_display_size(vpx_codec_alg_priv_t *ctx,
980                                              va_list args) {
981   int *const display_size = va_arg(args, int *);
982
983   // Only support this function in serial decode.
984   if (ctx->frame_parallel_decode) {
985     set_error_detail(ctx, "Not supported in frame parallel decode");
986     return VPX_CODEC_INCAPABLE;
987   }
988
989   if (display_size) {
990     if (ctx->frame_workers) {
991       VP9Worker *const worker = ctx->frame_workers;
992       FrameWorkerData *const frame_worker_data =
993           (FrameWorkerData *)worker->data1;
994       const VP9_COMMON *const cm = &frame_worker_data->pbi->common;
995       display_size[0] = cm->display_width;
996       display_size[1] = cm->display_height;
997       return VPX_CODEC_OK;
998     } else {
999       return VPX_CODEC_ERROR;
1000     }
1001   }
1002
1003   return VPX_CODEC_INVALID_PARAM;
1004 }
1005
1006 static vpx_codec_err_t ctrl_get_bit_depth(vpx_codec_alg_priv_t *ctx,
1007                                           va_list args) {
1008   unsigned int *const bit_depth = va_arg(args, unsigned int *);
1009   VP9Worker *const worker = &ctx->frame_workers[ctx->next_output_worker_id];
1010
1011   if (bit_depth) {
1012     if (worker) {
1013       FrameWorkerData *const frame_worker_data =
1014           (FrameWorkerData *)worker->data1;
1015       const VP9_COMMON *const cm = &frame_worker_data->pbi->common;
1016       *bit_depth = cm->bit_depth;
1017       return VPX_CODEC_OK;
1018     } else {
1019       return VPX_CODEC_ERROR;
1020     }
1021   }
1022
1023   return VPX_CODEC_INVALID_PARAM;
1024 }
1025
1026 static vpx_codec_err_t ctrl_set_invert_tile_order(vpx_codec_alg_priv_t *ctx,
1027                                                   va_list args) {
1028   ctx->invert_tile_order = va_arg(args, int);
1029   return VPX_CODEC_OK;
1030 }
1031
1032 static vpx_codec_err_t ctrl_set_decryptor(vpx_codec_alg_priv_t *ctx,
1033                                           va_list args) {
1034   vpx_decrypt_init *init = va_arg(args, vpx_decrypt_init *);
1035   ctx->decrypt_cb = init ? init->decrypt_cb : NULL;
1036   ctx->decrypt_state = init ? init->decrypt_state : NULL;
1037   return VPX_CODEC_OK;
1038 }
1039
1040 static vpx_codec_err_t ctrl_set_byte_alignment(vpx_codec_alg_priv_t *ctx,
1041                                                va_list args) {
1042   const int legacy_byte_alignment = 0;
1043   const int min_byte_alignment = 32;
1044   const int max_byte_alignment = 1024;
1045   const int byte_alignment = va_arg(args, int);
1046
1047   if (byte_alignment != legacy_byte_alignment &&
1048       (byte_alignment < min_byte_alignment ||
1049        byte_alignment > max_byte_alignment ||
1050        (byte_alignment & (byte_alignment - 1)) != 0))
1051     return VPX_CODEC_INVALID_PARAM;
1052
1053   ctx->byte_alignment = byte_alignment;
1054   if (ctx->frame_workers) {
1055     VP9Worker *const worker = ctx->frame_workers;
1056     FrameWorkerData *const frame_worker_data =
1057         (FrameWorkerData *)worker->data1;
1058     frame_worker_data->pbi->common.byte_alignment = byte_alignment;
1059   }
1060   return VPX_CODEC_OK;
1061 }
1062
1063 static vpx_codec_ctrl_fn_map_t decoder_ctrl_maps[] = {
1064   {VP8_COPY_REFERENCE,            ctrl_copy_reference},
1065
1066   // Setters
1067   {VP8_SET_REFERENCE,             ctrl_set_reference},
1068   {VP8_SET_POSTPROC,              ctrl_set_postproc},
1069   {VP8_SET_DBG_COLOR_REF_FRAME,   ctrl_set_dbg_options},
1070   {VP8_SET_DBG_COLOR_MB_MODES,    ctrl_set_dbg_options},
1071   {VP8_SET_DBG_COLOR_B_MODES,     ctrl_set_dbg_options},
1072   {VP8_SET_DBG_DISPLAY_MV,        ctrl_set_dbg_options},
1073   {VP9_INVERT_TILE_DECODE_ORDER,  ctrl_set_invert_tile_order},
1074   {VPXD_SET_DECRYPTOR,            ctrl_set_decryptor},
1075   {VP9_SET_BYTE_ALIGNMENT,        ctrl_set_byte_alignment},
1076
1077   // Getters
1078   {VP8D_GET_LAST_REF_UPDATES,     ctrl_get_last_ref_updates},
1079   {VP8D_GET_FRAME_CORRUPTED,      ctrl_get_frame_corrupted},
1080   {VP9_GET_REFERENCE,             ctrl_get_reference},
1081   {VP9D_GET_DISPLAY_SIZE,         ctrl_get_display_size},
1082   {VP9D_GET_BIT_DEPTH,            ctrl_get_bit_depth},
1083   {VP9D_GET_FRAME_SIZE,           ctrl_get_frame_size},
1084
1085   { -1, NULL},
1086 };
1087
1088 #ifndef VERSION_STRING
1089 #define VERSION_STRING
1090 #endif
1091 CODEC_INTERFACE(vpx_codec_vp9_dx) = {
1092   "WebM Project VP9 Decoder" VERSION_STRING,
1093   VPX_CODEC_INTERNAL_ABI_VERSION,
1094   VPX_CODEC_CAP_DECODER | VP9_CAP_POSTPROC |
1095       VPX_CODEC_CAP_EXTERNAL_FRAME_BUFFER,  // vpx_codec_caps_t
1096   decoder_init,       // vpx_codec_init_fn_t
1097   decoder_destroy,    // vpx_codec_destroy_fn_t
1098   decoder_ctrl_maps,  // vpx_codec_ctrl_fn_map_t
1099   { // NOLINT
1100     decoder_peek_si,    // vpx_codec_peek_si_fn_t
1101     decoder_get_si,     // vpx_codec_get_si_fn_t
1102     decoder_decode,     // vpx_codec_decode_fn_t
1103     decoder_get_frame,  // vpx_codec_frame_get_fn_t
1104     decoder_set_fb_fn,  // vpx_codec_set_fb_fn_t
1105   },
1106   { // NOLINT
1107     0,
1108     NULL,  // vpx_codec_enc_cfg_map_t
1109     NULL,  // vpx_codec_encode_fn_t
1110     NULL,  // vpx_codec_get_cx_data_fn_t
1111     NULL,  // vpx_codec_enc_config_set_fn_t
1112     NULL,  // vpx_codec_get_global_headers_fn_t
1113     NULL,  // vpx_codec_get_preview_frame_fn_t
1114     NULL   // vpx_codec_enc_mr_get_mem_loc_fn_t
1115   }
1116 };