Coverage Report

Created: 2026-08-13 07:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/work/svt-av1/Source/Lib/Codec/packetization_process.c
Line
Count
Source
1
/*
2
* Copyright(c) 2019 Intel Corporation
3
*
4
* This source code is subject to the terms of the BSD 2 Clause License and
5
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6
* was not distributed with this source code in the LICENSE file, you can
7
* obtain it at https://www.aomedia.org/license/software-license. If the Alliance for Open
8
* Media Patent License 1.0 was not distributed with this source code in the
9
* PATENTS file, you can obtain it at https://www.aomedia.org/license/patent-license.
10
*/
11
#include <stdlib.h>
12
13
#include "enc_handle.h"
14
#include "packetization_process.h"
15
#include "ec_results.h"
16
#include "sequence_control_set.h"
17
#include "pcs.h"
18
#include "entropy_coding.h"
19
#include "rc_tasks.h"
20
#include "svt_time.h"
21
#include "md_process.h"
22
#include "pic_demux_results.h"
23
#include "svt_log.h"
24
#include "EbSvtAv1ErrorCodes.h"
25
#include "pd_results.h"
26
#include "restoration.h" // RDCOST_DBL
27
#include "rc_process.h"
28
#include "enc_mode_config.h"
29
30
0
#define RDCOST_DBL_WITH_NATIVE_BD_DIST(RM, R, D, BD) RDCOST_DBL((RM), (R), (double)((D) >> (2 * (BD - 8))))
31
32
/**************************************
33
 * Context
34
 **************************************/
35
typedef struct PacketizationContext {
36
    EbDctor dctor;
37
    EbFifo* entropy_coding_input_fifo_ptr;
38
    EbFifo* rate_control_tasks_output_fifo_ptr;
39
    EbFifo* picture_decision_results_output_fifo_ptr; // to motion estimation process
40
    EbFifo* picture_demux_fifo_ptr; // to picture manager process
41
#if DETAILED_FRAME_OUTPUT
42
    uint64_t dpb_disp_order[8], dpb_dec_order[8];
43
#endif
44
    uint64_t tot_shown_frames;
45
    uint64_t disp_order_continuity_count;
46
} PacketizationContext;
47
48
void        free_temporal_filtering_buffer(PictureControlSet* pcs);
49
void        svt_aom_recon_output(PictureControlSet* pcs, SequenceControlSet* scs);
50
void        svt_aom_init_resize_picture(SequenceControlSet* scs, PictureParentControlSet* pcs);
51
void        pad_ref_and_set_flags(PictureControlSet* pcs, SequenceControlSet* scs);
52
void        svt_aom_update_rc_counts(PictureParentControlSet* ppcs);
53
EbErrorType svt_aom_ssim_calculations(PictureControlSet* pcs, SequenceControlSet* scs, bool free_memory);
54
55
485
static void packetization_context_dctor(EbPtr p) {
56
485
    EbThreadContext*      thread_ctx = (EbThreadContext*)p;
57
485
    PacketizationContext* obj        = (PacketizationContext*)thread_ctx->priv;
58
485
    EB_FREE_ARRAY(obj);
59
485
}
60
61
EbErrorType svt_aom_packetization_context_ctor(EbThreadContext* thread_ctx, const EbEncHandle* enc_handle_ptr,
62
485
                                               int rate_control_index, int demux_index, int me_port_index) {
63
485
    PacketizationContext* context_ptr;
64
485
    EB_CALLOC_ARRAY(context_ptr, 1);
65
485
    thread_ctx->priv  = context_ptr;
66
485
    thread_ctx->dctor = packetization_context_dctor;
67
68
485
    context_ptr->dctor                         = packetization_context_dctor;
69
485
    context_ptr->entropy_coding_input_fifo_ptr = svt_system_resource_get_consumer_fifo(
70
485
        enc_handle_ptr->entropy_coding_results_resource_ptr, 0);
71
485
    context_ptr->rate_control_tasks_output_fifo_ptr = svt_system_resource_get_producer_fifo(
72
485
        enc_handle_ptr->rate_control_tasks_resource_ptr, rate_control_index);
73
485
    context_ptr->picture_demux_fifo_ptr = svt_system_resource_get_producer_fifo(
74
485
        enc_handle_ptr->picture_demux_results_resource_ptr, demux_index);
75
485
    context_ptr->picture_decision_results_output_fifo_ptr = svt_system_resource_get_producer_fifo(
76
485
        enc_handle_ptr->picture_decision_results_resource_ptr, me_port_index);
77
78
485
    return EB_ErrorNone;
79
485
}
80
81
3.39k
static inline int get_reorder_queue_pos(const EncodeContext* enc_ctx, int delta) {
82
3.39k
    return (enc_ctx->packetization_reorder_queue_head_index + delta) % enc_ctx->packetization_reorder_queue_size;
83
3.39k
}
84
85
2.91k
static inline PacketizationReorderEntry* get_reorder_queue_entry(const EncodeContext* enc_ctx, int delta) {
86
2.91k
    int pos = get_reorder_queue_pos(enc_ctx, delta);
87
2.91k
    return enc_ctx->packetization_reorder_queue[pos];
88
2.91k
}
89
90
970
static uint32_t count_frames_in_next_tu(const EncodeContext* enc_ctx, uint32_t* data_size) {
91
970
    uint32_t i = 0;
92
970
    *data_size = 0;
93
970
    do {
94
970
        const PacketizationReorderEntry* queue_entry_ptr = get_reorder_queue_entry(enc_ctx, i);
95
970
        const EbObjectWrapper*           wrapper         = queue_entry_ptr->output_stream_wrapper_ptr;
96
        // not a completed td
97
970
        if (!wrapper) {
98
485
            return 0;
99
485
        }
100
101
485
        const EbBufferHeaderType* output_stream_ptr = (EbBufferHeaderType*)wrapper->object_ptr;
102
485
        *data_size += output_stream_ptr->n_filled_len;
103
104
485
        i++;
105
        //we have a td when we got a displable frame
106
485
        if (queue_entry_ptr->show_frame) {
107
485
            break;
108
485
        }
109
0
        if (output_stream_ptr->flags & EB_BUFFERFLAG_EOS) {
110
0
            break;
111
0
        }
112
113
0
    } while (i < enc_ctx->packetization_reorder_queue_size);
114
485
    return i;
115
970
}
116
117
0
static int pts_descend(const void* pa, const void* pb) {
118
0
    EbObjectWrapper*    a  = *(EbObjectWrapper**)pa;
119
0
    EbObjectWrapper*    b  = *(EbObjectWrapper**)pb;
120
0
    EbBufferHeaderType* ba = (EbBufferHeaderType*)(a->object_ptr);
121
0
    EbBufferHeaderType* bb = (EbBufferHeaderType*)(b->object_ptr);
122
0
    return (int)(bb->pts - ba->pts);
123
0
}
124
125
0
static void push_undisplayed_frame(EncodeContext* enc_ctx, EbObjectWrapper* wrapper) {
126
0
    if (enc_ctx->picture_decision_undisplayed_queue_count >= UNDISP_QUEUE_SIZE) {
127
0
        SVT_ERROR("bug, too many frames in undisplayed queue");
128
        // drop it as the alt ref path does, rather than leak the buffer. leaking drains the output
129
        // pool and stalls packetization for good, which hides the bug being reported here
130
0
        EB_FREE(((EbBufferHeaderType*)wrapper->object_ptr)->p_buffer);
131
0
        svt_release_object(wrapper);
132
0
        return;
133
0
    }
134
0
    uint32_t count                                       = enc_ctx->picture_decision_undisplayed_queue_count;
135
0
    enc_ctx->picture_decision_undisplayed_queue[count++] = wrapper;
136
0
    enc_ctx->picture_decision_undisplayed_queue_count    = count;
137
0
}
138
139
0
static EbObjectWrapper* pop_undisplayed_frame(EncodeContext* enc_ctx) {
140
0
    uint32_t count = enc_ctx->picture_decision_undisplayed_queue_count;
141
0
    if (!count) {
142
0
        SVT_ERROR("bug, no frame in undisplayed queue");
143
0
        return NULL;
144
0
    }
145
0
    count--;
146
0
    EbObjectWrapper* ret                              = enc_ctx->picture_decision_undisplayed_queue[count];
147
0
    enc_ctx->picture_decision_undisplayed_queue_count = count;
148
0
    return ret;
149
0
}
150
151
0
static void sort_undisplayed_frame(EncodeContext* enc_ctx) {
152
0
    qsort(&enc_ctx->picture_decision_undisplayed_queue[0],
153
0
          enc_ctx->picture_decision_undisplayed_queue_count,
154
0
          sizeof(EbObjectWrapper*),
155
0
          pts_descend);
156
0
}
157
158
#if DETAILED_FRAME_OUTPUT
159
static void print_detailed_frame_info(PacketizationContext*            context_ptr,
160
                                      const PacketizationReorderEntry* queue_entry_ptr) {
161
    int32_t i;
162
    uint8_t showTab[] = {'H', 'V'};
163
164
    //Countinuity count check of visible frames
165
    if (queue_entry_ptr->show_frame) {
166
        if (context_ptr->disp_order_continuity_count == queue_entry_ptr->poc) {
167
            context_ptr->disp_order_continuity_count++;
168
        } else {
169
            SVT_ERROR("disp_order_continuity_count Error1 POC:%i\n", (int32_t)queue_entry_ptr->poc);
170
            exit(0);
171
        }
172
    }
173
174
    if (queue_entry_ptr->has_show_existing) {
175
        if (context_ptr->disp_order_continuity_count ==
176
            context_ptr->dpb_disp_order[queue_entry_ptr->show_existing_frame]) {
177
            context_ptr->disp_order_continuity_count++;
178
        } else {
179
            SVT_ERROR("disp_order_continuity_count Error2 POC:%i\n", (int32_t)queue_entry_ptr->poc);
180
            exit(0);
181
        }
182
    }
183
184
    //update total number of shown frames
185
    if (queue_entry_ptr->show_frame) {
186
        context_ptr->tot_shown_frames++;
187
    }
188
    if (queue_entry_ptr->has_show_existing) {
189
        context_ptr->tot_shown_frames++;
190
    }
191
192
    //implement the GOP here - Serial dec order
193
    if (queue_entry_ptr->frame_type == KEY_FRAME) {
194
        //reset the DPB on a Key frame
195
        for (i = 0; i < 8; i++) {
196
            context_ptr->dpb_dec_order[i]  = queue_entry_ptr->picture_number;
197
            context_ptr->dpb_disp_order[i] = queue_entry_ptr->poc;
198
        }
199
        SVT_LOG("%i  %i  %c ****KEY***** %i frames\n",
200
                (int32_t)queue_entry_ptr->picture_number,
201
                (int32_t)queue_entry_ptr->poc,
202
                showTab[queue_entry_ptr->show_frame],
203
                (int32_t)context_ptr->tot_shown_frames);
204
    } else {
205
        int32_t LASTrefIdx = queue_entry_ptr->av1_ref_signal.ref_dpb_index[0];
206
        int32_t BWDrefIdx  = queue_entry_ptr->av1_ref_signal.ref_dpb_index[4];
207
208
        if (queue_entry_ptr->frame_type == INTER_FRAME) {
209
            if (queue_entry_ptr->has_show_existing) {
210
                SVT_LOG("%i (%i  %i)    %i  (%i  %i)   %c  showEx: %i   %i frames\n",
211
                        (int32_t)queue_entry_ptr->picture_number,
212
                        (int32_t)context_ptr->dpb_dec_order[LASTrefIdx],
213
                        (int32_t)context_ptr->dpb_dec_order[BWDrefIdx],
214
                        (int32_t)queue_entry_ptr->poc,
215
                        (int32_t)context_ptr->dpb_disp_order[LASTrefIdx],
216
                        (int32_t)context_ptr->dpb_disp_order[BWDrefIdx],
217
                        showTab[queue_entry_ptr->show_frame],
218
                        (int32_t)context_ptr->dpb_disp_order[queue_entry_ptr->show_existing_frame],
219
                        (int32_t)context_ptr->tot_shown_frames);
220
            } else {
221
                SVT_LOG("%i (%i  %i)    %i  (%i  %i)   %c  %i frames\n",
222
                        (int32_t)queue_entry_ptr->picture_number,
223
                        (int32_t)context_ptr->dpb_dec_order[LASTrefIdx],
224
                        (int32_t)context_ptr->dpb_dec_order[BWDrefIdx],
225
                        (int32_t)queue_entry_ptr->poc,
226
                        (int32_t)context_ptr->dpb_disp_order[LASTrefIdx],
227
                        (int32_t)context_ptr->dpb_disp_order[BWDrefIdx],
228
                        showTab[queue_entry_ptr->show_frame],
229
                        (int32_t)context_ptr->tot_shown_frames);
230
            }
231
232
            if (queue_entry_ptr->ref_poc_list0 != context_ptr->dpb_disp_order[LASTrefIdx]) {
233
                SVT_LOG("L0 MISMATCH POC:%i\n", (int32_t)queue_entry_ptr->poc);
234
                exit(0);
235
            }
236
237
            for (int rr = 0; rr < 7; rr++) {
238
                uint8_t dpb_spot = queue_entry_ptr->av1_ref_signal.ref_dpb_index[rr];
239
240
                if (queue_entry_ptr->ref_poc_array[rr] != context_ptr->dpb_disp_order[dpb_spot]) {
241
                    SVT_LOG("REF_POC MISMATCH POC:%i  ref:%i\n", (int32_t)queue_entry_ptr->poc, rr);
242
                }
243
            }
244
        } else {
245
            if (queue_entry_ptr->has_show_existing) {
246
                SVT_LOG("%i  %i  %c   showEx: %i ----INTRA---- %i frames \n",
247
                        (int32_t)queue_entry_ptr->picture_number,
248
                        (int32_t)queue_entry_ptr->poc,
249
                        showTab[queue_entry_ptr->show_frame],
250
                        (int32_t)context_ptr->dpb_disp_order[queue_entry_ptr->show_existing_frame],
251
                        (int32_t)context_ptr->tot_shown_frames);
252
            } else {
253
                SVT_LOG("%i  %i  %c   ----INTRA---- %i frames\n",
254
                        (int32_t)queue_entry_ptr->picture_number,
255
                        (int32_t)queue_entry_ptr->poc,
256
                        (int32_t)showTab[queue_entry_ptr->show_frame],
257
                        (int32_t)context_ptr->tot_shown_frames);
258
            }
259
        }
260
261
        //Update the DPB
262
        for (i = 0; i < 8; i++) {
263
            if ((queue_entry_ptr->av1_ref_signal.refresh_frame_mask >> i) & 1) {
264
                context_ptr->dpb_dec_order[i]  = queue_entry_ptr->picture_number;
265
                context_ptr->dpb_disp_order[i] = queue_entry_ptr->poc;
266
            }
267
        }
268
    }
269
}
270
#endif
271
272
485
static void collect_frames_info(PacketizationContext* context_ptr, const EncodeContext* enc_ctx, int frames) {
273
970
    for (int i = 0; i < frames; i++) {
274
485
        PacketizationReorderEntry* queue_entry_ptr   = get_reorder_queue_entry(enc_ctx, i);
275
485
        EbBufferHeaderType*        output_stream_ptr = (EbBufferHeaderType*)
276
485
                                                    queue_entry_ptr->output_stream_wrapper_ptr->object_ptr;
277
#if DETAILED_FRAME_OUTPUT
278
        print_detailed_frame_info(context_ptr, queue_entry_ptr);
279
#else
280
485
        (void)context_ptr;
281
282
485
#endif
283
        // Calculate frame latency in milliseconds
284
485
        uint64_t finish_time_seconds   = 0;
285
485
        uint64_t finish_time_u_seconds = 0;
286
485
        svt_av1_get_time(&finish_time_seconds, &finish_time_u_seconds);
287
288
485
        output_stream_ptr->n_tick_count = (uint32_t)svt_av1_compute_overall_elapsed_time_ms(
289
485
            queue_entry_ptr->start_time_seconds,
290
485
            queue_entry_ptr->start_time_u_seconds,
291
485
            finish_time_seconds,
292
485
            finish_time_u_seconds);
293
485
        output_stream_ptr->p_app_private = (EbBufferHeaderType*)NULL;
294
485
        if (queue_entry_ptr->is_alt_ref) {
295
0
            output_stream_ptr->flags |= (uint32_t)EB_BUFFERFLAG_IS_ALT_REF;
296
0
        }
297
485
    }
298
485
}
299
300
1.45k
#define TD_SIZE 2
301
302
// a tu start with a td, + 0 more not displable frame, + 1 display frame
303
static EbErrorType encode_tu(EncodeContext* enc_ctx, int frames, uint32_t total_bytes,
304
485
                             EbBufferHeaderType* output_stream_ptr) {
305
485
    total_bytes += TD_SIZE;
306
485
    if (total_bytes > output_stream_ptr->n_alloc_len) {
307
0
        uint8_t* pbuff;
308
0
        EB_MALLOC(pbuff, total_bytes);
309
0
        if (!pbuff) {
310
0
            SVT_ERROR("failed to allocate more memory in encode_tu");
311
0
            return EB_ErrorInsufficientResources;
312
0
        }
313
0
        svt_memcpy(pbuff,
314
0
                   output_stream_ptr->p_buffer,
315
0
                   output_stream_ptr->n_alloc_len > total_bytes ? total_bytes : output_stream_ptr->n_alloc_len);
316
0
        EB_FREE(output_stream_ptr->p_buffer);
317
0
        output_stream_ptr->p_buffer    = pbuff;
318
0
        output_stream_ptr->n_alloc_len = total_bytes;
319
0
    }
320
485
    uint8_t* dst = output_stream_ptr->p_buffer + total_bytes;
321
    // we use last frame's output_stream_ptr to hold entire tu, so we need copy backward.
322
970
    for (int i = frames - 1; i >= 0; i--) {
323
485
        PacketizationReorderEntry* queue_entry_ptr = get_reorder_queue_entry(enc_ctx, i);
324
485
        EbObjectWrapper*           wrapper         = queue_entry_ptr->output_stream_wrapper_ptr;
325
485
        EbBufferHeaderType*        src_stream_ptr  = (EbBufferHeaderType*)wrapper->object_ptr;
326
485
        uint32_t                   size            = src_stream_ptr->n_filled_len;
327
485
        dst -= size;
328
485
        memmove(dst, src_stream_ptr->p_buffer, size);
329
        // 1. The last frame is a displayable frame, others are undisplayed.
330
        // 2. We do not push alt ref frame since the overlay frame will carry the pts.
331
        // 3. Release alt ref stream buffer here for it will not be sent out
332
485
        if (i != frames - 1 && !queue_entry_ptr->is_alt_ref) {
333
0
            push_undisplayed_frame(enc_ctx, wrapper);
334
485
        } else if (queue_entry_ptr->is_alt_ref) {
335
0
            EB_FREE(src_stream_ptr->p_buffer);
336
0
            svt_release_object(wrapper);
337
0
        }
338
485
    }
339
485
    if (frames > 1) {
340
0
        sort_undisplayed_frame(enc_ctx);
341
0
    }
342
485
    dst -= TD_SIZE;
343
485
    svt_aom_encode_td_av1(dst);
344
485
    output_stream_ptr->n_filled_len = total_bytes;
345
485
    output_stream_ptr->flags |= EB_BUFFERFLAG_HAS_TD;
346
485
    return EB_ErrorNone;
347
485
}
348
349
static EbErrorType copy_data_from_bitstream(EncodeContext* enc_ctx, Bitstream* bitstream_ptr,
350
485
                                            EbBufferHeaderType* output_stream_ptr) {
351
485
    EbErrorType return_error = EB_ErrorNone;
352
485
    int         size         = svt_aom_bitstream_get_bytes_count(bitstream_ptr);
353
354
485
    CHECK_REPORT_ERROR((size + output_stream_ptr->n_filled_len < output_stream_ptr->n_alloc_len),
355
485
                       enc_ctx->app_callback_ptr,
356
485
                       EB_ENC_EC_ERROR2);
357
358
485
    void* dest = output_stream_ptr->p_buffer + output_stream_ptr->n_filled_len;
359
485
    svt_aom_bitstream_copy(bitstream_ptr, dest, size);
360
485
    output_stream_ptr->n_filled_len += size;
361
362
485
    return return_error;
363
485
}
364
365
static void encode_show_existing(EncodeContext* enc_ctx, PacketizationReorderEntry* queue_entry_ptr,
366
0
                                 EbBufferHeaderType* output_stream_ptr) {
367
0
    uint8_t* dst = output_stream_ptr->p_buffer;
368
369
0
    svt_aom_encode_td_av1(dst);
370
0
    output_stream_ptr->n_filled_len = TD_SIZE;
371
372
0
    copy_data_from_bitstream(enc_ctx, queue_entry_ptr->bitstream_ptr, output_stream_ptr);
373
374
0
    output_stream_ptr->flags |= (EB_BUFFERFLAG_SHOW_EXT | EB_BUFFERFLAG_HAS_TD);
375
0
}
376
377
485
static void release_frames(EncodeContext* enc_ctx, int frames) {
378
970
    for (int i = 0; i < frames; i++) {
379
485
        PacketizationReorderEntry* queue_entry_ptr = get_reorder_queue_entry(enc_ctx, i);
380
        // Reset the Reorder Queue Entry
381
485
        queue_entry_ptr->picture_number += enc_ctx->packetization_reorder_queue_size;
382
485
        queue_entry_ptr->output_stream_wrapper_ptr = (EbObjectWrapper*)NULL;
383
        // return the ppcs now the slot is free, instead of when rate control consumed the feedback
384
485
        if (queue_entry_ptr->ppcs_wrapper) {
385
485
            svt_release_object(queue_entry_ptr->ppcs_wrapper);
386
485
            queue_entry_ptr->ppcs_wrapper = NULL;
387
485
        }
388
485
    }
389
485
    enc_ctx->packetization_reorder_queue_head_index = get_reorder_queue_pos(enc_ctx, frames);
390
485
}
391
392
// Release the pd_dpb and ref_pic_list at the end of the sequence
393
485
void release_references_eos(SequenceControlSet* scs) {
394
485
    EncodeContext* enc_ctx = scs->enc_ctx;
395
    // At the end of the sequence release all the refs (needed for MacOS CI tests)
396
485
    svt_block_on_mutex(enc_ctx->pd_dpb_mutex);
397
4.36k
    for (uint8_t i = 0; i < REF_FRAMES; i++) {
398
        // Get the current entry at that spot in the DPB
399
3.88k
        PaReferenceEntry* input_entry = enc_ctx->pd_dpb[i];
400
401
        // If DPB entry is occupied, release the current entry
402
3.88k
        if (input_entry->is_valid) {
403
            // Release the entry at that DPB spot
404
            // Release the nominal live_count value
405
3.88k
            svt_release_object(input_entry->input_object_ptr);
406
407
3.88k
            if (input_entry->y8b_wrapper) {
408
                //y8b needs to get decremented at the same time of pa ref
409
3.88k
                svt_release_object(input_entry->y8b_wrapper);
410
3.88k
            }
411
412
3.88k
            input_entry->input_object_ptr = (EbObjectWrapper*)NULL;
413
3.88k
            input_entry->is_valid         = false;
414
3.88k
        }
415
3.88k
    }
416
485
    svt_release_mutex(enc_ctx->pd_dpb_mutex);
417
418
485
    svt_block_on_mutex(enc_ctx->ref_pic_list_mutex);
419
485
    ReferenceQueueEntry* ref_entry = NULL;
420
1.45k
    for (uint32_t i = 0; i < enc_ctx->ref_pic_list_length; i++) {
421
970
        ref_entry = enc_ctx->ref_pic_list[i];
422
970
        if (ref_entry->is_valid && ref_entry->reference_object_ptr) {
423
            // Remove the entry & release the reference if there are no remaining references
424
            // Release the nominal live_count value
425
0
            svt_release_object(ref_entry->reference_object_ptr);
426
0
            ref_entry->reference_object_ptr  = (EbObjectWrapper*)NULL;
427
0
            ref_entry->reference_available   = false;
428
0
            ref_entry->is_ref                = false;
429
0
            ref_entry->is_valid              = false;
430
0
            ref_entry->frame_context_updated = false;
431
0
            ref_entry->feedback_arrived      = false;
432
0
            if (scs->ref_buffer_available_semaphore) {
433
0
                svt_post_semaphore(scs->ref_buffer_available_semaphore);
434
0
            }
435
0
        }
436
970
    }
437
485
    svt_release_mutex(enc_ctx->ref_pic_list_mutex);
438
485
}
439
440
0
inline static void clear_eos_flag(EbBufferHeaderType* output_stream_ptr) {
441
0
    output_stream_ptr->flags &= ~EB_BUFFERFLAG_EOS;
442
0
}
443
444
0
inline static void set_eos_flag(EbBufferHeaderType* output_stream_ptr) {
445
0
    output_stream_ptr->flags |= EB_BUFFERFLAG_EOS;
446
0
}
447
448
/* Wrapper function to capture the return of EB_MALLOC */
449
485
static inline EbErrorType malloc_p_buffer(EbBufferHeaderType* output_stream_ptr) {
450
485
    EB_MALLOC(output_stream_ptr->p_buffer, output_stream_ptr->n_alloc_len);
451
485
    return EB_ErrorNone;
452
485
}
453
454
void update_firstpass_stats(PictureParentControlSet* pcs, const int frame_number, const double ts_duration,
455
                            StatStruct* stat_struct);
456
void svt_av1_end_first_pass(PictureParentControlSet* pcs);
457
458
/* Realloc when bitstream pointer size is not enough to write data of size sz */
459
970
EbErrorType svt_aom_packetization_kernel_iter(void* context) {
460
    // Context
461
970
    PacketizationContext* context_ptr = (PacketizationContext*)context;
462
463
    // Input
464
970
    EbObjectWrapper* entropy_coding_results_wrapper_ptr;
465
466
    // Output
467
970
    EbObjectWrapper* rate_control_tasks_wrapper_ptr;
468
970
    EbObjectWrapper* picture_manager_results_wrapper_ptr;
469
470
    // Get EntropyCoding Results
471
970
    EB_GET_FULL_OBJECT(context_ptr->entropy_coding_input_fifo_ptr, &entropy_coding_results_wrapper_ptr);
472
473
485
    EntropyCodingResults* entropy_coding_results_ptr = (EntropyCodingResults*)
474
485
                                                           entropy_coding_results_wrapper_ptr->object_ptr;
475
485
    PictureControlSet*       pcs      = (PictureControlSet*)entropy_coding_results_ptr->pcs_wrapper->object_ptr;
476
485
    SequenceControlSet*      scs      = pcs->scs;
477
485
    EncodeContext*           enc_ctx  = scs->enc_ctx;
478
485
    FrameHeader*             frm_hdr  = &pcs->ppcs->frm_hdr;
479
485
    Av1Common* const         cm       = pcs->ppcs->av1_cm;
480
485
    uint16_t                 tile_cnt = cm->tiles_info.tile_rows * cm->tiles_info.tile_cols;
481
485
    PictureParentControlSet* ppcs     = (PictureParentControlSet*)pcs->ppcs;
482
483
485
    if (ppcs->superres_total_recode_loop > 0 && ppcs->superres_recode_loop < ppcs->superres_total_recode_loop) {
484
        // Reset the Bitstream before writing to it
485
0
        svt_aom_bitstream_reset(pcs->bitstream_ptr);
486
0
        svt_aom_write_frame_header_av1(pcs->bitstream_ptr, scs, pcs, 0);
487
0
        int64_t bits = (int64_t)svt_aom_bitstream_get_bytes_count(pcs->bitstream_ptr) << 3;
488
0
        int64_t rate = bits << 5; // To match scale.
489
0
        svt_aom_bitstream_reset(pcs->bitstream_ptr);
490
0
        int64_t    sse       = ppcs->luma_sse;
491
0
        EbBitDepth bit_depth = SVT_EFFECTIVE_HBD_MD(pcs->hbd_md) ? EB_TEN_BIT : EB_EIGHT_BIT;
492
0
        uint8_t    qindex    = ppcs->frm_hdr.quantization_params.base_q_idx;
493
0
        int32_t    rdmult    = svt_aom_compute_rd_mult(pcs, qindex, qindex, bit_depth);
494
495
0
        double rdcost = RDCOST_DBL_WITH_NATIVE_BD_DIST(rdmult, rate, sse, scs->static_config.encoder_bit_depth);
496
497
#if DEBUG_SUPERRES_RECODE
498
        printf(
499
            "\n####### %s - frame %d, loop %d/%d, denom %d, rate %I64d, sse %I64d, rdcost "
500
            "%.2f, qindex %d, rdmult %d\n",
501
            __FUNCTION__,
502
            (int)ppcs->picture_number,
503
            ppcs->superres_recode_loop,
504
            ppcs->superres_total_recode_loop,
505
            ppcs->superres_denom,
506
            rate,
507
            sse,
508
            rdcost,
509
            qindex,
510
            rdmult);
511
#endif
512
513
0
        assert(ppcs->superres_total_recode_loop <= SCALE_NUMERATOR + 1);
514
0
        ppcs->superres_rdcost[ppcs->superres_recode_loop] = rdcost;
515
0
        ++ppcs->superres_recode_loop;
516
517
0
        if (ppcs->superres_recode_loop <= ppcs->superres_total_recode_loop) {
518
0
            bool do_recode = false;
519
0
            if (ppcs->superres_recode_loop == ppcs->superres_total_recode_loop) {
520
                // compare rdcosts to determine whether need to recode again
521
                // rdcost is the smaller the better
522
0
                int best_index = 0;
523
0
                for (int i = 1; i < ppcs->superres_total_recode_loop; ++i) {
524
0
                    double rdcost1 = ppcs->superres_rdcost[best_index];
525
0
                    double rdcost2 = ppcs->superres_rdcost[i];
526
0
                    if (rdcost2 < rdcost1) {
527
0
                        best_index = i;
528
0
                    }
529
0
                }
530
531
0
                if (best_index != ppcs->superres_total_recode_loop - 1) {
532
0
                    do_recode            = true;
533
0
                    ppcs->superres_denom = ppcs->superres_denom_array[best_index];
534
#if DEBUG_SUPERRES_RECODE
535
                    printf("\n####### %s - frame %d, extra loop, pick denom %d\n",
536
                           __FUNCTION__,
537
                           (int)ppcs->picture_number,
538
                           ppcs->superres_denom);
539
#endif
540
0
                }
541
0
            } else {
542
0
                do_recode = true;
543
0
            }
544
545
0
            if (do_recode) {
546
0
                svt_aom_init_resize_picture(scs, ppcs);
547
548
                // reset gm based on super-res on/off
549
0
                bool super_res_off = ppcs->frame_superres_enabled == false &&
550
0
                    scs->static_config.resize_mode == RESIZE_NONE;
551
0
                svt_aom_set_gm_controls(ppcs, svt_aom_derive_gm_level(ppcs, super_res_off));
552
                // Initialize Segments as picture decision process
553
0
                ppcs->me_segments_completion_count = 0;
554
0
                ppcs->me_processed_b64_count       = 0;
555
556
0
                if (ppcs->ref_pic_wrapper != NULL) {
557
                    // update mi_rows and mi_cols for the reference pic wrapper (used in mfmv
558
                    // for other pictures)
559
0
                    EbReferenceObject* ref_object = ppcs->ref_pic_wrapper->object_ptr;
560
0
                    svt_reference_object_reset(ref_object, scs);
561
0
                }
562
#if DEBUG_SUPERRES_RECODE
563
                printf("\n%s - send superres recode task to open loop ME. Frame %d, denom %d\n",
564
                       __FUNCTION__,
565
                       (int)ppcs->picture_number,
566
                       ppcs->superres_denom);
567
#endif
568
569
0
                for (uint32_t segment_index = 0; segment_index < ppcs->me_segments_total_count; ++segment_index) {
570
                    // Get Empty Results Object
571
0
                    EbObjectWrapper* out_results_wrapper;
572
0
                    svt_get_empty_object(context_ptr->picture_decision_results_output_fifo_ptr, &out_results_wrapper);
573
574
0
                    PictureDecisionResults* out_results = (PictureDecisionResults*)out_results_wrapper->object_ptr;
575
0
                    out_results->pcs_wrapper            = ppcs->p_pcs_wrapper_ptr;
576
0
                    out_results->segment_index          = segment_index;
577
0
                    out_results->task_type              = TASK_SUPERRES_RE_ME;
578
                    // Post the Full Results Object
579
0
                    svt_post_full_object(out_results_wrapper);
580
0
                }
581
582
                // Release the Entropy Coding Result
583
0
                svt_release_object(entropy_coding_results_wrapper_ptr);
584
0
                return EB_ErrorNone;
585
0
            }
586
0
        }
587
0
    }
588
589
485
    if (ppcs->superres_total_recode_loop > 0) {
590
        // Release pa_ref_objs
591
        // Delayed call from Initial Rate Control process / Source Based Operations process
592
0
        if (ppcs->tpl_ctrls.enable) {
593
0
            if (ppcs->temporal_layer_index == 0) {
594
0
                for (uint32_t i = 0; i < ppcs->tpl_group_size; i++) {
595
0
                    if (svt_aom_is_incomp_mg_frame(ppcs->tpl_group[i])) {
596
0
                        if (ppcs->tpl_group[i]->ext_mg_id == ppcs->ext_mg_id + 1) {
597
0
                            svt_aom_release_pa_reference_objects(scs, ppcs->tpl_group[i]);
598
0
                        }
599
0
                    } else {
600
0
                        if (ppcs->tpl_group[i]->ext_mg_id == ppcs->ext_mg_id) {
601
0
                            svt_aom_release_pa_reference_objects(scs, ppcs->tpl_group[i]);
602
0
                        }
603
0
                    }
604
0
                }
605
0
            }
606
0
        } else {
607
0
            svt_aom_release_pa_reference_objects(scs, ppcs);
608
0
        }
609
610
        // Delayed call from Rate Control process for multiple coding loop frames
611
0
        if (scs->static_config.rate_control_mode) {
612
0
            svt_aom_update_rc_counts(ppcs);
613
0
        }
614
615
        // Release pa me ptr. For non-superres-recode, it's released in svt_aom_mode_decision_kernel
616
0
        assert(pcs->ppcs->me_data_wrapper != NULL);
617
0
        assert(pcs->ppcs->pa_me_data != NULL);
618
0
        svt_release_object(pcs->ppcs->me_data_wrapper);
619
0
        pcs->ppcs->me_data_wrapper = NULL;
620
0
        pcs->ppcs->pa_me_data      = NULL;
621
622
        // Delayed call from Rest process
623
0
        {
624
0
            if (pcs->ppcs->compute_ssim) {
625
                // memory is freed in the svt_aom_ssim_calculations call
626
0
                svt_aom_ssim_calculations(pcs, scs, true);
627
0
            } else {
628
                // free memory used by psnr_calculations
629
0
                free_temporal_filtering_buffer(pcs);
630
0
            }
631
632
0
            if (scs->static_config.recon_enabled) {
633
0
                svt_aom_recon_output(pcs, scs);
634
0
            }
635
636
0
            if (ppcs->is_ref) {
637
0
                EbObjectWrapper*     picture_demux_results_wrapper_ptr;
638
0
                PictureDemuxResults* picture_demux_results_rtr;
639
640
                // Get Empty PicMgr Results
641
0
                svt_get_empty_object(context_ptr->picture_demux_fifo_ptr, &picture_demux_results_wrapper_ptr);
642
643
0
                picture_demux_results_rtr = (PictureDemuxResults*)picture_demux_results_wrapper_ptr->object_ptr;
644
0
                picture_demux_results_rtr->ref_pic_wrapper = ppcs->ref_pic_wrapper;
645
0
                picture_demux_results_rtr->scs             = ppcs->scs;
646
0
                picture_demux_results_rtr->picture_number  = ppcs->picture_number;
647
0
                picture_demux_results_rtr->picture_type    = EB_PIC_REFERENCE;
648
649
                // Post Reference Picture
650
0
                svt_post_full_object(picture_demux_results_wrapper_ptr);
651
0
            }
652
0
        }
653
654
        // Delayed call from Entropy Coding process
655
0
        {
656
            // Release the reference Pictures from both lists
657
0
            for (REF_FRAME_MINUS1 ref = LAST; ref < ALT + 1; ref++) {
658
0
                const uint8_t list_idx = get_list_idx(ref + 1);
659
0
                const uint8_t ref_idx  = get_ref_frame_idx(ref + 1);
660
0
                if (pcs->ref_pic_ptr_array[list_idx][ref_idx] != NULL) {
661
0
                    svt_release_object(pcs->ref_pic_ptr_array[list_idx][ref_idx]);
662
0
                }
663
0
            }
664
665
            //free palette data
666
0
            if (pcs->tile_tok[0][0]) {
667
0
                EB_FREE_ARRAY(pcs->tile_tok[0][0]);
668
0
            }
669
0
        }
670
485
    } else if (!(pcs->ppcs->compute_psnr || pcs->ppcs->compute_ssim)) {
671
485
        free_temporal_filtering_buffer(pcs);
672
485
    }
673
    //****************************************************
674
    // Input Entropy Results into Reordering Queue
675
    //****************************************************
676
    // get a new entry spot
677
485
    int32_t                    queue_entry_index = pcs->ppcs->decode_order % enc_ctx->packetization_reorder_queue_size;
678
485
    PacketizationReorderEntry* queue_entry_ptr   = enc_ctx->packetization_reorder_queue[queue_entry_index];
679
    // Slot i always holds decode order i modulo the queue size, so a mismatch means the entry
680
    // is still live and is about to be overwritten, losing a whole queue's worth of TUs and
681
    // leaving EOS unreachable. Report it loudly.
682
485
    svt_aom_assert_err(queue_entry_ptr->picture_number == pcs->ppcs->decode_order,
683
485
                       "packetization reorder queue overrun");
684
    // assert_err only logs under NDEBUG, so drop the stale ppcs rather than leaking it
685
485
    if (queue_entry_ptr->ppcs_wrapper) {
686
0
        svt_release_object(queue_entry_ptr->ppcs_wrapper);
687
0
    }
688
    // hold the ppcs until the slot drains, so an undrained entry always accounts for one ppcs.
689
    // also keeps it alive past the rate control post below, which may drop rc's own reference
690
485
    svt_object_inc_live_count(pcs->ppcs_wrapper, 1);
691
485
    queue_entry_ptr->ppcs_wrapper         = pcs->ppcs_wrapper;
692
485
    queue_entry_ptr->start_time_seconds   = pcs->ppcs->start_time_seconds;
693
485
    queue_entry_ptr->start_time_u_seconds = pcs->ppcs->start_time_u_seconds;
694
485
    queue_entry_ptr->is_alt_ref           = pcs->ppcs->is_alt_ref;
695
485
    svt_get_empty_object(scs->enc_ctx->stream_output_fifo_ptr, &pcs->ppcs->output_stream_wrapper_ptr);
696
485
    EbObjectWrapper*    output_stream_wrapper_ptr = pcs->ppcs->output_stream_wrapper_ptr;
697
485
    EbBufferHeaderType* output_stream_ptr         = (EbBufferHeaderType*)output_stream_wrapper_ptr->object_ptr;
698
699
485
    if (frm_hdr->frame_type == KEY_FRAME) {
700
485
        if (scs->static_config.mastering_display.max_luma) {
701
0
            svt_add_metadata(pcs->ppcs->input_ptr,
702
0
                             EB_AV1_METADATA_TYPE_HDR_MDCV,
703
0
                             (const uint8_t*)&scs->static_config.mastering_display,
704
0
                             sizeof(scs->static_config.mastering_display));
705
0
        }
706
485
        if (scs->static_config.content_light_level.max_cll) {
707
0
            svt_add_metadata(pcs->ppcs->input_ptr,
708
0
                             EB_AV1_METADATA_TYPE_HDR_CLL,
709
0
                             (const uint8_t*)&scs->static_config.content_light_level,
710
0
                             sizeof(scs->static_config.content_light_level));
711
0
        }
712
485
    }
713
714
485
    output_stream_ptr->flags        = 0;
715
485
    output_stream_ptr->n_filled_len = 0;
716
485
    output_stream_ptr->pts          = pcs->ppcs->input_ptr->pts;
717
    // we output one temporal unit a time, so dts alwasy equals to pts.
718
485
    output_stream_ptr->dts = output_stream_ptr->pts;
719
485
    if (pcs->ppcs->idr_flag) {
720
485
        output_stream_ptr->pic_type = EB_AV1_KEY_PICTURE;
721
485
    } else if (pcs->slice_type == I_SLICE) {
722
0
        output_stream_ptr->pic_type = EB_AV1_INTRA_ONLY_PICTURE;
723
0
    } else if (pcs->ppcs->is_ref) {
724
0
        output_stream_ptr->pic_type = EB_AV1_INTER_PICTURE;
725
0
    } else {
726
0
        output_stream_ptr->pic_type = EB_AV1_NON_REF_PICTURE;
727
0
    }
728
485
    output_stream_ptr->p_app_private        = pcs->ppcs->input_ptr->p_app_private;
729
485
    output_stream_ptr->temporal_layer_index = pcs->ppcs->temporal_layer_index;
730
485
    output_stream_ptr->qp                   = pcs->ppcs->picture_qp;
731
485
    output_stream_ptr->avg_qp               = pcs->ppcs->avg_qp;
732
485
    if (pcs->ppcs->compute_psnr) {
733
0
        output_stream_ptr->luma_sse = pcs->ppcs->luma_sse;
734
0
        output_stream_ptr->cr_sse   = pcs->ppcs->cr_sse;
735
0
        output_stream_ptr->cb_sse   = pcs->ppcs->cb_sse;
736
485
    } else {
737
485
        output_stream_ptr->luma_sse = 0;
738
485
        output_stream_ptr->cr_sse   = 0;
739
485
        output_stream_ptr->cb_sse   = 0;
740
485
    }
741
485
    if (pcs->ppcs->compute_ssim) {
742
0
        output_stream_ptr->luma_ssim = pcs->ppcs->luma_ssim;
743
0
        output_stream_ptr->cr_ssim   = pcs->ppcs->cr_ssim;
744
0
        output_stream_ptr->cb_ssim   = pcs->ppcs->cb_ssim;
745
485
    } else {
746
485
        output_stream_ptr->luma_ssim = 0;
747
485
        output_stream_ptr->cr_ssim   = 0;
748
485
        output_stream_ptr->cb_ssim   = 0;
749
485
    }
750
751
    // Get Empty Rate Control Input Tasks
752
485
    svt_get_empty_object(context_ptr->rate_control_tasks_output_fifo_ptr, &rate_control_tasks_wrapper_ptr);
753
485
    RateControlTasks* rc_tasks = (RateControlTasks*)rate_control_tasks_wrapper_ptr->object_ptr;
754
485
    rc_tasks->pcs_wrapper      = pcs->ppcs_wrapper;
755
485
    rc_tasks->task_type        = RC_PACKETIZATION_FEEDBACK_RESULT;
756
485
    if (scs->enable_dec_order || (pcs->ppcs->is_ref == true && pcs->ppcs->ref_pic_wrapper)) {
757
0
        if (pcs->ppcs->is_ref == true &&
758
            // Force each frame to update their data so future frames can use it,
759
            // even if the current frame did not use it.  This enables REF frames to
760
            // have the feature off, while NREF frames can have it on.  Used for
761
            // multi-threading.
762
0
            pcs->ppcs->ref_pic_wrapper) {
763
0
            for (uint16_t tile_idx = 0; tile_idx < tile_cnt; tile_idx++) {
764
0
                svt_av1_reset_cdf_symbol_counters(pcs->ec_info[tile_idx]->ec->fc);
765
0
                ((EbReferenceObject*)pcs->ppcs->ref_pic_wrapper->object_ptr)->frame_context =
766
0
                    (*pcs->ec_info[tile_idx]->ec->fc);
767
0
            }
768
0
        }
769
        // Get Empty Results Object
770
0
        svt_get_empty_object(context_ptr->picture_demux_fifo_ptr, &picture_manager_results_wrapper_ptr);
771
772
0
        PictureDemuxResults* picture_manager_results_ptr = (PictureDemuxResults*)
773
0
                                                               picture_manager_results_wrapper_ptr->object_ptr;
774
0
        picture_manager_results_ptr->picture_number = pcs->picture_number;
775
0
        picture_manager_results_ptr->picture_type   = EB_PIC_FEEDBACK;
776
0
        picture_manager_results_ptr->decode_order   = pcs->ppcs->decode_order;
777
0
        picture_manager_results_ptr->scs            = pcs->scs;
778
0
    }
779
    // Reset the Bitstream before writing to it
780
485
    svt_aom_bitstream_reset(pcs->bitstream_ptr);
781
782
485
    size_t metadata_sz = 0;
783
784
    // Code the SPS
785
485
    if (frm_hdr->frame_type == KEY_FRAME) {
786
485
        svt_aom_encode_sps_av1(pcs->bitstream_ptr, scs);
787
        // Add CLL and MDCV meta when frame is keyframe and SPS is written
788
485
        svt_aom_write_metadata_av1(pcs->bitstream_ptr, pcs->ppcs->input_ptr->metadata, EB_AV1_METADATA_TYPE_HDR_CLL);
789
485
        svt_aom_write_metadata_av1(pcs->bitstream_ptr, pcs->ppcs->input_ptr->metadata, EB_AV1_METADATA_TYPE_HDR_MDCV);
790
485
    }
791
792
485
    if (frm_hdr->show_frame) {
793
        // Add HDR10+ dynamic metadata when show frame flag is enabled
794
485
        svt_aom_write_metadata_av1(pcs->bitstream_ptr, pcs->ppcs->input_ptr->metadata, EB_AV1_METADATA_TYPE_ITUT_T35);
795
485
        svt_metadata_array_free(&pcs->ppcs->input_ptr->metadata);
796
485
    } else {
797
        // Copy metadata pointer to the queue entry related to current frame number
798
0
        uint64_t current_picture_number = pcs->picture_number;
799
        // TODO: Shouldn't entry be indexed based on decode order, not picture number
800
0
        PacketizationReorderEntry* temp_entry =
801
0
            enc_ctx->packetization_reorder_queue[current_picture_number % enc_ctx->packetization_reorder_queue_size];
802
0
        temp_entry->metadata           = pcs->ppcs->input_ptr->metadata;
803
0
        pcs->ppcs->input_ptr->metadata = NULL;
804
0
        metadata_sz                    = svt_metadata_size(temp_entry->metadata, EB_AV1_METADATA_TYPE_ITUT_T35);
805
0
    }
806
807
485
    svt_aom_write_frame_header_av1(pcs->bitstream_ptr, scs, pcs, 0);
808
809
485
    output_stream_ptr->n_alloc_len = (uint32_t)(svt_aom_bitstream_get_bytes_count(pcs->bitstream_ptr) + TD_SIZE +
810
485
                                                metadata_sz);
811
485
    malloc_p_buffer(output_stream_ptr);
812
813
485
    assert(output_stream_ptr->p_buffer != NULL && "bit-stream memory allocation failure");
814
815
485
    copy_data_from_bitstream(enc_ctx, pcs->bitstream_ptr, output_stream_ptr);
816
817
485
    if (pcs->ppcs->has_show_existing) {
818
0
        uint64_t next_picture_number = pcs->picture_number + 1;
819
        // TODO: Shouldn't entry be indexed based on decode order, not picture number
820
0
        PacketizationReorderEntry* temp_entry =
821
0
            enc_ctx->packetization_reorder_queue[next_picture_number % enc_ctx->packetization_reorder_queue_size];
822
        // Check if the temporal entry has metadata
823
0
        if (temp_entry->metadata) {
824
            // Get bitstream from queue entry
825
0
            size_t current_metadata_sz = svt_metadata_size(temp_entry->metadata, EB_AV1_METADATA_TYPE_ITUT_T35);
826
0
            if (queue_entry_ptr->bitstream_ptr) {
827
0
                OutputBitstreamUnit* output = queue_entry_ptr->bitstream_ptr->output_bitstream_ptr;
828
                // 16 bytes for frame header
829
0
                svt_realloc_output_bitstream_unit(output, (uint32_t)(current_metadata_sz + 16));
830
0
            }
831
0
        }
832
        // Reset the Bitstream before writing to it
833
0
        svt_aom_bitstream_reset(queue_entry_ptr->bitstream_ptr);
834
0
        svt_aom_write_metadata_av1(queue_entry_ptr->bitstream_ptr, temp_entry->metadata, EB_AV1_METADATA_TYPE_ITUT_T35);
835
0
        svt_aom_write_frame_header_av1(queue_entry_ptr->bitstream_ptr, scs, pcs, 1);
836
0
        svt_metadata_array_free(&temp_entry->metadata);
837
0
    }
838
839
    // Send the number of bytes per frame to RC
840
485
    pcs->ppcs->total_num_bits = (uint64_t)output_stream_ptr->n_filled_len << 3;
841
485
    if (scs->passes == 2 && scs->static_config.pass == ENC_FIRST_PASS) {
842
0
        StatStruct stat_struct;
843
0
        stat_struct.poc = pcs->picture_number;
844
0
        if (scs->first_pass_downsample) {
845
0
            stat_struct.total_num_bits = pcs->ppcs->total_num_bits * DS_SC_FACT / 10;
846
0
        } else {
847
0
            stat_struct.total_num_bits = pcs->ppcs->total_num_bits;
848
0
        }
849
0
        stat_struct.qindex       = frm_hdr->quantization_params.base_q_idx;
850
0
        stat_struct.worst_qindex = quantizer_to_qindex[(uint8_t)scs->static_config.qp];
851
0
        if (svt_aom_is_pic_skipped(pcs->ppcs)) {
852
0
            stat_struct.total_num_bits = 0;
853
0
        }
854
0
        stat_struct.temporal_layer_index = pcs->temporal_layer_index;
855
0
        update_firstpass_stats(pcs->ppcs, (const int)pcs->picture_number, pcs->ppcs->ts_duration, &stat_struct);
856
0
        if (ppcs->end_of_sequence_flag) {
857
0
            svt_av1_end_first_pass(ppcs);
858
0
        }
859
0
    }
860
485
    queue_entry_ptr->total_num_bits = pcs->ppcs->total_num_bits;
861
485
    queue_entry_ptr->frame_type     = frm_hdr->frame_type;
862
485
    queue_entry_ptr->poc            = pcs->picture_number;
863
485
    svt_memcpy(&queue_entry_ptr->av1_ref_signal, &pcs->ppcs->av1_ref_signal, sizeof(Av1RpsNode));
864
865
485
    queue_entry_ptr->slice_type = pcs->slice_type;
866
#if DETAILED_FRAME_OUTPUT
867
    queue_entry_ptr->ref_poc_list0 = pcs->ppcs->ref_pic_poc_array[REF_LIST_0][0];
868
    queue_entry_ptr->ref_poc_list1 = pcs->ppcs->ref_pic_poc_array[REF_LIST_1][0];
869
    svt_memcpy(queue_entry_ptr->ref_poc_array, pcs->ppcs->av1_ref_signal.ref_poc_array, 7 * sizeof(uint64_t));
870
#endif
871
485
    queue_entry_ptr->show_frame          = frm_hdr->show_frame;
872
485
    queue_entry_ptr->has_show_existing   = pcs->ppcs->has_show_existing;
873
485
    queue_entry_ptr->show_existing_frame = frm_hdr->show_existing_frame;
874
875
    //Store the output buffer in the Queue
876
485
    queue_entry_ptr->output_stream_wrapper_ptr = output_stream_wrapper_ptr;
877
878
    // Note: last chance here to add more output meta data for an encoded picture -->
879
880
485
    if (scs->speed_control_flag) {
881
        // update speed control variables
882
0
        svt_block_on_mutex(enc_ctx->sc_buffer_mutex);
883
0
        enc_ctx->sc_frame_out++;
884
0
        svt_release_mutex(enc_ctx->sc_buffer_mutex);
885
0
    }
886
887
485
    if (scs->enable_dec_order || (pcs->ppcs->is_ref == true && pcs->ppcs->ref_pic_wrapper)) {
888
        // Post the Full Results Object
889
0
        svt_post_full_object(picture_manager_results_wrapper_ptr);
890
0
    }
891
    // Post Rate Control Task. Be done after postig to PM as RC might release ppcs
892
485
    svt_post_full_object(rate_control_tasks_wrapper_ptr);
893
485
    if (pcs->ppcs->frm_hdr.allow_intrabc) {
894
0
        svt_av1_hash_table_destroy(&pcs->hash_table);
895
0
    }
896
485
    svt_release_object(pcs->ppcs->enc_dec_ptr->enc_dec_wrapper); // Child
897
    // Release the Parent PCS then the Child PCS
898
485
    assert(entropy_coding_results_ptr->pcs_wrapper->live_count == 1);
899
485
    svt_release_object(entropy_coding_results_ptr->pcs_wrapper); // Child
900
    // Release the Entropy Coding Result
901
485
    svt_release_object(entropy_coding_results_wrapper_ptr);
902
903
    //****************************************************
904
    // Process the head of the queue
905
    //****************************************************
906
    // Look at head of queue and see if we got a td
907
485
    uint32_t frames, total_bytes;
908
485
    svt_block_on_mutex(enc_ctx->total_number_of_shown_frames_mutex);
909
485
    bool eos = false;
910
970
    while ((frames = count_frames_in_next_tu(enc_ctx, &total_bytes))) {
911
485
        collect_frames_info(context_ptr, enc_ctx, frames);
912
        // last frame in a termporal unit is a displable frame. only the last frame has pts.
913
        // so we collect all bitstream to last frames' output buffer.
914
485
        queue_entry_ptr           = get_reorder_queue_entry(enc_ctx, frames - 1);
915
485
        output_stream_wrapper_ptr = queue_entry_ptr->output_stream_wrapper_ptr;
916
485
        output_stream_ptr         = (EbBufferHeaderType*)output_stream_wrapper_ptr->object_ptr;
917
485
        eos                       = output_stream_ptr->flags & EB_BUFFERFLAG_EOS;
918
485
        encode_tu(enc_ctx, frames, total_bytes, output_stream_ptr);
919
920
485
        if (eos && queue_entry_ptr->has_show_existing) {
921
0
            clear_eos_flag(output_stream_ptr);
922
0
        }
923
924
485
        svt_post_full_object(output_stream_wrapper_ptr);
925
485
        if (queue_entry_ptr->has_show_existing) {
926
0
            EbObjectWrapper* existed = pop_undisplayed_frame(enc_ctx);
927
0
            if (existed) {
928
0
                EbBufferHeaderType* existed_output_stream_ptr = (EbBufferHeaderType*)existed->object_ptr;
929
0
                encode_show_existing(enc_ctx, queue_entry_ptr, existed_output_stream_ptr);
930
0
                if (eos) {
931
0
                    set_eos_flag(existed_output_stream_ptr);
932
0
                }
933
0
                svt_post_full_object(existed);
934
0
            }
935
0
        }
936
937
485
        if (queue_entry_ptr->show_frame) {
938
485
            enc_ctx->total_number_of_shown_frames++;
939
485
        }
940
485
        if (queue_entry_ptr->has_show_existing) {
941
0
            enc_ctx->total_number_of_shown_frames++;
942
0
        }
943
485
        eos = (enc_ctx->total_number_of_shown_frames == enc_ctx->terminating_picture_number + 1) ? 1 : 0;
944
485
        release_frames(enc_ctx, frames);
945
485
    }
946
485
    if (eos) {
947
485
        EbObjectWrapper* tmp_out_str_wrp;
948
485
        svt_get_empty_object(scs->enc_ctx->stream_output_fifo_ptr, &tmp_out_str_wrp);
949
485
        EbBufferHeaderType* tmp_out_str = (EbBufferHeaderType*)tmp_out_str_wrp->object_ptr;
950
951
485
        tmp_out_str->flags        = EB_BUFFERFLAG_EOS;
952
485
        tmp_out_str->n_filled_len = 0;
953
954
485
        svt_post_full_object(tmp_out_str_wrp);
955
485
        release_references_eos(scs);
956
485
    }
957
485
    svt_release_mutex(enc_ctx->total_number_of_shown_frames_mutex);
958
485
    return EB_ErrorNone;
959
485
}
960
961
485
void* svt_aom_packetization_kernel(void* input_ptr) {
962
485
    EbThreadContext*      thread_ctx  = (EbThreadContext*)input_ptr;
963
485
    PacketizationContext* context_ptr = (PacketizationContext*)thread_ctx->priv;
964
965
485
    context_ptr->tot_shown_frames            = 0;
966
485
    context_ptr->disp_order_continuity_count = 0;
967
968
970
    for (;;) {
969
970
        EbErrorType err = svt_aom_packetization_kernel_iter(thread_ctx->priv);
970
970
        if (err == EB_NoErrorFifoShutdown) {
971
485
            return NULL;
972
485
        }
973
970
    }
974
0
    return NULL;
975
485
}