xref: /OK3568_Linux_fs/external/mpp/mpp/codec/dec/av1/av1d_parser.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 /*
2  * Copyright 2021 Rockchip Electronics Co. LTD
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define MODULE_TAG "av1d_parser"
18 
19 #include <stdlib.h>
20 #include <string.h>
21 
22 #include "mpp_env.h"
23 #include "mpp_mem.h"
24 #include "mpp_debug.h"
25 #include "mpp_common.h"
26 #include "mpp_compat_impl.h"
27 #include "rk_hdr_meta_com.h"
28 
29 #include "mpp_bitread.h"
30 #include "mpp_packet_impl.h"
31 
32 #include "av1d_parser.h"
33 #include "mpp_dec_cb_param.h"
34 #include "mpp_frame_impl.h"
35 
36 RK_U32 av1d_debug = 0;
37 
38 static const RK_S16 div_lut[AV1_DIV_LUT_NUM] = {
39     16384, 16320, 16257, 16194, 16132, 16070, 16009, 15948, 15888, 15828, 15768,
40     15709, 15650, 15592, 15534, 15477, 15420, 15364, 15308, 15252, 15197, 15142,
41     15087, 15033, 14980, 14926, 14873, 14821, 14769, 14717, 14665, 14614, 14564,
42     14513, 14463, 14413, 14364, 14315, 14266, 14218, 14170, 14122, 14075, 14028,
43     13981, 13935, 13888, 13843, 13797, 13752, 13707, 13662, 13618, 13574, 13530,
44     13487, 13443, 13400, 13358, 13315, 13273, 13231, 13190, 13148, 13107, 13066,
45     13026, 12985, 12945, 12906, 12866, 12827, 12788, 12749, 12710, 12672, 12633,
46     12596, 12558, 12520, 12483, 12446, 12409, 12373, 12336, 12300, 12264, 12228,
47     12193, 12157, 12122, 12087, 12053, 12018, 11984, 11950, 11916, 11882, 11848,
48     11815, 11782, 11749, 11716, 11683, 11651, 11619, 11586, 11555, 11523, 11491,
49     11460, 11429, 11398, 11367, 11336, 11305, 11275, 11245, 11215, 11185, 11155,
50     11125, 11096, 11067, 11038, 11009, 10980, 10951, 10923, 10894, 10866, 10838,
51     10810, 10782, 10755, 10727, 10700, 10673, 10645, 10618, 10592, 10565, 10538,
52     10512, 10486, 10460, 10434, 10408, 10382, 10356, 10331, 10305, 10280, 10255,
53     10230, 10205, 10180, 10156, 10131, 10107, 10082, 10058, 10034, 10010, 9986,
54     9963,  9939,  9916,  9892,  9869,  9846,  9823,  9800,  9777,  9754,  9732,
55     9709,  9687,  9664,  9642,  9620,  9598,  9576,  9554,  9533,  9511,  9489,
56     9468,  9447,  9425,  9404,  9383,  9362,  9341,  9321,  9300,  9279,  9259,
57     9239,  9218,  9198,  9178,  9158,  9138,  9118,  9098,  9079,  9059,  9039,
58     9020,  9001,  8981,  8962,  8943,  8924,  8905,  8886,  8867,  8849,  8830,
59     8812,  8793,  8775,  8756,  8738,  8720,  8702,  8684,  8666,  8648,  8630,
60     8613,  8595,  8577,  8560,  8542,  8525,  8508,  8490,  8473,  8456,  8439,
61     8422,  8405,  8389,  8372,  8355,  8339,  8322,  8306,  8289,  8273,  8257,
62     8240,  8224,  8208,  8192
63 };
64 
65 /**
66  * Clip a signed integer into the -(2^p),(2^p-1) range.
67  * @param  a value to clip
68  * @param  p bit position to clip at
69  * @return clipped value
70  */
mpp_clip_uintp2(RK_S32 a,RK_S32 p)71 static   RK_U32 mpp_clip_uintp2(RK_S32 a, RK_S32 p)
72 {
73     if (a & ~((1 << p) - 1)) return -a >> 31 & ((1 << p) - 1);
74     else                   return  a;
75 }
76 
77 static const Av1UnitType unit_types[] = {
78     AV1_OBU_TEMPORAL_DELIMITER,
79     AV1_OBU_SEQUENCE_HEADER,
80     AV1_OBU_FRAME_HEADER,
81     AV1_OBU_TILE_GROUP,
82     AV1_OBU_METADATA,
83     AV1_OBU_FRAME,
84 };
85 
get_pixel_format(Av1CodecContext * ctx)86 static MPP_RET get_pixel_format(Av1CodecContext *ctx)
87 {
88     AV1Context *s = ctx->priv_data;
89     const AV1RawSequenceHeader *seq = s->sequence_header;
90     uint8_t bit_depth = 8;;
91     MPP_RET ret = MPP_OK;
92     MppFrameFormat pix_fmt = MPP_FMT_BUTT;
93 
94     if (seq->seq_profile == 2 && seq->color_config.high_bitdepth)
95         bit_depth = seq->color_config.twelve_bit ? 12 : 10;
96     else if (seq->seq_profile <= 2)
97         bit_depth = seq->color_config.high_bitdepth ? 10 : 8;
98     else {
99         mpp_err_f("Unknown AV1 profile %d.\n", seq->seq_profile);
100         return -1;
101     }
102 
103     if (!seq->color_config.mono_chrome) {
104         // 4:4:4 x:0 y:0, 4:2:2 x:1 y:0, 4:2:0 x:1 y:1
105         if (seq->color_config.subsampling_x == 0 &&
106             seq->color_config.subsampling_y == 0) {
107             mpp_err_f("no support yuv444 AV1 pixel format.\n");
108             return -1;
109         } else if (seq->color_config.subsampling_x == 1 &&
110                    seq->color_config.subsampling_y == 0) {
111             if (bit_depth == 8)
112                 pix_fmt = MPP_FMT_YUV422P;
113             else {
114                 mpp_err_f("no support yuv422 bit depth > 8\n");
115                 return -1;
116             }
117         } else if (seq->color_config.subsampling_x == 1 &&
118                    seq->color_config.subsampling_y == 1) {
119             if (bit_depth == 8)
120                 pix_fmt = MPP_FMT_YUV420SP;
121             else if (bit_depth == 10) {
122                 pix_fmt = MPP_FMT_YUV420SP_10BIT;
123                 /* rk3588, allow user config 8bit for 10bit source. */
124                 if ((ctx->usr_set_fmt & MPP_FRAME_FMT_MASK) == MPP_FMT_YUV420SP &&
125                     (s->cfg->base.out_fmt & MPP_FRAME_FMT_MASK) == MPP_FMT_YUV420SP)
126                     pix_fmt = MPP_FMT_YUV420SP;
127             } else {
128                 mpp_err_f("no support MPP_FMT_YUV420SP bit depth > 8\n");
129                 return -1;
130             }
131         }
132     } else {
133         mpp_err_f("no supprot PIX_FMT_GRAY pixel format.\n");
134         return -1;
135     }
136 
137 
138     if (pix_fmt == MPP_FMT_BUTT)
139         return -1;
140     ctx->pix_fmt = pix_fmt;
141     s->bit_depth = bit_depth;
142     return ret;
143 }
144 
inverse_recenter(RK_S32 r,RK_U32 v)145 static RK_U32 inverse_recenter(RK_S32 r, RK_U32 v)
146 {
147     if ((RK_S32)v > 2 * r)
148         return v;
149     else if (v & 1)
150         return r - ((v + 1) >> 1);
151     else
152         return r + (v >> 1);
153 }
154 
decode_unsigned_subexp_with_ref(RK_U32 sub_exp,RK_S32 mx,RK_S32 r)155 static RK_U32 decode_unsigned_subexp_with_ref(RK_U32 sub_exp,
156                                               RK_S32 mx, RK_S32 r)
157 {
158     if ((r << 1) <= mx) {
159         return inverse_recenter(r, sub_exp);
160     } else {
161         return mx - 1 - inverse_recenter(mx - 1 - r, sub_exp);
162     }
163 }
164 
decode_signed_subexp_with_ref(RK_U32 sub_exp,RK_S32 low,RK_S32 high,RK_S32 r)165 static RK_S32 decode_signed_subexp_with_ref(RK_U32 sub_exp, RK_S32 low,
166                                             RK_S32 high, RK_S32 r)
167 {
168     RK_S32 x = decode_unsigned_subexp_with_ref(sub_exp, high - low, r - low);
169     return x + low;
170 }
171 
read_global_param(AV1Context * s,RK_S32 type,RK_S32 ref,RK_S32 idx)172 static void read_global_param(AV1Context *s, RK_S32 type, RK_S32 ref, RK_S32 idx)
173 {
174     uint8_t primary_frame, prev_frame;
175     RK_U32 abs_bits, prec_bits, round, prec_diff, sub, mx;
176     RK_S32 r, prev_gm_param;
177 
178     primary_frame = s->raw_frame_header->primary_ref_frame;
179     prev_frame = s->raw_frame_header->ref_frame_idx[primary_frame];
180     abs_bits = AV1_GM_ABS_ALPHA_BITS;
181     prec_bits = AV1_GM_ALPHA_PREC_BITS;
182 
183     /* setup_past_independence() sets PrevGmParams to default values. We can
184      * simply point to the current's frame gm_params as they will be initialized
185      * with defaults at this point.
186      */
187     if (s->raw_frame_header->primary_ref_frame == AV1_PRIMARY_REF_NONE)
188         prev_gm_param = s->cur_frame.gm_params[ref].wmmat[idx];
189     else
190         prev_gm_param = s->ref[prev_frame].gm_params[ref].wmmat[idx];
191 
192     if (idx < 2) {
193         if (type == AV1_WARP_MODEL_TRANSLATION) {
194             abs_bits = AV1_GM_ABS_TRANS_ONLY_BITS -
195                        !s->raw_frame_header->allow_high_precision_mv;
196             prec_bits = AV1_GM_TRANS_ONLY_PREC_BITS -
197                         !s->raw_frame_header->allow_high_precision_mv;
198         } else {
199             abs_bits = AV1_GM_ABS_TRANS_BITS;
200             prec_bits = AV1_GM_TRANS_PREC_BITS;
201         }
202     }
203     round = (idx % 3) == 2 ? (1 << AV1_WARPEDMODEL_PREC_BITS) : 0;
204     prec_diff = AV1_WARPEDMODEL_PREC_BITS - prec_bits;
205     sub = (idx % 3) == 2 ? (1 << prec_bits) : 0;
206     mx = 1 << abs_bits;
207     r = (prev_gm_param >> prec_diff) - sub;
208 
209     s->cur_frame.gm_params[ref].wmmat[idx] =
210         (decode_signed_subexp_with_ref(s->raw_frame_header->gm_params[ref][idx],
211                                        -mx, mx + 1, r) << prec_diff) + round;
212 }
213 
round_two(RK_U64 x,RK_U16 n)214 static RK_U16 round_two(RK_U64 x, RK_U16 n)
215 {
216     if (n == 0)
217         return x;
218     return ((x + ((RK_U64)1 << (n - 1))) >> n);
219 }
220 
round_two_signed(RK_S64 x,RK_U16 n)221 static RK_S64 round_two_signed(RK_S64 x, RK_U16 n)
222 {
223     return ((x < 0) ? -((RK_S64)round_two(-x, n)) : (RK_S64)round_two(x, n));
224 }
225 
226 /**
227  * Resolve divisor process.
228  * see spec 7.11.3.7
229  */
resolve_divisor(RK_U32 d,RK_S16 * shift)230 static RK_S16 resolve_divisor(RK_U32 d, RK_S16 *shift)
231 {
232     RK_S32 e, f;
233 
234     *shift = mpp_log2(d);
235     e = d - (1 << (*shift));
236     if (*shift > AV1_DIV_LUT_BITS)
237         f = round_two(e, *shift - AV1_DIV_LUT_BITS);
238     else
239         f = e << (AV1_DIV_LUT_BITS - (*shift));
240 
241     *shift += AV1_DIV_LUT_PREC_BITS;
242 
243     return div_lut[f];
244 }
245 
246 /**
247  * check if global motion params is valid.
248  * see spec 7.11.3.6
249  */
get_shear_params_valid(AV1Context * s,RK_S32 idx)250 static RK_U8 get_shear_params_valid(AV1Context *s, RK_S32 idx)
251 {
252     RK_S16 alpha, beta, gamma, delta, divf, divs;
253     RK_S64 v, w;
254     RK_S32 *param = &s->cur_frame.gm_params[idx].wmmat[0];
255 
256     if (param[2] < 0)
257         return 0;
258 
259     alpha = MPP_CLIP3(INT16_MIN, INT16_MAX, param[2] - (1 << AV1_WARPEDMODEL_PREC_BITS));
260     beta  = MPP_CLIP3(INT16_MIN, INT16_MAX, param[3]);
261     divf  = resolve_divisor(MPP_ABS(param[2]), &divs) * (param[2] < 0 ? -1 : 1);
262     v     = (RK_S64)param[4] * (1 << AV1_WARPEDMODEL_PREC_BITS);
263     w     = (RK_S64)param[3] * param[4];
264     gamma = MPP_CLIP3(INT16_MIN, INT16_MAX, (RK_S32)round_two_signed((v * divf), divs));
265     delta = MPP_CLIP3(INT16_MIN, INT16_MAX, param[5] - (RK_S32)round_two_signed((w * divf), divs) -
266                       (1 << AV1_WARPEDMODEL_PREC_BITS));
267 
268     alpha = round_two_signed(alpha, AV1_WARP_PARAM_REDUCE_BITS) << AV1_WARP_PARAM_REDUCE_BITS;
269     beta  = round_two_signed(beta,  AV1_WARP_PARAM_REDUCE_BITS) << AV1_WARP_PARAM_REDUCE_BITS;
270     gamma = round_two_signed(gamma, AV1_WARP_PARAM_REDUCE_BITS) << AV1_WARP_PARAM_REDUCE_BITS;
271     delta = round_two_signed(delta, AV1_WARP_PARAM_REDUCE_BITS) << AV1_WARP_PARAM_REDUCE_BITS;
272 
273     s->cur_frame.gm_params[idx].alpha = alpha;
274     s->cur_frame.gm_params[idx].beta = beta;
275     s->cur_frame.gm_params[idx].gamma = gamma;
276     s->cur_frame.gm_params[idx].delta = delta;
277 
278     if ((4 * MPP_ABS(alpha) + 7 * MPP_ABS(beta)) >= (1 << AV1_WARPEDMODEL_PREC_BITS) ||
279         (4 * MPP_ABS(gamma) + 4 * MPP_ABS(delta)) >= (1 << AV1_WARPEDMODEL_PREC_BITS))
280         return 0;
281 
282     return 1;
283 }
284 
285 /**
286 * update gm type/params, since cbs already implemented part of this funcation,
287 * so we don't need to full implement spec.
288 */
global_motion_params(AV1Context * s)289 static void global_motion_params(AV1Context *s)
290 {
291     const AV1RawFrameHeader *header = s->raw_frame_header;
292     RK_S32 type, ref;
293     RK_S32 i = 0;
294     AV1Context *ctx = s;
295 
296     for (ref = AV1_REF_FRAME_LAST; ref <= AV1_REF_FRAME_ALTREF; ref++) {
297         s->cur_frame.gm_params[ref].wmtype = AV1_WARP_MODEL_IDENTITY;
298         for (i = 0; i < 6; i++)
299             s->cur_frame.gm_params[ref].wmmat[i] = (i % 3 == 2) ?
300                                                    1 << AV1_WARPEDMODEL_PREC_BITS : 0;
301     }
302     if (header->frame_type == AV1_FRAME_KEY ||
303         header->frame_type == AV1_FRAME_INTRA_ONLY)
304         return;
305 
306     for (ref = AV1_REF_FRAME_LAST; ref <= AV1_REF_FRAME_ALTREF; ref++) {
307         RK_U8 ref_uses_scaling = ctx->frame_width != ctx->ref_s[ref].frame_width ||
308                                  ctx->frame_height != ctx->ref_s[ref].frame_height;
309         RK_U32 shear_params_valid = 0;
310 
311         if (header->is_global[ref]) {
312             if (header->is_rot_zoom[ref]) {
313                 type = AV1_WARP_MODEL_ROTZOOM;
314             } else {
315                 type = header->is_translation[ref] ? AV1_WARP_MODEL_TRANSLATION
316                        : AV1_WARP_MODEL_AFFINE;
317             }
318         } else {
319             type = AV1_WARP_MODEL_IDENTITY;
320         }
321         s->cur_frame.gm_params[ref].wmtype = type;
322 
323         if (type >= AV1_WARP_MODEL_ROTZOOM) {
324             read_global_param(s, type, ref, 2);
325             read_global_param(s, type, ref, 3);
326             if (type == AV1_WARP_MODEL_AFFINE) {
327                 read_global_param(s, type, ref, 4);
328                 read_global_param(s, type, ref, 5);
329             } else {
330                 s->cur_frame.gm_params[ref].wmmat[4] = -s->cur_frame.gm_params[ref].wmmat[3];
331                 s->cur_frame.gm_params[ref].wmmat[5] = s->cur_frame.gm_params[ref].wmmat[2];
332             }
333         }
334         if (type >= AV1_WARP_MODEL_TRANSLATION) {
335             read_global_param(s, type, ref, 0);
336             read_global_param(s, type, ref, 1);
337         }
338 
339         if (type <= AV1_WARP_MODEL_AFFINE)
340             shear_params_valid = get_shear_params_valid(ctx, ref);
341 
342         if (!shear_params_valid || ref_uses_scaling) {
343             ctx->cur_frame.gm_params[ref].alpha = -32768;
344             ctx->cur_frame.gm_params[ref].beta  = -32768;
345             ctx->cur_frame.gm_params[ref].gamma = -32768;
346             ctx->cur_frame.gm_params[ref].delta = -32768;
347         }
348         av1d_dbg(AV1D_DBG_HEADER, "ref %d alpa %d beta %d gamma %d delta %d\n",
349                  ref,
350                  ctx->cur_frame.gm_params[ref].alpha,
351                  ctx->cur_frame.gm_params[ref].beta,
352                  ctx->cur_frame.gm_params[ref].gamma,
353                  ctx->cur_frame.gm_params[ref].delta);
354     }
355 }
356 
get_relative_dist(const AV1RawSequenceHeader * seq,RK_U32 a,RK_U32 b)357 static RK_S32 get_relative_dist(const AV1RawSequenceHeader *seq,
358                                 RK_U32 a, RK_U32 b)
359 {
360     RK_U32 diff = a - b;
361     RK_U32 m = 1 << seq->order_hint_bits_minus_1;
362     return (diff & (m - 1)) - (diff & m);
363 }
364 
skip_mode_params(AV1Context * s)365 static void skip_mode_params(AV1Context *s)
366 {
367     const AV1RawFrameHeader *header = s->raw_frame_header;
368     const AV1RawSequenceHeader *seq = s->sequence_header;
369 
370     RK_S32 forward_idx,  backward_idx;
371     RK_S32 forward_hint, backward_hint;
372     RK_S32 second_forward_idx, second_forward_hint;
373     RK_S32 ref_hint, dist, i;
374 
375     if (!header->skip_mode_present)
376         return;
377 
378     forward_idx  = -1;
379     backward_idx = -1;
380     forward_hint = -1;
381     backward_hint = -1;
382     for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
383         ref_hint = s->ref[header->ref_frame_idx[i]].order_hint;
384         dist = get_relative_dist(seq, ref_hint, header->order_hint);
385         if (dist < 0) {
386             if (forward_idx < 0 ||
387                 get_relative_dist(seq, ref_hint, forward_hint) > 0) {
388                 forward_idx  = i;
389                 forward_hint = ref_hint;
390             }
391         } else if (dist > 0) {
392             if (backward_idx < 0 ||
393                 get_relative_dist(seq, ref_hint, backward_hint) < 0) {
394                 backward_idx  = i;
395                 backward_hint = ref_hint;
396             }
397         }
398     }
399 
400     if (forward_idx < 0) {
401         return;
402     } else if (backward_idx >= 0) {
403         s->cur_frame.skip_mode_frame_idx[0] =
404             AV1_REF_FRAME_LAST + MPP_MIN(forward_idx, backward_idx);
405         s->cur_frame.skip_mode_frame_idx[1] =
406             AV1_REF_FRAME_LAST + MPP_MAX(forward_idx, backward_idx);
407         return;
408     }
409 
410     second_forward_idx = -1;
411     for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
412         ref_hint = s->ref[header->ref_frame_idx[i]].order_hint;
413         if (get_relative_dist(seq, ref_hint, forward_hint) < 0) {
414             if (second_forward_idx < 0 ||
415                 get_relative_dist(seq, ref_hint, second_forward_hint) > 0) {
416                 second_forward_idx  = i;
417                 second_forward_hint = ref_hint;
418             }
419         }
420     }
421 
422     if (second_forward_idx < 0)
423         return;
424 
425     s->cur_frame.skip_mode_frame_idx[0] =
426         AV1_REF_FRAME_LAST + MPP_MIN(forward_idx, second_forward_idx);
427     s->cur_frame.skip_mode_frame_idx[1] =
428         AV1_REF_FRAME_LAST + MPP_MAX(forward_idx, second_forward_idx);
429 }
430 
coded_lossless_param(AV1Context * s)431 static void coded_lossless_param(AV1Context *s)
432 {
433     const AV1RawFrameHeader *header = s->raw_frame_header;
434     RK_S32 i;
435 
436     if (header->delta_q_y_dc || header->delta_q_u_ac ||
437         header->delta_q_u_dc || header->delta_q_v_ac ||
438         header->delta_q_v_dc) {
439         s->cur_frame.coded_lossless = 0;
440         return;
441     }
442 
443     s->cur_frame.coded_lossless = 1;
444     for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
445         RK_S32 qindex;
446         if (header->feature_enabled[i][AV1_SEG_LVL_ALT_Q]) {
447             qindex = (header->base_q_idx +
448                       header->feature_value[i][AV1_SEG_LVL_ALT_Q]);
449         } else {
450             qindex = header->base_q_idx;
451         }
452         qindex = mpp_clip_uintp2(qindex, 8);
453 
454         if (qindex) {
455             s->cur_frame.coded_lossless = 0;
456             return;
457         }
458     }
459 }
460 
load_grain_params(AV1Context * s)461 static void load_grain_params(AV1Context *s)
462 {
463     const AV1RawFrameHeader *header = s->raw_frame_header;
464     const AV1RawFilmGrainParams *film_grain = &header->film_grain, *src;
465     AV1RawFilmGrainParams *dst = &s->cur_frame.film_grain;
466 
467     if (!film_grain->apply_grain)
468         return;
469 
470     if (film_grain->update_grain) {
471         memcpy(dst, film_grain, sizeof(*dst));
472         return;
473     }
474 
475     src = &s->ref[film_grain->film_grain_params_ref_idx].film_grain;
476 
477     memcpy(dst, src, sizeof(*dst));
478     dst->grain_seed = film_grain->grain_seed;
479 }
480 
481 typedef struct GetByteCxt_t {
482     const uint8_t *buffer, *buffer_end, *buffer_start;
483 } GetByteCxt;
bytestream_init(GetByteCxt * g,const uint8_t * buf,int buf_size)484 void bytestream_init(GetByteCxt *g,
485                      const uint8_t *buf,
486                      int buf_size)
487 {
488     mpp_assert(buf_size >= 0);
489     g->buffer       = buf;
490     g->buffer_start = buf;
491     g->buffer_end   = buf + buf_size;
492 }
493 
bytestream_get_bytes_left(GetByteCxt * g)494 static int bytestream_get_bytes_left(GetByteCxt *g)
495 {
496     return g->buffer_end - g->buffer;
497 }
498 
bytestream_skipu(GetByteCxt * g,unsigned int size)499 static void bytestream_skipu(GetByteCxt *g, unsigned int size)
500 {
501     g->buffer += size;
502 }
503 
bytestream_tell(GetByteCxt * g)504 static int bytestream_tell(GetByteCxt *g)
505 {
506     return (int)(g->buffer - g->buffer_start);
507 }
508 
bytestream_get_byteu(GetByteCxt * g)509 static int bytestream_get_byteu(GetByteCxt *g)
510 {
511     int tmp;
512     tmp = g->buffer[0];
513     g->buffer++;
514     return tmp;
515 }
516 
get_tiles_info(Av1CodecContext * ctx,const AV1RawTileGroup * tile_group)517 static RK_S32 get_tiles_info(Av1CodecContext *ctx, const AV1RawTileGroup *tile_group)
518 {
519     AV1Context *s = ctx->priv_data;
520     GetByteCxt gb;
521     RK_S16 tile_num;
522     RK_S32 size = 0, size_bytes = 0;
523     RK_S32 i;
524 
525     bytestream_init(&gb, tile_group->tile_data.data,
526                     tile_group->tile_data.data_size);
527 
528     if (s->tile_offset)
529         s->tile_offset += tile_group->tile_data.offset;
530 
531     for (tile_num = tile_group->tg_start; tile_num <= tile_group->tg_end; tile_num++) {
532         if (tile_num == tile_group->tg_end) {
533             s->tile_offset_start[tile_num] = bytestream_tell(&gb) + s->tile_offset;
534             s->tile_offset_end[tile_num] = bytestream_tell(&gb) + bytestream_get_bytes_left(&gb) + s->tile_offset;
535             s->tile_offset = s->tile_offset_end[tile_num];
536             return 0;
537         }
538         size_bytes = s->raw_frame_header->tile_size_bytes_minus1 + 1;
539         if (bytestream_get_bytes_left(&gb) < size_bytes)
540             return MPP_ERR_VALUE;
541         size = 0;
542         for (i = 0; i < size_bytes; i++)
543             size |= bytestream_get_byteu(&gb) << 8 * i;
544         if (bytestream_get_bytes_left(&gb) <= size)
545             return MPP_ERR_VALUE;
546         size++;
547 
548         s->tile_offset_start[tile_num] = bytestream_tell(&gb) + s->tile_offset;
549 
550         s->tile_offset_end[tile_num] = bytestream_tell(&gb) + size + s->tile_offset;
551 
552         bytestream_skipu(&gb, size);
553     }
554 
555     return 0;
556 
557 }
558 
av1d_frame_unref(Av1CodecContext * ctx,AV1Frame * f)559 static void av1d_frame_unref(Av1CodecContext *ctx, AV1Frame *f)
560 {
561     AV1Context *s = ctx->priv_data;
562     f->raw_frame_header = NULL;
563     f->spatial_id = f->temporal_id = 0;
564     memset(f->skip_mode_frame_idx, 0,
565            2 * sizeof(uint8_t));
566     memset(&f->film_grain, 0, sizeof(f->film_grain));
567 
568     f->coded_lossless = 0;
569 
570     if (!f->ref || f->ref->ref_count <= 0 || f->slot_index >= 0x7f) {
571         mpp_err("ref count alreay is zero");
572         return;
573     }
574 
575     f->ref->ref_count--;
576     av1d_dbg(AV1D_DBG_REF, "ref %p, f->ref->ref_count %d, ref->invisible= %d", f->ref, f->ref->ref_count, f->ref->invisible);
577     if (!f->ref->ref_count) {
578         if (f->slot_index < 0x7f) {
579             av1d_dbg(AV1D_DBG_REF, "clr f->slot_index = %d",  f->slot_index);
580             /* if pic no output for disaplay when ref_cnt
581                clear we will free this buffer directly,
582                maybe cause some frame can't display    */
583             // if (f->ref->invisible && !f->ref->is_output) {
584             if (!f->ref->is_output) {
585                 MppBuffer framebuf = NULL;
586                 mpp_buf_slot_get_prop(s->slots, f->slot_index, SLOT_BUFFER, &framebuf);
587                 av1d_dbg(AV1D_DBG_REF, "free framebuf prt %p", framebuf);
588                 if (framebuf)
589                     mpp_buffer_put(framebuf);
590                 f->ref->invisible = 0;
591             }
592             mpp_buf_slot_clr_flag(s->slots, f->slot_index, SLOT_CODEC_USE);
593         }
594         f->slot_index = 0xff;
595         mpp_free(f->ref);
596         f->ref = NULL;
597     }
598     f->ref = NULL;
599 }
600 
601 
set_output_frame(Av1CodecContext * ctx)602 static MPP_RET set_output_frame(Av1CodecContext *ctx)
603 {
604     AV1Context *s = ctx->priv_data;
605     MppFrame frame = NULL;
606     MPP_RET ret = MPP_OK;
607 
608     // TODO: all layers
609     if (s->operating_point_idc &&
610         mpp_log2(s->operating_point_idc >> 8) > s->cur_frame.spatial_id)
611         return 0;
612     mpp_buf_slot_get_prop(s->slots, s->cur_frame.slot_index, SLOT_FRAME_PTR, &frame);
613     if (s->hdr_dynamic_meta && s->hdr_dynamic) {
614         mpp_frame_set_hdr_dynamic_meta(frame, s->hdr_dynamic_meta);
615         s->hdr_dynamic = 0;
616         if (s->raw_frame_header->show_existing_frame)
617             fill_hdr_meta_to_frame(frame, HDR_AV1);
618     }
619     mpp_frame_set_pts(frame, s->pts);
620     mpp_buf_slot_set_flag(s->slots, s->cur_frame.slot_index, SLOT_QUEUE_USE);
621     mpp_buf_slot_enqueue(s->slots, s->cur_frame.slot_index, QUEUE_DISPLAY);
622     s->cur_frame.ref->is_output = 1;
623 
624     return ret;
625 }
626 
av1d_frame_ref(Av1CodecContext * ctx,AV1Frame * dst,const AV1Frame * src)627 static RK_S32 av1d_frame_ref(Av1CodecContext *ctx, AV1Frame *dst, const AV1Frame *src)
628 {
629     AV1Context *s = ctx->priv_data;
630     MppFrameImpl *impl_frm = (MppFrameImpl *)dst->f;
631     dst->spatial_id = src->spatial_id;
632     dst->temporal_id = src->temporal_id;
633     dst->order_hint  = src->order_hint;
634 
635     memcpy(dst->gm_params,
636            src->gm_params,
637            sizeof(src->gm_params));
638     memcpy(dst->skip_mode_frame_idx,
639            src->skip_mode_frame_idx,
640            2 * sizeof(uint8_t));
641     memcpy(&dst->film_grain,
642            &src->film_grain,
643            sizeof(dst->film_grain));
644     dst->coded_lossless = src->coded_lossless;
645 
646     if (src->slot_index >= 0x7f) {
647         mpp_err("av1d_ref_frame is vaild");
648         return -1;
649     }
650 
651     dst->slot_index = src->slot_index;
652     dst->ref = src->ref;
653     dst->ref->ref_count++;
654 
655     mpp_buf_slot_get_prop(s->slots, src->slot_index, SLOT_FRAME, &dst->f);
656     impl_frm->buffer = NULL; //parser no need process hal buf
657 
658 
659     return 0;
660 }
661 
update_reference_list(Av1CodecContext * ctx)662 static MPP_RET update_reference_list(Av1CodecContext *ctx)
663 {
664     AV1Context *s = ctx->priv_data;
665     const AV1RawFrameHeader *header = s->raw_frame_header;
666     MPP_RET ret = MPP_OK;
667     RK_S32 i = 0;
668     RK_S32 lst2_buf_idx;
669     RK_S32 lst3_buf_idx;
670     RK_S32 gld_buf_idx;
671     RK_S32 alt_buf_idx;
672     RK_S32 lst_buf_idx;
673     RK_S32 bwd_buf_idx;
674     RK_S32 alt2_buf_idx;
675 
676     if (!header->show_existing_frame) {
677         lst2_buf_idx = s->raw_frame_header->ref_frame_idx[AV1_REF_FRAME_LAST2 - AV1_REF_FRAME_LAST];
678         lst3_buf_idx = s->raw_frame_header->ref_frame_idx[AV1_REF_FRAME_LAST3 - AV1_REF_FRAME_LAST];
679         gld_buf_idx =  s->raw_frame_header->ref_frame_idx[AV1_REF_FRAME_GOLDEN - AV1_REF_FRAME_LAST];
680         alt_buf_idx =  s->raw_frame_header->ref_frame_idx[AV1_REF_FRAME_ALTREF - AV1_REF_FRAME_LAST];
681         lst_buf_idx =  s->raw_frame_header->ref_frame_idx[AV1_REF_FRAME_LAST - AV1_REF_FRAME_LAST];
682         bwd_buf_idx =  s->raw_frame_header->ref_frame_idx[AV1_REF_FRAME_BWDREF - AV1_REF_FRAME_LAST];
683         alt2_buf_idx = s->raw_frame_header->ref_frame_idx[AV1_REF_FRAME_ALTREF2 - AV1_REF_FRAME_LAST];
684 
685         s->cur_frame.ref->lst2_frame_offset = s->ref[lst2_buf_idx].order_hint;
686         s->cur_frame.ref->lst3_frame_offset = s->ref[lst3_buf_idx].order_hint;
687         s->cur_frame.ref->gld_frame_offset  = s->ref[gld_buf_idx].order_hint;
688         s->cur_frame.ref->alt_frame_offset  = s->ref[alt_buf_idx].order_hint;
689         s->cur_frame.ref->lst_frame_offset  = s->ref[lst_buf_idx].order_hint;
690         s->cur_frame.ref->bwd_frame_offset  = s->ref[bwd_buf_idx].order_hint;
691         s->cur_frame.ref->alt2_frame_offset = s->ref[alt2_buf_idx].order_hint;
692     }
693 
694     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
695         av1d_dbg(AV1D_DBG_REF, "header->refresh_frame_flags = %d",
696                  header->refresh_frame_flags);
697         if (header->refresh_frame_flags & (1 << i)) {
698             av1d_dbg(AV1D_DBG_REF, "av1 ref idx %d s->ref[%d].slot_index %d",
699                      i, i, s->ref[i].slot_index);
700             if (s->ref[i].ref)
701                 av1d_frame_unref(ctx, &s->ref[i]);
702 
703             if ((ret = av1d_frame_ref(ctx, &s->ref[i], &s->cur_frame)) < 0) {
704                 mpp_err_f("Failed to update frame %d in reference list\n", i);
705                 return ret;
706             }
707         }
708     }
709     return ret;
710 }
711 
hor_align_16(RK_U32 val)712 static RK_U32 hor_align_16(RK_U32 val)
713 {
714     return MPP_ALIGN(val, 16);
715 }
716 
get_current_frame(Av1CodecContext * ctx)717 static MPP_RET get_current_frame(Av1CodecContext *ctx)
718 {
719     AV1Context *s = ctx->priv_data;
720     MPP_RET ret = MPP_OK;
721     AV1Frame *frame = &s->cur_frame;
722     RK_U32 value;
723 
724     if (frame->ref)
725         av1d_frame_unref(ctx, frame);
726 
727     mpp_frame_set_meta(frame->f, NULL);
728     mpp_frame_set_width(frame->f, s->frame_width);
729     mpp_frame_set_height(frame->f, s->frame_height);
730 
731     /*
732      * rk3588, user can set 8bit for 10bit source.
733      * If user config 8bit output when input video is 10bti,
734      * here should set hor_stride according to 8bit.
735      */
736     if (MPP_FRAME_FMT_IS_YUV_10BIT(ctx->pix_fmt))
737         mpp_frame_set_hor_stride(frame->f, MPP_ALIGN(s->frame_width * s->bit_depth / 8, 8));
738     else
739         mpp_frame_set_hor_stride(frame->f, MPP_ALIGN(s->frame_width, 8));
740 
741     mpp_frame_set_ver_stride(frame->f, MPP_ALIGN(s->frame_height, 8));
742     mpp_frame_set_errinfo(frame->f, 0);
743     mpp_frame_set_discard(frame->f, 0);
744     mpp_frame_set_pts(frame->f, s->pts);
745 
746     if (s->is_hdr)
747         ctx->pix_fmt |= MPP_FRAME_HDR;
748 
749     if (MPP_FRAME_FMT_IS_FBC(s->cfg->base.out_fmt)) {
750         mpp_slots_set_prop(s->slots, SLOTS_HOR_ALIGN, hor_align_16);
751         if (s->bit_depth == 10) {
752             if (ctx->pix_fmt == MPP_FMT_YUV420SP || ctx->pix_fmt == MPP_FMT_YUV420SP_10BIT)
753                 ctx->pix_fmt = MPP_FMT_YUV420SP_10BIT;
754             else
755                 mpp_err("422p 10bit no support");
756         }
757 
758         mpp_frame_set_fmt(frame->f, ctx->pix_fmt | ((s->cfg->base.out_fmt & (MPP_FRAME_FBC_MASK))));
759         mpp_frame_set_offset_x(frame->f, 0);
760         mpp_frame_set_offset_y(frame->f, 0);
761         mpp_frame_set_ver_stride(frame->f, MPP_ALIGN(ctx->height, 8) + 28);
762     } else
763         mpp_frame_set_fmt(frame->f, ctx->pix_fmt);
764 
765     value = 4;
766     mpp_slots_set_prop(s->slots, SLOTS_NUMERATOR, &value);
767     value = 1;
768     mpp_slots_set_prop(s->slots, SLOTS_DENOMINATOR, &value);
769     mpp_buf_slot_get_unused(s->slots, &frame->slot_index);
770     av1d_dbg(AV1D_DBG_REF, "get frame->slot_index %d", frame->slot_index);
771     mpp_buf_slot_set_prop(s->slots, frame->slot_index, SLOT_FRAME, frame->f);
772     mpp_buf_slot_set_flag(s->slots, frame->slot_index, SLOT_CODEC_USE);
773     mpp_buf_slot_set_flag(s->slots, frame->slot_index, SLOT_HAL_OUTPUT);
774 
775     frame->ref = mpp_calloc(RefInfo, 1);
776     frame->ref->ref_count++;
777     frame->ref->is_intra_frame = !s->raw_frame_header->frame_type;
778     frame->ref->intra_only     = (s->raw_frame_header->frame_type == 2);
779     frame->ref->is_output = 0;
780     if (!s->raw_frame_header->show_frame && !s->raw_frame_header->showable_frame) {
781         frame->ref->invisible = 1;
782     }
783 
784     if (ret < 0) {
785         mpp_err_f("Failed to allocate space for current frame.\n");
786         return ret;
787     }
788 
789     /*  ret = init_tile_data(s);
790       if (ret < 0) {
791           mpp_err_f( "Failed to init tile data.\n");
792           return ret;
793       }*/
794     global_motion_params(s);
795     skip_mode_params(s);
796     coded_lossless_param(s);
797     load_grain_params(s);
798 
799     return ret;
800 }
801 
av1d_parser_init(Av1CodecContext * ctx,ParserCfg * init)802 MPP_RET av1d_parser_init(Av1CodecContext *ctx, ParserCfg *init)
803 {
804     MPP_RET ret = MPP_OK;
805     RK_S32 i = 0;
806     av1d_dbg_func("enter ctx %p\n", ctx);
807     AV1Context *s = mpp_calloc(AV1Context, 1);
808     ctx->priv_data = (void*)s;
809     if (!ctx->priv_data) {
810         mpp_err("av1d codec context malloc fail");
811         return MPP_ERR_NOMEM;
812     }
813 
814     s->seq_ref = mpp_calloc(AV1RawSequenceHeader, 1);
815 
816     s->unit_types = unit_types;
817     s->nb_unit_types = MPP_ARRAY_ELEMS(unit_types);
818     s->packet_slots = init->packet_slots;
819     s->slots = init->frame_slots;
820     s->cfg = init->cfg;
821     mpp_buf_slot_setup(s->slots, 25);
822 
823     mpp_env_get_u32("av1d_debug", &av1d_debug, 0);
824     for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
825         mpp_frame_init(&s->ref[i].f);
826         if (!s->ref[i].f) {
827             mpp_err("Failed to allocate frame buffer %d\n", i);
828             return MPP_ERR_NOMEM;
829         }
830         s->ref[i].slot_index = 0x7f;
831         s->ref[i].ref = NULL;
832     }
833 
834     mpp_frame_init(&s->cur_frame.f);
835     s->cur_frame.ref = NULL;
836     s->cur_frame.slot_index = 0xff;
837     if (!s->cur_frame.f) {
838         mpp_err("Failed to allocate frame buffer %d\n", i);
839         return MPP_ERR_NOMEM;
840     }
841     s->cdfs = &s->default_cdfs;
842     s->cdfs_ndvc = &s->default_cdfs_ndvc;
843     AV1SetDefaultCDFs(s->cdfs, s->cdfs_ndvc);
844 
845     return MPP_OK;
846 
847     av1d_dbg_func("leave ctx %p\n", ctx);
848 
849     return ret;
850 }
851 
av1d_parser_deinit(Av1CodecContext * ctx)852 MPP_RET av1d_parser_deinit(Av1CodecContext *ctx)
853 {
854     MPP_RET ret = MPP_OK;
855     RK_U32 i = 0;
856 
857     AV1Context *s = ctx->priv_data;
858     for ( i = 0; i < MPP_ARRAY_ELEMS(s->ref); i++) {
859         if (s->ref[i].ref) {
860             av1d_frame_unref(ctx, &s->ref[i]);
861         }
862         mpp_frame_deinit(&s->ref[i].f);
863         s->ref[i].f = NULL;
864     }
865     if (s->cur_frame.ref) {
866         av1d_frame_unref(ctx, &s->cur_frame);
867     }
868     mpp_frame_deinit(&s->cur_frame.f);
869 
870     mpp_av1_fragment_reset(&s->current_obu);
871     MPP_FREE(s->seq_ref);
872     MPP_FREE((s->hdr_dynamic_meta));
873     MPP_FREE(ctx->priv_data);
874     return MPP_OK;
875 
876     av1d_dbg_func("leave ctx %p\n", ctx);
877 
878     return ret;
879 }
880 
av1d_parser_frame(Av1CodecContext * ctx,HalDecTask * task)881 MPP_RET av1d_parser_frame(Av1CodecContext *ctx, HalDecTask *task)
882 {
883     RK_U8 *data = NULL;
884     RK_S32 size = 0;
885     AV1Context *s = ctx->priv_data;
886     AV1RawTileGroup *raw_tile_group = NULL;
887     MPP_RET ret = MPP_OK;
888     RK_S32 i;
889 
890     av1d_dbg_func("enter ctx %p\n", ctx);
891     task->valid = 0;
892 
893     data = (RK_U8 *)mpp_packet_get_pos(ctx->pkt);
894     size = (RK_S32)mpp_packet_get_length(ctx->pkt);
895 
896     s->pts = mpp_packet_get_pts(ctx->pkt);
897 
898     s->current_obu.data = data;
899     s->current_obu.data_size = size;
900     s->tile_offset = 0;
901     ret = mpp_av1_split_fragment(s, &s->current_obu, 0);
902     if (ret < 0) {
903         return ret;
904     }
905     ret = mpp_av1_read_fragment_content(s, &s->current_obu);
906     if (ret < 0) {
907         return ret;
908     }
909 
910     for (i = 0; i < s->current_obu.nb_units; i++) {
911         Av1ObuUnit *unit = &s->current_obu.units[i];
912         AV1RawOBU  *obu = unit->content;
913         const AV1RawOBUHeader *header;
914 
915         if (!obu)
916             continue;
917 
918         header = &obu->header;
919 
920         switch (unit->type) {
921         case AV1_OBU_SEQUENCE_HEADER:
922             memcpy(s->seq_ref, &obu->obu.sequence_header, sizeof(AV1RawSequenceHeader));
923             s->sequence_header = s->seq_ref;
924             ret = mpp_av1_set_context_with_sequence(ctx, s->sequence_header);
925             if (ret < 0) {
926                 mpp_err_f("Failed to set context.\n");
927                 s->sequence_header = NULL;
928                 goto end;
929             }
930 
931             s->operating_point_idc = s->sequence_header->operating_point_idc[s->operating_point];
932 
933             if (ctx->pix_fmt == MPP_FMT_BUTT) {
934                 ret = get_pixel_format(ctx);
935                 if (ret < 0) {
936                     mpp_err_f("Failed to get pixel format.\n");
937                     s->sequence_header = NULL;
938                     goto end;
939                 }
940             }
941             break;
942         case AV1_OBU_REDUNDANT_FRAME_HEADER:
943             if (s->raw_frame_header)
944                 break;
945             // fall-through
946         case AV1_OBU_FRAME:
947         case AV1_OBU_FRAME_HEADER:
948             if (!s->sequence_header) {
949                 mpp_err_f("Missing Sequence Header.\n");
950                 ret = MPP_ERR_VALUE;
951                 goto end;
952             }
953 
954             if (unit->type == AV1_OBU_FRAME)
955                 s->raw_frame_header = &obu->obu.frame.header;
956             else
957                 s->raw_frame_header = &obu->obu.frame_header;
958 
959             if (s->raw_frame_header->show_existing_frame) {
960                 if (s->cur_frame.ref) {
961                     av1d_frame_unref(ctx, &s->cur_frame);
962                 }
963 
964                 ret = av1d_frame_ref(ctx, &s->cur_frame,
965                                      &s->ref[s->raw_frame_header->frame_to_show_map_idx]);
966 
967                 if (ret < 0) {
968                     mpp_err_f("Failed to get reference frame.\n");
969                     goto end;
970                 }
971 
972                 ret = update_reference_list(ctx);
973                 if (ret < 0) {
974                     mpp_err_f("Failed to update reference list.\n");
975                     goto end;
976                 }
977                 ret = set_output_frame(ctx);
978                 if (ret < 0)
979                     mpp_err_f("Set output frame error.\n");
980 
981                 s->raw_frame_header = NULL;
982 
983                 goto end;
984             }
985             ret = get_current_frame(ctx);
986             if (ret < 0) {
987                 mpp_err_f("Get current frame error\n");
988                 goto end;
989             }
990             s->cur_frame.spatial_id  = header->spatial_id;
991             s->cur_frame.temporal_id = header->temporal_id;
992             s->cur_frame.order_hint  = s->raw_frame_header->order_hint;
993 
994             if (unit->type != AV1_OBU_FRAME)
995                 break;
996             // fall-through
997         case AV1_OBU_TILE_GROUP:
998             if (!s->raw_frame_header) {
999                 mpp_err_f("Missing Frame Header.\n");
1000                 ret = MPP_ERR_VALUE;
1001                 goto end;
1002             }
1003 
1004             if (unit->type == AV1_OBU_FRAME)
1005                 raw_tile_group = &obu->obu.frame.tile_group;
1006             else
1007                 raw_tile_group = &obu->obu.tile_group;
1008 
1009             ret = get_tiles_info(ctx, raw_tile_group);
1010             if (ret < 0)
1011                 goto end;
1012 
1013             break;
1014         case AV1_OBU_TILE_LIST:
1015         case AV1_OBU_TEMPORAL_DELIMITER:
1016         case AV1_OBU_PADDING:
1017         case AV1_OBU_METADATA:
1018             break;
1019         default:
1020             av1d_dbg(AV1D_DBG_HEADER, "Unknown obu type: %d (%d bits).\n",
1021                      unit->type, unit->data_size);
1022         }
1023 
1024         if (raw_tile_group && (s->tile_num == raw_tile_group->tg_end + 1)) {
1025             av1d_parser2_syntax(ctx);
1026             task->syntax.data = (void*)&ctx->pic_params;
1027             task->syntax.number = 1;
1028             task->valid = 1;
1029             task->output = s->cur_frame.slot_index;
1030             task->input_packet = ctx->pkt;
1031 
1032             for (i = 0; i < AV1_REFS_PER_FRAME; i++) {
1033                 int8_t ref_idx = s->raw_frame_header->ref_frame_idx[i];
1034                 if (s->ref[ref_idx].slot_index < 0x7f) {
1035                     mpp_buf_slot_set_flag(s->slots, s->ref[ref_idx].slot_index, SLOT_HAL_INPUT);
1036                     MppFrame mframe = NULL;
1037                     task->refer[i] = s->ref[ref_idx].slot_index;
1038                     mpp_buf_slot_get_prop(s->slots, task->refer[i], SLOT_FRAME_PTR, &mframe);
1039                     if (mframe)
1040                         task->flags.ref_err |= mpp_frame_get_errinfo(mframe);
1041                 } else {
1042                     task->refer[i] = -1;
1043                 }
1044             }
1045             ret = update_reference_list(ctx);
1046             if (ret < 0) {
1047                 mpp_err_f("Failed to update reference list.\n");
1048                 goto end;
1049             }
1050 
1051             if (s->raw_frame_header->show_frame) {
1052                 ret = set_output_frame(ctx);
1053                 if (ret < 0) {
1054                     mpp_err_f("Set output frame error\n");
1055                     goto end;
1056                 }
1057             }
1058             raw_tile_group = NULL;
1059             s->raw_frame_header = NULL;
1060         }
1061     }
1062 
1063     if (s->eos) {
1064         task->flags.eos = 1;
1065     }
1066 end:
1067     mpp_av1_fragment_reset(&s->current_obu);
1068     if (ret < 0)
1069         s->raw_frame_header = NULL;
1070 
1071     av1d_dbg_func("leave ctx %p\n", ctx);
1072     return ret;
1073 }
1074 
av1d_parser_update(Av1CodecContext * ctx,void * info)1075 void av1d_parser_update(Av1CodecContext *ctx, void *info)
1076 {
1077     AV1Context* c_ctx = (AV1Context*)ctx->priv_data;
1078     DecCbHalDone *cb = (DecCbHalDone*)info;
1079     RK_U8 *data = (RK_U8*)cb->task;
1080     RK_U32 i;
1081     const RK_U32 mv_cdf_offset = offsetof(AV1CDFs, mv_cdf);
1082     const RK_U32 mv_cdf_size = sizeof(MvCDFs);
1083     const RK_U32 mv_cdf_end_offset = mv_cdf_offset + mv_cdf_size;
1084     const RK_U32 cdf_size = sizeof(AV1CDFs);
1085 
1086     av1d_dbg_func("enter ctx %p\n", ctx);
1087     if (!c_ctx->disable_frame_end_update_cdf) {
1088         for (i = 0; i < NUM_REF_FRAMES; i++) {
1089             if (c_ctx->refresh_frame_flags & (1 << i)) {
1090                 /* 1. get cdfs */
1091                 Av1GetCDFs(c_ctx, i);
1092                 {
1093                     RK_U8 *cdf_base = (RK_U8 *)c_ctx->cdfs;
1094                     RK_U8 *cdf_ndvc_base = (RK_U8 *)c_ctx->cdfs_ndvc;
1095                     /* 2. read cdfs from memory*/
1096                     if (c_ctx->frame_is_intra) {
1097                         memcpy(cdf_base, data, mv_cdf_offset);
1098                         // Read intrabc MV context
1099                         memcpy(cdf_ndvc_base, data + mv_cdf_offset, mv_cdf_size);
1100                         memcpy(cdf_base + mv_cdf_end_offset, data + mv_cdf_end_offset,
1101                                cdf_size - mv_cdf_end_offset);
1102                     } else {
1103                         memcpy(cdf_base, data, cdf_size);
1104                     }
1105                 }
1106                 /* 3. store cdfs*/
1107                 Av1StoreCDFs(c_ctx, c_ctx->refresh_frame_flags);
1108                 break;
1109             }
1110         }
1111     }
1112 
1113     av1d_dbg_func("leave ctx %p\n", ctx);
1114 }
1115 
av1d_paser_reset(Av1CodecContext * ctx)1116 MPP_RET av1d_paser_reset(Av1CodecContext *ctx)
1117 {
1118     (void)ctx;
1119     MPP_RET ret = MPP_OK;
1120     RK_U32 i = 0;
1121     AV1Context *s = ctx->priv_data;
1122 
1123     av1d_dbg_func("enter ctx %p\n", ctx);
1124     for ( i = 0; i < MPP_ARRAY_ELEMS(s->ref); i++) {
1125         AV1Frame *f = &s->ref[i];
1126 
1127         if (f->ref)
1128             av1d_frame_unref(ctx, &s->ref[i]);
1129     }
1130 
1131     if (s->cur_frame.ref) {
1132         av1d_frame_unref(ctx, &s->cur_frame);
1133     }
1134 
1135     ctx->frame_header = 0;
1136     ctx->stream_offset = 0;
1137     ctx->eos = 0;
1138 
1139     av1d_dbg_func("leave ctx %p\n", ctx);
1140     return ret;
1141 
1142 }
1143 
1144 
leb128(BitReadCtx_t * gb)1145 static inline int64_t leb128(BitReadCtx_t *gb)
1146 {
1147     int64_t ret = 0;
1148     RK_S32 byte = 0;
1149     RK_S32 i;
1150 
1151     for (i = 0; i < 8; i++) {
1152         mpp_read_bits(gb, 8, &byte);
1153         ret |= (int64_t)(byte & 0x7f) << (i * 7);
1154         if (!(byte & 0x80))
1155             break;
1156     }
1157     return ret;
1158 }
1159 
parse_obu_header(uint8_t * buf,RK_S32 buf_size,int64_t * obu_size,RK_S32 * start_pos,RK_S32 * type,RK_S32 * temporal_id,RK_S32 * spatial_id)1160 static inline RK_S32 parse_obu_header(uint8_t *buf, RK_S32 buf_size,
1161                                       int64_t *obu_size, RK_S32 *start_pos, RK_S32 *type,
1162                                       RK_S32 *temporal_id, RK_S32 *spatial_id)
1163 {
1164     BitReadCtx_t gb;
1165     RK_S32 extension_flag, has_size_flag;
1166     int64_t size;
1167     RK_S32 value = 0;
1168     mpp_set_bitread_ctx(&gb, buf, MPP_MIN(buf_size, MAX_OBU_HEADER_SIZE));
1169 
1170     mpp_read_bits(&gb, 1, &value);
1171     if (value != 0) // obu_forbidden_bit
1172         return MPP_ERR_PROTOL;
1173 
1174     mpp_read_bits(&gb, 4, type);
1175     mpp_read_bits(&gb, 1, &extension_flag);
1176     mpp_read_bits(&gb, 1, &has_size_flag);
1177     mpp_skip_bits(&gb, 1); // obu_reserved_1bit
1178 
1179     if (extension_flag) {
1180         mpp_read_bits(&gb, 3, temporal_id);
1181         mpp_read_bits(&gb, 2, spatial_id);
1182         mpp_skip_bits(&gb, 3); // extension_header_reserved_3bits
1183     } else {
1184         *temporal_id = *spatial_id = 0;
1185     }
1186 
1187     *obu_size  = has_size_flag ? leb128(&gb)
1188                  : buf_size - 1 - extension_flag;
1189 
1190     if (mpp_get_bits_left(&gb) < 0)
1191         return MPP_ERR_PROTOL;
1192 
1193     *start_pos = mpp_get_bits_count(&gb) / 8;
1194 
1195     size = *obu_size + *start_pos;
1196 
1197     if (size > buf_size)
1198         return MPP_ERR_PROTOL;
1199 
1200     return size;
1201 
1202 }
1203 
av1_extract_obu(AV1OBU * obu,uint8_t * buf,RK_S32 length)1204 RK_S32 av1_extract_obu(AV1OBU *obu, uint8_t *buf, RK_S32 length)
1205 {
1206     int64_t obu_size;
1207     RK_S32 start_pos, type, temporal_id, spatial_id;
1208     RK_S32 len;
1209 
1210     len = parse_obu_header(buf, length, &obu_size, &start_pos,
1211                            &type, &temporal_id, &spatial_id);
1212     if (len < 0)
1213         return len;
1214 
1215     obu->type        = type;
1216     obu->temporal_id = temporal_id;
1217     obu->spatial_id  = spatial_id;
1218 
1219     obu->data     = buf + start_pos;
1220     obu->size     = obu_size;
1221     obu->raw_data = buf;
1222     obu->raw_size = len;
1223 
1224     av1d_dbg(AV1D_DBG_STRMIN, "obu_type: %d, temporal_id: %d, spatial_id: %d, payload size: %d\n",
1225              obu->type, obu->temporal_id, obu->spatial_id, obu->size);
1226 
1227     return len;
1228 }
1229 
av1d_split_frame(Av1CodecContext * ctx,RK_U8 ** out_data,RK_S32 * out_size,RK_U8 * data,RK_S32 size)1230 RK_S32 av1d_split_frame(Av1CodecContext *ctx,
1231                         RK_U8 **out_data, RK_S32 *out_size,
1232                         RK_U8 *data, RK_S32 size)
1233 {
1234     (void)out_data;
1235     (void)out_size;
1236 
1237     AV1OBU obu;
1238     uint8_t *ptr = data, *end = data + size;
1239     av1d_dbg_func("enter ctx %p\n", ctx);
1240 
1241     *out_data = data;
1242 
1243     while (ptr < end) {
1244         RK_S32 len = av1_extract_obu(&obu, ptr, size);
1245         if (len < 0)
1246             break;
1247         if (obu.type == AV1_OBU_FRAME_HEADER || obu.type == AV1_OBU_FRAME ||
1248             ((obu.type == AV1_OBU_TEMPORAL_DELIMITER ||
1249               obu.type == AV1_OBU_SEQUENCE_HEADER) && ctx->frame_header))
1250             ctx->frame_header ++;
1251         if (ctx->frame_header == 2) {
1252             *out_size = (RK_S32)(ptr - data);
1253             ctx->new_frame = 1;
1254             ctx->frame_header = 0;
1255             return ptr - data;
1256         }
1257         if (obu.type == AV1_OBU_FRAME) {
1258             ptr      += len;
1259             size     -= len;
1260             *out_size = (RK_S32)(ptr - data);
1261             ctx->new_frame = 1;
1262             ctx->frame_header = 0;
1263             return ptr - data;
1264         }
1265         ptr      += len;
1266         size -= len;
1267     }
1268 
1269     *out_size = (RK_S32)(ptr - data);
1270 
1271     return ptr - data;
1272 
1273     av1d_dbg_func("leave ctx %p\n", ctx);
1274 
1275     return 0;
1276 }
1277 
av1d_get_frame_stream(Av1CodecContext * ctx,RK_U8 * buf,RK_S32 length)1278 MPP_RET av1d_get_frame_stream(Av1CodecContext *ctx, RK_U8 *buf, RK_S32 length)
1279 {
1280     MPP_RET ret = MPP_OK;
1281     av1d_dbg_func("enter ctx %p\n", ctx);
1282     RK_S32 buff_size = 0;
1283     RK_U8 *data = NULL;
1284     RK_S32 size = 0;
1285     RK_S32 offset = ctx->stream_offset;
1286 
1287     data = (RK_U8 *)mpp_packet_get_data(ctx->pkt);
1288     size = (RK_S32)mpp_packet_get_size(ctx->pkt);
1289 
1290     if ((length + offset) > size) {
1291         mpp_packet_deinit(&ctx->pkt);
1292         buff_size = length + offset + 10 * 1024;
1293         data = mpp_realloc(data, RK_U8, buff_size);
1294         mpp_packet_init(&ctx->pkt, (void *)data, buff_size);
1295         mpp_packet_set_size(ctx->pkt, buff_size);
1296         ctx->stream_size = buff_size;
1297     }
1298 
1299     memcpy(data + offset, buf, length);
1300     ctx->stream_offset += length;
1301     mpp_packet_set_length(ctx->pkt, ctx->stream_offset);
1302 
1303     av1d_dbg_func("leave ctx %p\n", ctx);
1304     return ret;
1305 
1306 }
1307 
av1d_split_deinit(Av1CodecContext * ctx)1308 MPP_RET av1d_split_deinit(Av1CodecContext *ctx)
1309 {
1310     MPP_RET ret = MPP_OK;
1311     (void)ctx;
1312 
1313     av1d_dbg_func("enter ctx %p\n", ctx);
1314 
1315     av1d_dbg_func("leave ctx %p\n", ctx);
1316 
1317     return ret;
1318 }
1319 
av1d_split_init(Av1CodecContext * ctx)1320 MPP_RET av1d_split_init(Av1CodecContext *ctx)
1321 {
1322     MPP_RET ret = MPP_OK;
1323     (void)ctx;
1324 
1325     av1d_dbg_func("enter ctx %p\n", ctx);
1326 
1327     av1d_dbg_func("leave ctx %p\n", ctx);
1328     return ret;
1329 }
1330