1 /*
2 * Copyright(c) 2019 Intel Corporation
3 * SPDX - License - Identifier: BSD - 2 - Clause - Patent
4 */
5 
6 // SUMMARY
7 //   Contains the API component functions
8 
9 /**************************************
10  * Includes
11  **************************************/
12 
13 // Defining _GNU_SOURCE is needed for CPU_ZERO macro and needs to be set before any other includes
14 #ifdef __unix__
15 #define _GNU_SOURCE
16 #endif
17 
18 #include <stdlib.h>
19 #include <stdio.h>
20 
21 #include "EbDefinitions.h"
22 #include "EbSvtVp9Enc.h"
23 #include "EbThreads.h"
24 #include "EbUtility.h"
25 #include "EbEncHandle.h"
26 
27 #include "EbSystemResourceManager.h"
28 #include "EbPictureControlSet.h"
29 #include "EbSequenceControlSet.h"
30 #include "EbPictureBufferDesc.h"
31 #include "EbReferenceObject.h"
32 
33 #include "EbResourceCoordinationProcess.h"
34 #include "EbPictureAnalysisProcess.h"
35 #include "EbPictureDecisionProcess.h"
36 #include "EbMotionEstimationProcess.h"
37 #include "EbInitialRateControlProcess.h"
38 #include "EbSourceBasedOperationsProcess.h"
39 #include "EbPictureManagerProcess.h"
40 #include "EbRateControlProcess.h"
41 #include "EbModeDecisionConfigurationProcess.h"
42 #include "EbEncDecProcess.h"
43 #include "EbEntropyCodingProcess.h"
44 #include "EbPacketizationProcess.h"
45 
46 #include "EbResourceCoordinationResults.h"
47 #include "EbPictureAnalysisResults.h"
48 #include "EbPictureDecisionResults.h"
49 #include "EbMotionEstimationResults.h"
50 #include "EbInitialRateControlResults.h"
51 #include "EbPictureDemuxResults.h"
52 #include "EbRateControlTasks.h"
53 #include "EbRateControlResults.h"
54 #include "EbEncDecTasks.h"
55 #include "EbEncDecResults.h"
56 #include "EbEntropyCodingResults.h"
57 
58 #include "EbPredictionStructure.h"
59 
60 #ifdef _WIN32
61 #include <windows.h>
62 #else
63 #include <unistd.h>
64 #endif
65 
66 #ifdef __unix__
67 #include <sched.h>
68 #include <pthread.h>
69 #include <errno.h>
70 #include <sys/stat.h>
71 #include <fcntl.h>
72 #endif
73 
74 #define RTCD_C
75 #include "vpx_dsp_rtcd.h"
76 #include "vp9_rtcd.h"
77  /**************************************
78   * Defines
79   **************************************/
80 
81 #define EB_EncodeInstancesTotalCount                    1
82 #define EB_CandidateInitCount                           1
83 #define EB_ComputeSegmentInitCount                      1
84 
85   // Config Set Initial Count
86 #define EB_SequenceControlSetPoolInitCount              3
87 
88 // Process Instantiation Initial Counts
89 #define EB_ResourceCoordinationProcessInitCount         1
90 #define EB_PictureDecisionProcessInitCount              1
91 #define EB_InitialRateControlProcessInitCount           1
92 #define EB_PictureManagerProcessInitCount               1
93 #define EB_RateControlProcessInitCount                  1
94 #define EB_PacketizationProcessInitCount                1
95 
96 // Buffer Transfer Parameters
97 #define EB_INPUTVIDEOBUFFERSIZE                         0x10000//   832*480*3//      // Input Slice Size , must me a multiple of 2 in case of 10 bit video.
98 #define EB_OUTPUTSTREAMBUFFERSIZE                       0x2DC6C0   //0x7D00        // match MTU Size
99 #define EB_OUTPUTRECONBUFFERSIZE                        (MAX_PICTURE_WIDTH_SIZE*MAX_PICTURE_HEIGHT_SIZE*2)   // Recon Slice Size
100 #define EB_OUTPUTSTREAMQUANT                            27
101 #define EB_OUTPUTSTATISTICSBUFFERSIZE                   0x30            // 6X8 (8 Bytes for Y, U, V, number of bits, picture number, QP)
102 #define EB_OUTPUTSTREAMBUFFERSIZE_MACRO(ResolutionSize)                ((ResolutionSize) < (INPUT_SIZE_1080i_TH) ? 0x1E8480 : (ResolutionSize) < (INPUT_SIZE_1080p_TH) ? 0x2DC6C0 : (ResolutionSize) < (INPUT_SIZE_4K_TH) ? 0x2DC6C0 : 0x2DC6C0  )
103 
104 static uint64_t max_luma_picture_size[TOTAL_LEVEL_COUNT] = { 36864U, 122880U, 245760U, 552960U, 983040U, 2228224U, 2228224U, 8912896U, 8912896U, 8912896U, 35651584U, 35651584U, 35651584U };
105 static uint64_t max_luma_sample_rate[TOTAL_LEVEL_COUNT] = { 552960U, 3686400U, 7372800U, 16588800U, 33177600U, 66846720U, 133693440U, 267386880U, 534773760U, 1069547520U, 1069547520U, 2139095040U, 4278190080U };
106 
107 uint32_t eb_vp9_ASM_TYPES;
108 /**************************************
109  * External Functions
110  **************************************/
111 static EbErrorType  init_svt_vp9_encoder_handle(EbComponentType * h_component);
112 #include <immintrin.h>
113 
114 /**************************************
115  * Globals
116  **************************************/
117 
118 EbMemoryMapEntry  *memory_map;
119 uint32_t          *memory_map_index;
120 uint64_t          *total_lib_memory;
121 
122 uint32_t           lib_malloc_count = 0;
123 uint32_t           lib_thread_count = 0;
124 uint32_t           lib_semaphore_count = 0;
125 uint32_t           lib_mutex_count = 0;
126 
127 uint8_t                          eb_vp9_num_groups = 0;
128 #ifdef _WIN32
129 GROUP_AFFINITY                   eb_vp9_group_affinity;
130 EbBool                           eb_vp9_alternate_groups = 0;
131 #elif defined(__unix__)
132 cpu_set_t                        eb_vp9_group_affinity;
133 typedef struct logicalProcessorGroup {
134     uint32_t num;
135     uint32_t group[1024];
136 }processorGroup;
137 #define MAX_PROCESSOR_GROUP 16
138 processorGroup                   eb_vp9_lp_group[MAX_PROCESSOR_GROUP];
139 #endif
140 
141 /**************************************
142 * Instruction Set Support
143 **************************************/
144 #include <stdint.h>
145 #ifdef _WIN32
146 # include <intrin.h>
147 #endif
run_cpuid(uint32_t eax,uint32_t ecx,int * abcd)148 void run_cpuid(uint32_t eax, uint32_t ecx, int* abcd)
149 {
150 #ifdef _WIN32
151     __cpuidex(abcd, eax, ecx);
152 #else
153     uint32_t ebx, edx;
154 # if defined( __i386__ ) && defined ( __PIC__ )
155     /* in case of PIC under 32-bit EBX cannot be clobbered */
156     __asm__("movl %%ebx, %%edi \n\t cpuid \n\t xchgl %%ebx, %%edi" : "=D" (ebx),
157 # else
158     __asm__("cpuid" : "=b" (ebx),
159 # endif
160         "+a" (eax), "+c" (ecx), "=d" (edx));
161     abcd[0] = eax; abcd[1] = ebx; abcd[2] = ecx; abcd[3] = edx;
162 #endif
163 }
164 
check_xcr0_ymm()165 int check_xcr0_ymm()
166 {
167     uint32_t xcr0;
168 #ifdef _WIN32
169     xcr0 = (uint32_t)_xgetbv(0);  /* min VS2010 SP1 compiler is required */
170 #else
171     __asm__("xgetbv" : "=a" (xcr0) : "c" (0) : "%edx");
172 #endif
173     return ((xcr0 & 6) == 6); /* checking if xmm and ymm state are enabled in XCR0 */
174 }
check4th_gen_intel_core_features()175 int32_t check4th_gen_intel_core_features()
176 {
177     int abcd[4];
178     int fma_movbe_osxsave_mask = ((1 << 12) | (1 << 22) | (1 << 27));
179     int avx2_bmi12_mask = (1 << 5) | (1 << 3) | (1 << 8);
180 
181     /* CPUID.(EAX=01H, ECX=0H):ECX.FMA[bit 12]==1   &&
182        CPUID.(EAX=01H, ECX=0H):ECX.MOVBE[bit 22]==1 &&
183        CPUID.(EAX=01H, ECX=0H):ECX.OSXSAVE[bit 27]==1 */
184     run_cpuid(1, 0, abcd);
185     if ((abcd[2] & fma_movbe_osxsave_mask) != fma_movbe_osxsave_mask)
186         return 0;
187 
188     if (!check_xcr0_ymm())
189         return 0;
190 
191     /*  CPUID.(EAX=07H, ECX=0H):EBX.AVX2[bit 5]==1  &&
192         CPUID.(EAX=07H, ECX=0H):EBX.BMI1[bit 3]==1  &&
193         CPUID.(EAX=07H, ECX=0H):EBX.BMI2[bit 8]==1  */
194     run_cpuid(7, 0, abcd);
195     if ((abcd[1] & avx2_bmi12_mask) != avx2_bmi12_mask)
196         return 0;
197     /* CPUID.(EAX=80000001H):ECX.LZCNT[bit 5]==1 */
198     run_cpuid(0x80000001, 0, abcd);
199     if ((abcd[2] & (1 << 5)) == 0)
200         return 0;
201     return 1;
202 }
can_use_intel_core4th_gen_features()203 static int32_t can_use_intel_core4th_gen_features()
204 {
205     static int the_4th_gen_features_available = -1;
206     /* test is performed once */
207     if (the_4th_gen_features_available < 0)
208         the_4th_gen_features_available = check4th_gen_intel_core_features();
209     return the_4th_gen_features_available;
210 }
211 
check_xcr0_zmm()212 int check_xcr0_zmm()
213 {
214     uint32_t xcr0;
215     uint32_t zmm_ymm_xmm = (7 << 5) | (1 << 2) | (1 << 1);
216 #ifdef _WIN32
217     xcr0 = (uint32_t)_xgetbv(0);  /* min VS2010 SP1 compiler is required */
218 #else
219     __asm__("xgetbv" : "=a" (xcr0) : "c" (0) : "%edx");
220 #endif
221     return ((xcr0 & zmm_ymm_xmm) == zmm_ymm_xmm); /* check if xmm, ymm and zmm state are enabled in XCR0 */
222 }
223 
can_use_intel_avx512()224 static int32_t can_use_intel_avx512()
225 {
226     int abcd[4];
227 
228     /*  CPUID.(EAX=07H, ECX=0):EBX[bit 16]==1 AVX512F
229         CPUID.(EAX=07H, ECX=0):EBX[bit 17] AVX512DQ
230         CPUID.(EAX=07H, ECX=0):EBX[bit 28] AVX512CD
231         CPUID.(EAX=07H, ECX=0):EBX[bit 30] AVX512BW
232         CPUID.(EAX=07H, ECX=0):EBX[bit 31] AVX512VL */
233 
234     int avx512_ebx_mask =
235         (1 << 16)  // AVX-512F
236         | (1 << 17)  // AVX-512DQ
237         | (1 << 28)  // AVX-512CD
238         | (1 << 30)  // AVX-512BW
239         | (1 << 31); // AVX-512VL
240 
241     // ensure OS supports ZMM registers (and YMM, and XMM)
242     if (!check_xcr0_zmm())
243         return 0;
244 
245     if (!check4th_gen_intel_core_features())
246         return 0;
247 
248     run_cpuid(7, 0, abcd);
249     if ((abcd[1] & avx512_ebx_mask) != avx512_ebx_mask)
250         return 0;
251 
252     return 1;
253 }
254 
255 // Returns ASM Type based on system configuration. AVX512 - 111, AVX2 - 011, NONAVX2 - 001, C - 000
256 // Using bit-fields, the fastest function will always be selected based on the available functions in the function arrays
get_cpu_asm_type()257 uint32_t get_cpu_asm_type()
258 {
259     uint32_t asm_type = 0;
260 
261     if (can_use_intel_avx512() == 1)
262         asm_type = 7; // bit-field
263     else
264         if (can_use_intel_core4th_gen_features() == 1)
265             asm_type = 3; // bit-field
266         else
267             asm_type = 1; // bit-field
268 
269     return asm_type;
270 }
271 
272 //Get Number of logical processors
get_num_cores()273 uint32_t get_num_cores() {
274 #ifdef _WIN32
275    SYSTEM_INFO sysinfo;
276    GetSystemInfo(&sysinfo);
277    return eb_vp9_num_groups == 1 ? sysinfo.dwNumberOfProcessors : sysinfo.dwNumberOfProcessors << 1;
278 #else
279    return sysconf(_SC_NPROCESSORS_ONLN);
280 #endif
281 }
282 
283 /*****************************************
284  * Process Input Ports Config
285  *****************************************/
286 
287  // Rate Control
288 static RateControlPorts  rate_control_ports[] = {
289     {RATE_CONTROL_INPUT_PORT_PICTURE_MANAGER,    0},
290     {RATE_CONTROL_INPUT_PORT_PACKETIZATION,      0},
291     {RATE_CONTROL_INPUT_PORT_ENTROPY_CODING,     0},
292     {RATE_CONTROL_INPUT_PORT_INVALID,            0}
293 };
294 
295 typedef struct
296 {
297     int32_t   type;
298     uint32_t  count;
299 } EncDecPorts;
300 
301 #define ENCDEC_INPUT_PORT_MDC      0
302 #define ENCDEC_INPUT_PORT_ENCDEC   1
303 #define ENCDEC_INPUT_PORT_INVALID -1
304 
305 // EncDec
306 static EncDecPorts enc_dec_ports[] = {
307     {ENCDEC_INPUT_PORT_MDC,        0},
308     {ENCDEC_INPUT_PORT_ENCDEC,     0},
309     {ENCDEC_INPUT_PORT_INVALID,    0}
310 };
311 
312 /*****************************************
313  * Input Port Lookup
314  *****************************************/
315 
316  // Rate Control
rate_control_port_lookup(RateControlInputPortTypes type,uint32_t port_type_index)317 static uint32_t rate_control_port_lookup(
318     RateControlInputPortTypes type,
319     uint32_t                  port_type_index)
320 {
321     uint32_t port_index = 0;
322     uint32_t port_count = 0;
323 
324     while ((type != rate_control_ports[port_index].type) && (type != RATE_CONTROL_INPUT_PORT_INVALID)) {
325         port_count += rate_control_ports[port_index++].count;
326     }
327 
328     return (port_count + port_type_index);
329 }
330 
331 // EncDec
enc_dec_port_lookup(int32_t type,uint32_t port_type_index)332 static uint32_t enc_dec_port_lookup(
333     int32_t   type,
334     uint32_t  port_type_index)
335 {
336     uint32_t port_index = 0;
337     uint32_t port_count = 0;
338 
339     while ((type != enc_dec_ports[port_index].type) && (type != ENCDEC_INPUT_PORT_INVALID)) {
340         port_count += enc_dec_ports[port_index++].count;
341     }
342 
343     return (port_count + port_type_index);
344 }
345 
346 /*****************************************
347  * Input Port Total Count
348  *****************************************/
349 
350  // Rate Control
rate_control_port_total_count(void)351 static uint32_t rate_control_port_total_count(void)
352 {
353     uint32_t port_index = 0;
354     uint32_t total_count = 0;
355 
356     while (rate_control_ports[port_index].type != RATE_CONTROL_INPUT_PORT_INVALID) {
357         total_count += rate_control_ports[port_index++].count;
358     }
359 
360     return total_count;
361 }
362 
363 // EncDec
enc_dec_port_total_count(void)364 static uint32_t enc_dec_port_total_count(void)
365 {
366     uint32_t port_index = 0;
367     uint32_t total_count = 0;
368 
369     while (enc_dec_ports[port_index].type != ENCDEC_INPUT_PORT_INVALID) {
370         total_count += enc_dec_ports[port_index++].count;
371     }
372 
373     return total_count;
374 }
375 
init_thread_managment_params()376 EbErrorType init_thread_managment_params() {
377 #ifdef _WIN32
378     // Initialize eb_vp9_group_affinity structure with Current thread info
379     GetThreadGroupAffinity(GetCurrentThread(), &eb_vp9_group_affinity);
380     eb_vp9_num_groups = (uint8_t)GetActiveProcessorGroupCount();
381 #else
382     const char* PROCESSORID = "processor";
383     const char* PHYSICALID = "physical id";
384     int processor_id_len = EB_STRLEN(PROCESSORID, 128);
385     int physical_id_len = EB_STRLEN(PHYSICALID, 128);
386     if (processor_id_len < 0 || processor_id_len >= 128)
387         return EB_ErrorInsufficientResources;
388     if (physical_id_len < 0 || physical_id_len >= 128)
389         return EB_ErrorInsufficientResources;
390     memset(eb_vp9_lp_group, 0, sizeof(eb_vp9_lp_group));
391 
392     FILE *fin = fopen("/proc/cpuinfo", "r");
393     if (fin) {
394         int processor_id = 0, socket_id = 0;
395         char line[1024];
396         while (fgets(line, sizeof(line), fin)) {
397             if (strncmp(line, PROCESSORID, processor_id_len) == 0) {
398                 char* p = line + processor_id_len;
399                 while (*p < '0' || *p > '9') p++;
400                 processor_id = strtol(p, NULL, 0);
401             }
402             if (strncmp(line, PHYSICALID, physical_id_len) == 0) {
403                 char* p = line + physical_id_len;
404                 while (*p < '0' || *p > '9') p++;
405                 socket_id = strtol(p, NULL, 0);
406                 if (socket_id < 0 || socket_id > 15) {
407                     fclose(fin);
408                 return EB_ErrorInsufficientResources;
409             }
410             if (socket_id + 1 > eb_vp9_num_groups)
411                 eb_vp9_num_groups = socket_id + 1;
412             eb_vp9_lp_group[socket_id].group[eb_vp9_lp_group[socket_id].num++] = processor_id;
413         }
414     }
415     fclose(fin);
416     }
417 #endif
418     return EB_ErrorNone;
419 }
420 
421 /**********************************
422 * Encoder Error Handling
423 **********************************/
lib_svt_vp9_encoder_send_error_exit(EbPtr h_component,uint32_t error_code)424 void lib_svt_vp9_encoder_send_error_exit(
425     EbPtr    h_component,
426     uint32_t error_code) {
427 
428     EbComponentType      *svt_enc_component = (EbComponentType*)h_component;
429     EbEncHandle          *p_enc_comp_data   = (EbEncHandle*)svt_enc_component->p_component_private;
430     EbObjectWrapper      *eb_wrapper_ptr    = NULL;
431     EbBufferHeaderType   *output_packet;
432 
433     eb_vp9_get_empty_object(
434         (p_enc_comp_data->output_stream_buffer_producer_fifo_ptr_dbl_array[0])[0],
435         &eb_wrapper_ptr);
436 
437     output_packet = (EbBufferHeaderType*)eb_wrapper_ptr->object_ptr;
438 
439     output_packet->size   = 0;
440     output_packet->flags  = error_code;
441     output_packet->p_buffer = NULL;
442 
443     eb_vp9_post_full_object(eb_wrapper_ptr);
444 }
445 
446 /**********************************
447  * Encoder Library Handle Constructor
448  **********************************/
eb_enc_handle_ctor(EbEncHandle ** enc_handle_dbl_ptr,EbHandleType eb_handle_ptr)449 static EbErrorType  eb_enc_handle_ctor(
450     EbEncHandle **enc_handle_dbl_ptr,
451     EbHandleType  eb_handle_ptr){
452 
453     EbErrorType  return_error = EB_ErrorNone;
454     // Allocate Memory
455     EbEncHandle *enc_handle_ptr = (EbEncHandle*)malloc(sizeof(EbEncHandle));
456     *enc_handle_dbl_ptr = enc_handle_ptr;
457     if (enc_handle_ptr == (EbEncHandle*)EB_NULL) {
458         return EB_ErrorInsufficientResources;
459     }
460     enc_handle_ptr->memory_map = (EbMemoryMapEntry*)malloc(sizeof(EbMemoryMapEntry) * MAX_NUM_PTR);
461     enc_handle_ptr->memory_map_index = 0;
462     enc_handle_ptr->total_lib_memory = sizeof(EbEncHandle) + sizeof(EbMemoryMapEntry) * MAX_NUM_PTR;
463 
464     // Save Memory Map Pointers
465     total_lib_memory = &enc_handle_ptr->total_lib_memory;
466     memory_map = enc_handle_ptr->memory_map;
467     memory_map_index = &enc_handle_ptr->memory_map_index;
468     lib_malloc_count = 0;
469     lib_thread_count = 0;
470     lib_mutex_count = 0;
471     lib_semaphore_count = 0;
472 
473     if (memory_map == (EbMemoryMapEntry*)EB_NULL) {
474         return EB_ErrorInsufficientResources;
475     }
476 
477     return_error = init_thread_managment_params();
478     if (return_error == EB_ErrorInsufficientResources)
479         return EB_ErrorInsufficientResources;
480 
481     enc_handle_ptr->encode_instance_total_count = EB_EncodeInstancesTotalCount;
482 
483     EB_MALLOC(uint32_t*, enc_handle_ptr->compute_segments_total_count_array, sizeof(uint32_t) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
484 
485     enc_handle_ptr->compute_segments_total_count_array[0]                 = EB_ComputeSegmentInitCount;
486 
487     // Config Set Count
488     enc_handle_ptr->sequence_control_set_pool_total_count                 = EB_SequenceControlSetPoolInitCount;
489 
490     // Sequence Control Set Buffers
491     enc_handle_ptr->sequence_control_set_pool_ptr                         = (EbSystemResource*)EB_NULL;
492     enc_handle_ptr->sequence_control_set_pool_producer_fifo_ptr_array     = (EbFifo**)EB_NULL;
493 
494     // Picture Buffers
495     enc_handle_ptr->reference_picture_pool_ptr_array                      = (EbSystemResource**)EB_NULL;
496     enc_handle_ptr->pa_reference_picture_pool_ptr_array                   = (EbSystemResource**)EB_NULL;
497 
498     // Picture Buffer Producer Fifos
499     enc_handle_ptr->reference_picture_pool_producer_fifo_ptr_dbl_array    = (EbFifo***)EB_NULL;
500     enc_handle_ptr->pa_reference_picture_pool_producer_fifo_ptr_dbl_array = (EbFifo***)EB_NULL;
501 
502     // Threads
503     enc_handle_ptr->resource_coordination_thread_handle             = (EbHandle)EB_NULL;
504     enc_handle_ptr->picture_analysis_thread_handle_array            = (EbHandle*)EB_NULL;
505     enc_handle_ptr->picture_decision_thread_handle                  = (EbHandle)EB_NULL;
506     enc_handle_ptr->motion_estimation_thread_handle_array           = (EbHandle*)EB_NULL;
507     enc_handle_ptr->initial_rate_control_thread_handle              = (EbHandle)EB_NULL;
508     enc_handle_ptr->source_based_operations_thread_handle_array     = (EbHandle*)EB_NULL;
509     enc_handle_ptr->picture_manager_thread_handle                   = (EbHandle)EB_NULL;
510     enc_handle_ptr->rate_control_thread_handle                      = (EbHandle)EB_NULL;
511     enc_handle_ptr->mode_decision_configuration_thread_handle_array = (EbHandle*)EB_NULL;
512     enc_handle_ptr->enc_dec_thread_handle_array                     = (EbHandle*)EB_NULL;
513     enc_handle_ptr->entropy_coding_thread_handle_array              = (EbHandle*)EB_NULL;
514     enc_handle_ptr->packetization_thread_handle                     = (EbHandle)EB_NULL;
515 
516     // Contexts
517     enc_handle_ptr->resource_coordination_context_ptr             = (EbPtr)EB_NULL;
518     enc_handle_ptr->picture_analysis_context_ptr_array            = (EbPtr *)EB_NULL;
519     enc_handle_ptr->picture_decision_context_ptr                  = (EbPtr)EB_NULL;
520     enc_handle_ptr->motion_estimation_context_ptr_array           = (EbPtr *)EB_NULL;
521     enc_handle_ptr->initial_rate_control_context_ptr              = (EbPtr)EB_NULL;
522     enc_handle_ptr->source_based_operations_context_ptr_array     = (EbPtr *)EB_NULL;
523     enc_handle_ptr->picture_manager_context_ptr                   = (EbPtr)EB_NULL;
524     enc_handle_ptr->rate_control_context_ptr                      = (EbPtr)EB_NULL;
525     enc_handle_ptr->mode_decision_configuration_context_ptr_array = (EbPtr *)EB_NULL;
526     enc_handle_ptr->enc_dec_context_ptr_array                     = (EbPtr *)EB_NULL;
527     enc_handle_ptr->entropy_coding_context_ptr_array              = (EbPtr *)EB_NULL;
528     enc_handle_ptr->packetization_context_ptr                     = (EbPtr)EB_NULL;
529 
530     // System Resource Managers
531     enc_handle_ptr->input_buffer_resource_ptr                             = (EbSystemResource*)EB_NULL;
532     enc_handle_ptr->output_stream_buffer_resource_ptr_array               = (EbSystemResource**)EB_NULL;
533     enc_handle_ptr->resource_coordination_results_resource_ptr            = (EbSystemResource*)EB_NULL;
534     enc_handle_ptr->picture_analysis_results_resource_ptr                 = (EbSystemResource*)EB_NULL;
535     enc_handle_ptr->picture_decision_results_resource_ptr                 = (EbSystemResource*)EB_NULL;
536     enc_handle_ptr->motion_estimation_results_resource_ptr                = (EbSystemResource*)EB_NULL;
537     enc_handle_ptr->initial_rate_control_results_resource_ptr             = (EbSystemResource*)EB_NULL;
538     enc_handle_ptr->picture_demux_results_resource_ptr                    = (EbSystemResource*)EB_NULL;
539     enc_handle_ptr->rate_control_tasks_resource_ptr                       = (EbSystemResource*)EB_NULL;
540     enc_handle_ptr->rate_control_results_resource_ptr                     = (EbSystemResource*)EB_NULL;
541     enc_handle_ptr->enc_dec_tasks_resource_ptr                            = (EbSystemResource*)EB_NULL;
542     enc_handle_ptr->enc_dec_results_resource_ptr                          = (EbSystemResource*)EB_NULL;
543     enc_handle_ptr->entropy_coding_results_resource_ptr                   = (EbSystemResource*)EB_NULL;
544     enc_handle_ptr->output_recon_buffer_resource_ptr_array                = (EbSystemResource**)EB_NULL;
545 
546     // Inter-Process Producer Fifos
547     enc_handle_ptr->input_buffer_producer_fifo_ptr_array                  = (EbFifo**)EB_NULL;
548     enc_handle_ptr->output_stream_buffer_producer_fifo_ptr_dbl_array      = (EbFifo***)EB_NULL;
549     enc_handle_ptr->resource_coordination_results_producer_fifo_ptr_array = (EbFifo**)EB_NULL;
550     enc_handle_ptr->picture_demux_results_producer_fifo_ptr_array         = (EbFifo**)EB_NULL;
551     enc_handle_ptr->picture_manager_results_producer_fifo_ptr_array       = (EbFifo**)EB_NULL;
552     enc_handle_ptr->rate_control_tasks_producer_fifo_ptr_array            = (EbFifo**)EB_NULL;
553     enc_handle_ptr->rate_control_results_producer_fifo_ptr_array          = (EbFifo**)EB_NULL;
554     enc_handle_ptr->enc_dec_tasks_producer_fifo_ptr_array                 = (EbFifo**)EB_NULL;
555     enc_handle_ptr->enc_dec_results_producer_fifo_ptr_array               = (EbFifo**)EB_NULL;
556     enc_handle_ptr->entropy_coding_results_producer_fifo_ptr_array        = (EbFifo**)EB_NULL;
557     enc_handle_ptr->output_recon_buffer_producer_fifo_ptr_dbl_array       = (EbFifo***)EB_NULL;
558 
559     // Inter-Process Consumer Fifos
560     enc_handle_ptr->input_buffer_consumer_fifo_ptr_array                  = (EbFifo**)EB_NULL;
561     enc_handle_ptr->output_stream_buffer_consumer_fifo_ptr_dbl_array      = (EbFifo***)EB_NULL;
562     enc_handle_ptr->resource_coordination_results_consumer_fifo_ptr_array = (EbFifo**)EB_NULL;
563     enc_handle_ptr->picture_demux_results_consumer_fifo_ptr_array         = (EbFifo**)EB_NULL;
564     enc_handle_ptr->rate_control_tasks_consumer_fifo_ptr_array            = (EbFifo**)EB_NULL;
565     enc_handle_ptr->rate_control_results_consumer_fifo_ptr_array          = (EbFifo**)EB_NULL;
566     enc_handle_ptr->enc_dec_tasks_consumer_fifo_ptr_array                 = (EbFifo**)EB_NULL;
567     enc_handle_ptr->enc_dec_results_consumer_fifo_ptr_array               = (EbFifo**)EB_NULL;
568     enc_handle_ptr->entropy_coding_results_consumer_fifo_ptr_array        = (EbFifo**)EB_NULL;
569     enc_handle_ptr->output_recon_buffer_consumer_fifo_ptr_dbl_array       = (EbFifo***)EB_NULL;
570 
571     // Initialize Callbacks
572     EB_MALLOC(EbCallback  **, enc_handle_ptr->app_callback_ptr_array, sizeof(EbCallback  *) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
573 
574     EB_MALLOC(EbCallback  *, enc_handle_ptr->app_callback_ptr_array[0], sizeof(EbCallback), EB_N_PTR);
575 
576     enc_handle_ptr->app_callback_ptr_array[0]->error_handler = lib_svt_vp9_encoder_send_error_exit;
577     enc_handle_ptr->app_callback_ptr_array[0]->app_private_data                     = EB_NULL;
578     enc_handle_ptr->app_callback_ptr_array[0]->handle                               = eb_handle_ptr;
579 
580     // Initialize Sequence Control Set Instance Array
581     EB_MALLOC(EbSequenceControlSetInstance  **, enc_handle_ptr->sequence_control_set_instance_array, sizeof(EbSequenceControlSetInstance  *) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
582 
583     return_error = eb_vp9_sequence_control_set_instance_ctor(&enc_handle_ptr->sequence_control_set_instance_array[0]);
584     if (return_error == EB_ErrorInsufficientResources) {
585         return EB_ErrorInsufficientResources;
586     }
587 
588     return EB_ErrorNone;
589 }
590 
591 #ifdef _WIN32
get_affinity_mask(uint32_t lpnum)592 static uint64_t get_affinity_mask(uint32_t lpnum) {
593     uint64_t mask = 0x1;
594     for (uint32_t i = lpnum - 1; i > 0; i--)
595         mask += (uint64_t)1 << i;
596     return mask;
597 }
598 #endif
599 
eb_set_thread_management_parameters(EbSvtVp9EncConfiguration * config_ptr)600 static void eb_set_thread_management_parameters( EbSvtVp9EncConfiguration *config_ptr){
601 
602     uint32_t num_logical_processors = get_num_cores();
603 #ifdef _WIN32
604     // For system with a single processor group(no more than 64 logic processors all together)
605     // Affinity of the thread can be set to one or more logical processors
606     if (eb_vp9_num_groups == 1) {
607         uint32_t lps = config_ptr->logical_processors == 0 ? num_logical_processors :
608             config_ptr->logical_processors < num_logical_processors ? config_ptr->logical_processors : num_logical_processors;
609         eb_vp9_group_affinity.Mask = get_affinity_mask(lps);
610     }
611     else if (eb_vp9_num_groups > 1) { // For system with multiple processor group
612         if (config_ptr->logical_processors == 0) {
613             if (config_ptr->target_socket != -1)
614                 eb_vp9_group_affinity.Group = config_ptr->target_socket;
615         }
616         else {
617             uint32_t num_lp_per_group = num_logical_processors / eb_vp9_num_groups;
618             if (config_ptr->target_socket == -1) {
619                 if (config_ptr->logical_processors > num_lp_per_group) {
620                     eb_vp9_alternate_groups = EB_TRUE;
621                     SVT_LOG("SVT [WARNING]: -lp(logical processors) setting is ignored. Run on both sockets. \n");
622                 }
623                 else
624                     eb_vp9_group_affinity.Mask = get_affinity_mask(config_ptr->logical_processors);
625             }
626             else {
627                 uint32_t lps = config_ptr->logical_processors == 0 ? num_lp_per_group :
628                     config_ptr->logical_processors < num_lp_per_group ? config_ptr->logical_processors : num_lp_per_group;
629                 eb_vp9_group_affinity.Mask = get_affinity_mask(lps);
630                 eb_vp9_group_affinity.Group = config_ptr->target_socket;
631             }
632         }
633     }
634 #elif defined(__unix__)
635 
636     CPU_ZERO(&eb_vp9_group_affinity);
637 
638     if (eb_vp9_num_groups == 1) {
639         uint32_t lps = config_ptr->logical_processors == 0 ? num_logical_processors :
640             config_ptr->logical_processors < num_logical_processors ? config_ptr->logical_processors : num_logical_processors;
641         for (uint32_t i = 0; i < lps; i++)
642             CPU_SET(eb_vp9_lp_group[0].group[i], &eb_vp9_group_affinity);
643     }
644     else if (eb_vp9_num_groups > 1) {
645         uint32_t num_lp_per_group = num_logical_processors / eb_vp9_num_groups;
646         if (config_ptr->logical_processors == 0) {
647             if (config_ptr->target_socket != -1) {
648                 for (uint32_t i = 0; i < eb_vp9_lp_group[config_ptr->target_socket].num; i++)
649                     CPU_SET(eb_vp9_lp_group[config_ptr->target_socket].group[i], &eb_vp9_group_affinity);
650             }
651         }
652         else {
653             if (config_ptr->target_socket == -1) {
654                 uint32_t lps = config_ptr->logical_processors == 0 ? num_logical_processors :
655                     config_ptr->logical_processors < num_logical_processors ? config_ptr->logical_processors : num_logical_processors;
656                 if (lps > num_lp_per_group) {
657                     for (uint32_t i = 0; i < eb_vp9_lp_group[0].num; i++)
658                         CPU_SET(eb_vp9_lp_group[0].group[i], &eb_vp9_group_affinity);
659                     for (uint32_t i = 0; i < (lps - eb_vp9_lp_group[0].num); i++)
660                         CPU_SET(eb_vp9_lp_group[1].group[i], &eb_vp9_group_affinity);
661                 }
662                 else {
663                     for (uint32_t i = 0; i < lps; i++)
664                         CPU_SET(eb_vp9_lp_group[0].group[i], &eb_vp9_group_affinity);
665                 }
666             }
667             else {
668                 uint32_t lps = config_ptr->logical_processors == 0 ? num_lp_per_group :
669                     config_ptr->logical_processors < num_lp_per_group ? config_ptr->logical_processors : num_lp_per_group;
670                 for (uint32_t i = 0; i < lps; i++)
671                     CPU_SET(eb_vp9_lp_group[config_ptr->target_socket].group[i], &eb_vp9_group_affinity);
672             }
673         }
674     }
675 #endif
676 }
677 
lib_allocate_frame_buffer(SequenceControlSet * sequence_control_set_ptr,EbBufferHeaderType * input_buffer)678 EbErrorType lib_allocate_frame_buffer(
679     SequenceControlSet *sequence_control_set_ptr,
680     EbBufferHeaderType *input_buffer)
681 {
682     EbErrorType   return_error = EB_ErrorNone;
683     EbPictureBufferDescInitData input_picture_buffer_desc_init_data;
684     EbSvtVp9EncConfiguration   *config = &sequence_control_set_ptr->static_config;
685     uint8_t is16bit = config->encoder_bit_depth > 8 ? 1 : 0;
686     // Init Picture Init data
687     input_picture_buffer_desc_init_data.max_width = (uint16_t)sequence_control_set_ptr->max_input_luma_width;
688     input_picture_buffer_desc_init_data.max_height = (uint16_t)sequence_control_set_ptr->max_input_luma_height;
689     input_picture_buffer_desc_init_data.bit_depth = config->encoder_bit_depth;
690 
691     input_picture_buffer_desc_init_data.buffer_enable_mask = is16bit ? PICTURE_BUFFER_DESC_FULL_MASK : 0;
692 
693     input_picture_buffer_desc_init_data.left_padding = sequence_control_set_ptr->left_padding;
694     input_picture_buffer_desc_init_data.right_padding = sequence_control_set_ptr->right_padding;
695     input_picture_buffer_desc_init_data.top_padding = sequence_control_set_ptr->top_padding;
696     input_picture_buffer_desc_init_data.bot_padding = sequence_control_set_ptr->bot_padding;
697 
698     input_picture_buffer_desc_init_data.split_mode = is16bit ? EB_TRUE : EB_FALSE;
699 
700     input_picture_buffer_desc_init_data.buffer_enable_mask = PICTURE_BUFFER_DESC_FULL_MASK;
701 
702     // Enhanced Picture Buffer
703     return_error = eb_vp9_picture_buffer_desc_ctor(
704         (EbPtr*) &(input_buffer->p_buffer),
705         (EbPtr)&input_picture_buffer_desc_init_data);
706 
707     if (return_error == EB_ErrorInsufficientResources) {
708         return EB_ErrorInsufficientResources;
709     }
710 
711     return return_error;
712 }
713 
714 /**************************************
715 * EbBufferHeaderType Constructor
716 **************************************/
eb_input_buffer_header_ctor(EbPtr * object_dbl_ptr,EbPtr object_init_data_ptr)717 static EbErrorType eb_input_buffer_header_ctor(
718     EbPtr *object_dbl_ptr,
719     EbPtr  object_init_data_ptr)
720 {
721     EbBufferHeaderType        *input_buffer;
722     SequenceControlSet        *sequence_control_set_ptr = (SequenceControlSet*)object_init_data_ptr;
723     EB_MALLOC(EbBufferHeaderType*, input_buffer, sizeof(EbBufferHeaderType), EB_N_PTR);
724     *object_dbl_ptr = (EbPtr)input_buffer;
725     // Initialize Header
726     input_buffer->size = sizeof(EbBufferHeaderType);
727 
728     lib_allocate_frame_buffer(
729         sequence_control_set_ptr,
730         input_buffer);
731 
732     input_buffer->p_app_private = NULL;
733 
734     return EB_ErrorNone;
735 }
eb_output_recon_buffer_header_ctor(EbPtr * object_dbl_ptr,EbPtr object_init_data_ptr)736 EbErrorType eb_output_recon_buffer_header_ctor(
737     EbPtr *object_dbl_ptr,
738     EbPtr  object_init_data_ptr)
739 {
740     EbBufferHeaderType        *recon_buffer;
741     SequenceControlSet        *sequence_control_set_ptr = (SequenceControlSet*)object_init_data_ptr;
742     const uint32_t luma_size =
743         sequence_control_set_ptr->luma_width    *
744         sequence_control_set_ptr->luma_height;
745     // both u and v
746     const uint32_t chroma_size = luma_size >> 1;
747     const uint32_t ten_bit = (sequence_control_set_ptr->static_config.encoder_bit_depth > 8);
748     const uint32_t frame_size = (luma_size + chroma_size) << ten_bit;
749 
750     EB_MALLOC(EbBufferHeaderType*, recon_buffer, sizeof(EbBufferHeaderType), EB_N_PTR);
751     *object_dbl_ptr = (EbPtr)recon_buffer;
752 
753     // Initialize Header
754     recon_buffer->size = sizeof(EbBufferHeaderType);
755 
756     // Assign the variables
757     EB_MALLOC(uint8_t*, recon_buffer->p_buffer, frame_size, EB_N_PTR);
758 
759     recon_buffer->n_alloc_len = frame_size;
760     recon_buffer->p_app_private = NULL;
761 
762     return EB_ErrorNone;
763 }
764 /**************************************
765 * EbBufferHeaderType Constructor
766 **************************************/
eb_output_buffer_header_ctor(EbPtr * object_dbl_ptr,EbPtr object_init_data_ptr)767 static EbErrorType eb_output_buffer_header_ctor(
768     EbPtr *object_dbl_ptr,
769     EbPtr  object_init_data_ptr)
770 {
771     EbSvtVp9EncConfiguration   * config = (EbSvtVp9EncConfiguration*)object_init_data_ptr;
772     uint32_t size = (uint32_t)(EB_OUTPUTSTREAMBUFFERSIZE_MACRO(config->source_width * config->source_height));  //TBC
773     EbBufferHeaderType* out_buf_ptr;
774 
775     EB_MALLOC(EbBufferHeaderType*, out_buf_ptr, sizeof(EbBufferHeaderType), EB_N_PTR);
776     *object_dbl_ptr = (EbPtr)out_buf_ptr;
777 
778     // Initialize Header
779     out_buf_ptr->size = sizeof(EbBufferHeaderType);
780 
781     EB_MALLOC(uint8_t*, out_buf_ptr->p_buffer, size, EB_N_PTR);
782 
783     out_buf_ptr->n_alloc_len = size;
784     out_buf_ptr->p_app_private = NULL;
785 
786     return EB_ErrorNone;
787 }
788 
789 /**********************************
790  * Initialize Encoder Library
791  **********************************/
792 #if __unix__
793 __attribute__((visibility("default")))
794 #endif
eb_vp9_init_encoder(EbComponentType * svt_enc_component)795 EB_API EbErrorType  eb_vp9_init_encoder(EbComponentType *svt_enc_component) {
796 
797     EbEncHandle *enc_handle_ptr = (EbEncHandle*)svt_enc_component->p_component_private;
798     EbErrorType  return_error = EB_ErrorNone;
799     uint32_t process_index;
800     uint32_t maxpicture_width;
801     uint32_t max_look_ahead_distance = 0;
802     SequenceControlSet *scs_ptr = enc_handle_ptr->sequence_control_set_instance_array[0]->sequence_control_set_ptr;
803 
804     EB_BOOL is16bit = (EB_BOOL)(scs_ptr->static_config.encoder_bit_depth > EB_8BIT);
805 
806     /************************************
807     * Platform detection
808     ************************************/
809 
810     if (scs_ptr->static_config.asm_type == ASM_AVX2) {
811         eb_vp9_ASM_TYPES = get_cpu_asm_type();
812     }
813     else if (scs_ptr->static_config.asm_type == ASM_NON_AVX2) {
814         eb_vp9_ASM_TYPES = 0;
815     }
816 
817     setup_rtcd_internal(eb_vp9_ASM_TYPES);
818     setup_rtcd_internal_vp9(eb_vp9_ASM_TYPES);
819     build_ep_block_stats();
820 
821     /************************************
822      * Sequence Control Set
823      ************************************/
824     return_error = eb_vp9_system_resource_ctor(
825         &enc_handle_ptr->sequence_control_set_pool_ptr,
826         enc_handle_ptr->sequence_control_set_pool_total_count,
827         1,
828         0,
829         &enc_handle_ptr->sequence_control_set_pool_producer_fifo_ptr_array,
830         (EbFifo ***)EB_NULL,
831         EB_FALSE,
832         eb_vp9_sequence_control_set_ctor,
833         EB_NULL);
834 
835     if (return_error == EB_ErrorInsufficientResources) {
836         return EB_ErrorInsufficientResources;
837     }
838     /************************************
839      * Picture Control Set: Parent
840      ************************************/
841     EB_MALLOC(EbSystemResource**, enc_handle_ptr->picture_parent_control_set_pool_ptr_array, sizeof(EbSystemResource*)  * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
842     EB_MALLOC(EbFifo***, enc_handle_ptr->picture_parent_control_set_pool_producer_fifo_ptr_dbl_array, sizeof(EbSystemResource**) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
843 
844     // Updating the picture_control_set_pool_total_count based on the maximum look ahead distance
845     max_look_ahead_distance = MAX(max_look_ahead_distance, scs_ptr->look_ahead_distance);
846 
847     // The segment Width & Height Arrays are in units of LCUs, not samples
848     PictureControlSetInitData input_data;
849 
850     input_data.picture_width = scs_ptr->max_input_luma_width;
851     input_data.picture_height = scs_ptr->max_input_luma_height;
852     input_data.left_padding = scs_ptr->left_padding;
853     input_data.right_padding = scs_ptr->right_padding;
854     input_data.top_padding = scs_ptr->top_padding;
855     input_data.bot_padding = scs_ptr->bot_padding;
856     input_data.bit_depth = scs_ptr->output_bitdepth;
857     input_data.is16bit = is16bit;
858 
859     input_data.enc_mode = scs_ptr->static_config.enc_mode;
860     input_data.speed_control = (uint8_t)scs_ptr->static_config.speed_control_flag;
861     input_data.tune = scs_ptr->static_config.tune;
862     return_error = eb_vp9_system_resource_ctor(
863         &(enc_handle_ptr->picture_parent_control_set_pool_ptr_array[0]),
864         scs_ptr->picture_control_set_pool_init_count,//enc_handle_ptr->picture_control_set_pool_total_count,
865         1,
866         0,
867         &enc_handle_ptr->picture_parent_control_set_pool_producer_fifo_ptr_dbl_array[0],
868         (EbFifo ***)EB_NULL,
869         EB_FALSE,
870         eb_vp9_picture_parent_control_set_ctor,
871         &input_data);
872     if (return_error == EB_ErrorInsufficientResources) {
873         return EB_ErrorInsufficientResources;
874     }
875 
876     /************************************
877      * Picture Control Set: Child
878      ************************************/
879     EB_MALLOC(EbSystemResource**, enc_handle_ptr->picture_control_set_pool_ptr_array, sizeof(EbSystemResource*)  * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
880     EB_MALLOC(EbFifo***, enc_handle_ptr->picture_control_set_pool_producer_fifo_ptr_dbl_array, sizeof(EbSystemResource**) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
881 
882     // The segment Width & Height Arrays are in units of LCUs, not samples
883     {
884         PictureControlSetInitData input_data;
885         unsigned i;
886 
887         input_data.enc_dec_segment_col = 0;
888         input_data.enc_dec_segment_row = 0;
889 
890         for (i = 0; i <= scs_ptr->hierarchical_levels; ++i) {
891             input_data.enc_dec_segment_col = scs_ptr->enc_dec_segment_col_count_array[i] > input_data.enc_dec_segment_col ?
892                 (uint16_t)scs_ptr->enc_dec_segment_col_count_array[i] :
893                 input_data.enc_dec_segment_col;
894             input_data.enc_dec_segment_row = scs_ptr->enc_dec_segment_row_count_array[i] > input_data.enc_dec_segment_row ?
895                 (uint16_t)scs_ptr->enc_dec_segment_row_count_array[i] :
896                 input_data.enc_dec_segment_row;
897         }
898 
899         input_data.picture_width = scs_ptr->max_input_luma_width;
900         input_data.picture_height = scs_ptr->max_input_luma_height;
901         input_data.left_padding = scs_ptr->left_padding;
902         input_data.right_padding = scs_ptr->right_padding;
903         input_data.top_padding = scs_ptr->top_padding;
904         input_data.bot_padding = scs_ptr->bot_padding;
905         input_data.bit_depth = EB_8BIT;
906         input_data.is16bit = is16bit;
907         return_error = eb_vp9_system_resource_ctor(
908             &(enc_handle_ptr->picture_control_set_pool_ptr_array[0]),
909             scs_ptr->picture_control_set_pool_init_count_child, //EB_PictureControlSetPoolInitCountChild,
910             1,
911             0,
912             &enc_handle_ptr->picture_control_set_pool_producer_fifo_ptr_dbl_array[0],
913             (EbFifo ***)EB_NULL,
914             EB_FALSE,
915             eb_vp9_picture_control_set_ctor,
916             &input_data);
917         if (return_error == EB_ErrorInsufficientResources) {
918             return EB_ErrorInsufficientResources;
919         }
920     }
921 
922     /************************************
923      * Picture Buffers
924      ************************************/
925 
926      // Allocate Resource Arrays
927     EB_MALLOC(EbSystemResource**, enc_handle_ptr->reference_picture_pool_ptr_array, sizeof(EbSystemResource*) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
928     EB_MALLOC(EbSystemResource**, enc_handle_ptr->pa_reference_picture_pool_ptr_array, sizeof(EbSystemResource*) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
929 
930     // Allocate Producer Fifo Arrays
931     EB_MALLOC(EbFifo***, enc_handle_ptr->reference_picture_pool_producer_fifo_ptr_dbl_array, sizeof(EbFifo**) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
932     EB_MALLOC(EbFifo***, enc_handle_ptr->pa_reference_picture_pool_producer_fifo_ptr_dbl_array, sizeof(EbFifo**) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
933 
934     // Rate Control
935     rate_control_ports[0].count = EB_PictureManagerProcessInitCount;
936     rate_control_ports[1].count = EB_PacketizationProcessInitCount;
937     rate_control_ports[2].count = scs_ptr->entropy_coding_process_init_count;
938     rate_control_ports[3].count = 0;
939 
940     enc_dec_ports[ENCDEC_INPUT_PORT_MDC].count = scs_ptr->mode_decision_configuration_process_init_count;
941     enc_dec_ports[ENCDEC_INPUT_PORT_ENCDEC].count = scs_ptr->enc_dec_process_init_count;
942 
943     EbReferenceObjectDescInitData     eb_reference_object_desc_init_data_structure;
944     EbPaReferenceObjectDescInitData   eb_pa_reference_object_desc_init_data_structure;
945     EbPictureBufferDescInitData       reference_picture_buffer_desc_init_data;
946     EbPictureBufferDescInitData       quarter_decim_picture_buffer_desc_init_data;
947     EbPictureBufferDescInitData       sixteenth_decim_picture_buffer_desc_init_data;
948 
949     // Initialize the various Picture types
950     reference_picture_buffer_desc_init_data.max_width = scs_ptr->max_input_luma_width;
951     reference_picture_buffer_desc_init_data.max_height = scs_ptr->max_input_luma_height;
952     reference_picture_buffer_desc_init_data.bit_depth = scs_ptr->input_bit_depth;
953     reference_picture_buffer_desc_init_data.buffer_enable_mask = PICTURE_BUFFER_DESC_FULL_MASK;
954     reference_picture_buffer_desc_init_data.left_padding = MAX_SB_SIZE + MCPXPaddingOffset;
955     reference_picture_buffer_desc_init_data.right_padding = MAX_SB_SIZE + MCPXPaddingOffset;
956     reference_picture_buffer_desc_init_data.top_padding = MAX_SB_SIZE + MCPYPaddingOffset;
957     reference_picture_buffer_desc_init_data.bot_padding = MAX_SB_SIZE + MCPYPaddingOffset;
958     reference_picture_buffer_desc_init_data.split_mode = EB_FALSE;
959 
960     if (is16bit) {
961         reference_picture_buffer_desc_init_data.bit_depth = EB_10BIT;
962     }
963 
964     eb_reference_object_desc_init_data_structure.reference_picture_desc_init_data = reference_picture_buffer_desc_init_data;
965 
966     // Reference Picture Buffers
967     return_error = eb_vp9_system_resource_ctor(
968         &enc_handle_ptr->reference_picture_pool_ptr_array[0],
969         scs_ptr->reference_picture_buffer_init_count,//enc_handle_ptr->reference_picture_pool_total_count,
970         EB_PictureManagerProcessInitCount,
971         0,
972         &enc_handle_ptr->reference_picture_pool_producer_fifo_ptr_dbl_array[0],
973         (EbFifo ***)EB_NULL,
974         EB_FALSE,
975         eb_vp9_reference_object_ctor,
976         &(eb_reference_object_desc_init_data_structure));
977 
978     if (return_error == EB_ErrorInsufficientResources) {
979         return EB_ErrorInsufficientResources;
980     }
981 
982     // PA Reference Picture Buffers
983     // Currently, only Luma samples are needed in the PA
984     reference_picture_buffer_desc_init_data.max_width = scs_ptr->max_input_luma_width;
985     reference_picture_buffer_desc_init_data.max_height = scs_ptr->max_input_luma_height;
986     reference_picture_buffer_desc_init_data.bit_depth = scs_ptr->input_bit_depth;
987     reference_picture_buffer_desc_init_data.buffer_enable_mask = 0;
988     reference_picture_buffer_desc_init_data.left_padding = MAX_SB_SIZE + ME_FILTER_TAP;
989     reference_picture_buffer_desc_init_data.right_padding = MAX_SB_SIZE + ME_FILTER_TAP;
990     reference_picture_buffer_desc_init_data.top_padding = MAX_SB_SIZE + ME_FILTER_TAP;
991     reference_picture_buffer_desc_init_data.bot_padding = MAX_SB_SIZE + ME_FILTER_TAP;
992     reference_picture_buffer_desc_init_data.split_mode = EB_FALSE;
993 
994     quarter_decim_picture_buffer_desc_init_data.max_width = scs_ptr->max_input_luma_width >> 1;
995     quarter_decim_picture_buffer_desc_init_data.max_height = scs_ptr->max_input_luma_height >> 1;
996     quarter_decim_picture_buffer_desc_init_data.bit_depth = scs_ptr->input_bit_depth;
997     quarter_decim_picture_buffer_desc_init_data.buffer_enable_mask = PICTURE_BUFFER_DESC_LUMA_MASK;
998     quarter_decim_picture_buffer_desc_init_data.left_padding = MAX_SB_SIZE >> 1;
999     quarter_decim_picture_buffer_desc_init_data.right_padding = MAX_SB_SIZE >> 1;
1000     quarter_decim_picture_buffer_desc_init_data.top_padding = MAX_SB_SIZE >> 1;
1001     quarter_decim_picture_buffer_desc_init_data.bot_padding = MAX_SB_SIZE >> 1;
1002     quarter_decim_picture_buffer_desc_init_data.split_mode = EB_FALSE;
1003 
1004     sixteenth_decim_picture_buffer_desc_init_data.max_width = scs_ptr->max_input_luma_width >> 2;
1005     sixteenth_decim_picture_buffer_desc_init_data.max_height = scs_ptr->max_input_luma_height >> 2;
1006     sixteenth_decim_picture_buffer_desc_init_data.bit_depth = scs_ptr->input_bit_depth;
1007     sixteenth_decim_picture_buffer_desc_init_data.buffer_enable_mask = PICTURE_BUFFER_DESC_LUMA_MASK;
1008     sixteenth_decim_picture_buffer_desc_init_data.left_padding = MAX_SB_SIZE >> 2;
1009     sixteenth_decim_picture_buffer_desc_init_data.right_padding = MAX_SB_SIZE >> 2;
1010     sixteenth_decim_picture_buffer_desc_init_data.top_padding = MAX_SB_SIZE >> 2;
1011     sixteenth_decim_picture_buffer_desc_init_data.bot_padding = MAX_SB_SIZE >> 2;
1012     sixteenth_decim_picture_buffer_desc_init_data.split_mode = EB_FALSE;
1013 
1014     eb_pa_reference_object_desc_init_data_structure.reference_picture_desc_init_data = reference_picture_buffer_desc_init_data;
1015     eb_pa_reference_object_desc_init_data_structure.quarter_picture_desc_init_data = quarter_decim_picture_buffer_desc_init_data;
1016     eb_pa_reference_object_desc_init_data_structure.sixteenth_picture_desc_init_data = sixteenth_decim_picture_buffer_desc_init_data;
1017 
1018     // Reference Picture Buffers
1019     return_error = eb_vp9_system_resource_ctor(
1020         &enc_handle_ptr->pa_reference_picture_pool_ptr_array[0],
1021         scs_ptr->pa_reference_picture_buffer_init_count,
1022         EB_PictureDecisionProcessInitCount,
1023         0,
1024         &enc_handle_ptr->pa_reference_picture_pool_producer_fifo_ptr_dbl_array[0],
1025         (EbFifo ***)EB_NULL,
1026         EB_FALSE,
1027         eb_vp9_pa_reference_object_ctor,
1028         &(eb_pa_reference_object_desc_init_data_structure));
1029     if (return_error == EB_ErrorInsufficientResources) {
1030         return EB_ErrorInsufficientResources;
1031     }
1032 
1033     // Set the SequenceControlSet Picture Pool Fifo Ptrs
1034     scs_ptr->encode_context_ptr->reference_picture_pool_fifo_ptr = (enc_handle_ptr->reference_picture_pool_producer_fifo_ptr_dbl_array[0])[0];
1035     scs_ptr->encode_context_ptr->pa_reference_picture_pool_fifo_ptr = (enc_handle_ptr->pa_reference_picture_pool_producer_fifo_ptr_dbl_array[0])[0];
1036 
1037     /************************************
1038      * System Resource Managers & Fifos
1039      ************************************/
1040 
1041      // EbBufferHeaderType Input
1042     return_error = eb_vp9_system_resource_ctor(
1043         &enc_handle_ptr->input_buffer_resource_ptr,
1044         scs_ptr->input_output_buffer_fifo_init_count,
1045         1,
1046         EB_ResourceCoordinationProcessInitCount,
1047         &enc_handle_ptr->input_buffer_producer_fifo_ptr_array,
1048         &enc_handle_ptr->input_buffer_consumer_fifo_ptr_array,
1049         EB_TRUE,
1050         eb_input_buffer_header_ctor,
1051         scs_ptr);
1052 
1053     if (return_error == EB_ErrorInsufficientResources) {
1054         return EB_ErrorInsufficientResources;
1055     }
1056     // EbBufferHeaderType Output Stream
1057     EB_MALLOC(EbSystemResource**, enc_handle_ptr->output_stream_buffer_resource_ptr_array, sizeof(EbSystemResource*) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
1058     EB_MALLOC(EbFifo***, enc_handle_ptr->output_stream_buffer_producer_fifo_ptr_dbl_array, sizeof(EbFifo**)          * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
1059     EB_MALLOC(EbFifo***, enc_handle_ptr->output_stream_buffer_consumer_fifo_ptr_dbl_array, sizeof(EbFifo**)          * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
1060 
1061     return_error = eb_vp9_system_resource_ctor(
1062         &enc_handle_ptr->output_stream_buffer_resource_ptr_array[0],
1063         scs_ptr->input_output_buffer_fifo_init_count + 6,
1064         scs_ptr->total_process_init_count,
1065         1,
1066         &enc_handle_ptr->output_stream_buffer_producer_fifo_ptr_dbl_array[0],
1067         &enc_handle_ptr->output_stream_buffer_consumer_fifo_ptr_dbl_array[0],
1068         EB_TRUE,
1069         eb_output_buffer_header_ctor,
1070         &scs_ptr->static_config);
1071 
1072     if (return_error == EB_ErrorInsufficientResources) {
1073         return EB_ErrorInsufficientResources;
1074     }
1075     if (scs_ptr->static_config.recon_file){
1076         // EbBufferHeaderType Output Recon
1077         EB_MALLOC(EbSystemResource**, enc_handle_ptr->output_recon_buffer_resource_ptr_array, sizeof(EbSystemResource*) * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
1078         EB_MALLOC(EbFifo***, enc_handle_ptr->output_recon_buffer_producer_fifo_ptr_dbl_array, sizeof(EbFifo**)          * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
1079         EB_MALLOC(EbFifo***, enc_handle_ptr->output_recon_buffer_consumer_fifo_ptr_dbl_array, sizeof(EbFifo**)          * enc_handle_ptr->encode_instance_total_count, EB_N_PTR);
1080 
1081         return_error = eb_vp9_system_resource_ctor(
1082             &enc_handle_ptr->output_recon_buffer_resource_ptr_array[0],
1083             scs_ptr->output_recon_buffer_fifo_init_count,
1084             EB_PacketizationProcessInitCount,
1085             1,
1086             &enc_handle_ptr->output_recon_buffer_producer_fifo_ptr_dbl_array[0],
1087             &enc_handle_ptr->output_recon_buffer_consumer_fifo_ptr_dbl_array[0],
1088             EB_TRUE,
1089             eb_output_recon_buffer_header_ctor,
1090             scs_ptr);
1091         if (return_error == EB_ErrorInsufficientResources) {
1092             return EB_ErrorInsufficientResources;
1093         }
1094     }
1095 
1096     // Resource Coordination Results
1097     {
1098         ResourceCoordinationResultInitData resource_coordination_result_init_data;
1099 
1100         return_error = eb_vp9_system_resource_ctor(
1101             &enc_handle_ptr->resource_coordination_results_resource_ptr,
1102             scs_ptr->resource_coordination_fifo_init_count,
1103             EB_ResourceCoordinationProcessInitCount,
1104             scs_ptr->picture_analysis_process_init_count,
1105             &enc_handle_ptr->resource_coordination_results_producer_fifo_ptr_array,
1106             &enc_handle_ptr->resource_coordination_results_consumer_fifo_ptr_array,
1107             EB_TRUE,
1108             eb_vp9_resource_coordination_result_ctor,
1109             &resource_coordination_result_init_data);
1110 
1111         if (return_error == EB_ErrorInsufficientResources) {
1112             return EB_ErrorInsufficientResources;
1113         }
1114     }
1115 
1116     // Picture Analysis Results
1117     {
1118         PictureAnalysisResultInitData picture_analysis_result_init_data;
1119 
1120         return_error = eb_vp9_system_resource_ctor(
1121             &enc_handle_ptr->picture_analysis_results_resource_ptr,
1122             scs_ptr->picture_analysis_fifo_init_count,
1123             scs_ptr->picture_analysis_process_init_count,
1124             EB_PictureDecisionProcessInitCount,
1125             &enc_handle_ptr->picture_analysis_results_producer_fifo_ptr_array,
1126             &enc_handle_ptr->picture_analysis_results_consumer_fifo_ptr_array,
1127             EB_TRUE,
1128             eb_vp9_picture_analysis_result_ctor,
1129             &picture_analysis_result_init_data);
1130         if (return_error == EB_ErrorInsufficientResources) {
1131             return EB_ErrorInsufficientResources;
1132         }
1133     }
1134 
1135     // Picture Decision Results
1136     {
1137         PictureDecisionResultInitData picture_decision_result_init_data;
1138 
1139         return_error = eb_vp9_system_resource_ctor(
1140             &enc_handle_ptr->picture_decision_results_resource_ptr,
1141             scs_ptr->picture_decision_fifo_init_count,
1142             EB_PictureDecisionProcessInitCount,
1143             scs_ptr->motion_estimation_process_init_count,
1144             &enc_handle_ptr->picture_decision_results_producer_fifo_ptr_array,
1145             &enc_handle_ptr->picture_decision_results_consumer_fifo_ptr_array,
1146             EB_TRUE,
1147             eb_vp9_picture_decision_result_ctor,
1148             &picture_decision_result_init_data);
1149         if (return_error == EB_ErrorInsufficientResources) {
1150             return EB_ErrorInsufficientResources;
1151         }
1152     }
1153 
1154     // Motion Estimation Results
1155     {
1156         MotionEstimationResultsInitData motion_estimation_result_init_data;
1157 
1158         return_error = eb_vp9_system_resource_ctor(
1159             &enc_handle_ptr->motion_estimation_results_resource_ptr,
1160             scs_ptr->motion_estimation_fifo_init_count,
1161             scs_ptr->motion_estimation_process_init_count,
1162             EB_InitialRateControlProcessInitCount,
1163             &enc_handle_ptr->motion_estimation_results_producer_fifo_ptr_array,
1164             &enc_handle_ptr->motion_estimation_results_consumer_fifo_ptr_array,
1165             EB_TRUE,
1166             eb_vp9_motion_estimation_results_ctor,
1167             &motion_estimation_result_init_data);
1168         if (return_error == EB_ErrorInsufficientResources) {
1169             return EB_ErrorInsufficientResources;
1170         }
1171     }
1172 
1173     // Initial Rate Control Results
1174     {
1175         InitialRateControlResultInitData initial_rate_control_result_init_data;
1176 
1177         return_error = eb_vp9_system_resource_ctor(
1178             &enc_handle_ptr->initial_rate_control_results_resource_ptr,
1179             scs_ptr->initial_rate_control_fifo_init_count,
1180             EB_InitialRateControlProcessInitCount,
1181             scs_ptr->source_based_operations_process_init_count,
1182             &enc_handle_ptr->initial_rate_control_results_producer_fifo_ptr_array,
1183             &enc_handle_ptr->initial_rate_control_results_consumer_fifo_ptr_array,
1184             EB_TRUE,
1185             eb_vp9_initial_eb_vp9_rate_control_results_ctor,
1186             &initial_rate_control_result_init_data);
1187 
1188         if (return_error == EB_ErrorInsufficientResources) {
1189             return EB_ErrorInsufficientResources;
1190         }
1191     }
1192 
1193     // Picture Demux Results
1194     {
1195         PictureResultInitData picture_result_init_data;
1196 
1197         return_error = eb_vp9_system_resource_ctor(
1198             &enc_handle_ptr->picture_demux_results_resource_ptr,
1199             scs_ptr->picture_demux_fifo_init_count,
1200             scs_ptr->source_based_operations_process_init_count + scs_ptr->enc_dec_process_init_count,
1201             EB_PictureManagerProcessInitCount,
1202             &enc_handle_ptr->picture_demux_results_producer_fifo_ptr_array,
1203             &enc_handle_ptr->picture_demux_results_consumer_fifo_ptr_array,
1204             EB_TRUE,
1205             eb_vp9_picture_results_ctor,
1206             &picture_result_init_data);
1207         if (return_error == EB_ErrorInsufficientResources) {
1208             return EB_ErrorInsufficientResources;
1209         }
1210     }
1211 
1212     // Rate Control Tasks
1213     {
1214         RateControlTasksInitData rate_control_tasks_init_data;
1215 
1216         return_error = eb_vp9_system_resource_ctor(
1217             &enc_handle_ptr->rate_control_tasks_resource_ptr,
1218             scs_ptr->rate_control_tasks_fifo_init_count,
1219             rate_control_port_total_count(),
1220             EB_RateControlProcessInitCount,
1221             &enc_handle_ptr->rate_control_tasks_producer_fifo_ptr_array,
1222             &enc_handle_ptr->rate_control_tasks_consumer_fifo_ptr_array,
1223             EB_TRUE,
1224             eb_vp9_rate_control_tasks_ctor,
1225             &rate_control_tasks_init_data);
1226         if (return_error == EB_ErrorInsufficientResources) {
1227             return EB_ErrorInsufficientResources;
1228         }
1229     }
1230 
1231     // Rate Control Results
1232     {
1233         RateControlResultsInitData rate_control_result_init_data;
1234 
1235         return_error = eb_vp9_system_resource_ctor(
1236             &enc_handle_ptr->rate_control_results_resource_ptr,
1237             scs_ptr->rate_control_fifo_init_count,
1238             EB_RateControlProcessInitCount,
1239             scs_ptr->mode_decision_configuration_process_init_count,
1240             &enc_handle_ptr->rate_control_results_producer_fifo_ptr_array,
1241             &enc_handle_ptr->rate_control_results_consumer_fifo_ptr_array,
1242             EB_TRUE,
1243             eb_vp9_rate_control_results_ctor,
1244             &rate_control_result_init_data);
1245         if (return_error == EB_ErrorInsufficientResources) {
1246             return EB_ErrorInsufficientResources;
1247         }
1248     }
1249 
1250     // EncDec Tasks
1251     {
1252         EncDecTasksInitData mode_decision_result_init_data;
1253         unsigned i;
1254 
1255         mode_decision_result_init_data.enc_dec_segment_row_count = 0;
1256 
1257         for (i = 0; i <= scs_ptr->hierarchical_levels; ++i) {
1258             mode_decision_result_init_data.enc_dec_segment_row_count = MAX(
1259                 mode_decision_result_init_data.enc_dec_segment_row_count,
1260                 scs_ptr->enc_dec_segment_row_count_array[i]);
1261         }
1262 
1263         return_error = eb_vp9_system_resource_ctor(
1264             &enc_handle_ptr->enc_dec_tasks_resource_ptr,
1265             scs_ptr->mode_decision_configuration_fifo_init_count,
1266             enc_dec_port_total_count(),
1267             scs_ptr->enc_dec_process_init_count,
1268             &enc_handle_ptr->enc_dec_tasks_producer_fifo_ptr_array,
1269             &enc_handle_ptr->enc_dec_tasks_consumer_fifo_ptr_array,
1270             EB_TRUE,
1271             eb_vp9_enc_dec_tasks_ctor,
1272             &mode_decision_result_init_data);
1273         if (return_error == EB_ErrorInsufficientResources) {
1274             return EB_ErrorInsufficientResources;
1275         }
1276     }
1277 
1278     // EncDec Results
1279     {
1280         EncDecResultsInitData enc_dec_result_init_data;
1281 
1282         return_error = eb_vp9_system_resource_ctor(
1283             &enc_handle_ptr->enc_dec_results_resource_ptr,
1284             scs_ptr->enc_dec_fifo_init_count,
1285             scs_ptr->enc_dec_process_init_count,
1286             scs_ptr->entropy_coding_process_init_count,
1287             &enc_handle_ptr->enc_dec_results_producer_fifo_ptr_array,
1288             &enc_handle_ptr->enc_dec_results_consumer_fifo_ptr_array,
1289             EB_TRUE,
1290             eb_vp9_enc_dec_results_ctor,
1291             &enc_dec_result_init_data);
1292         if (return_error == EB_ErrorInsufficientResources) {
1293             return EB_ErrorInsufficientResources;
1294         }
1295     }
1296 
1297     // Entropy Coding Results
1298     {
1299         EntropyCodingResultsInitData entropy_coding_result_init_data;
1300 
1301         return_error = eb_vp9_system_resource_ctor(
1302             &enc_handle_ptr->entropy_coding_results_resource_ptr,
1303             scs_ptr->entropy_coding_fifo_init_count,
1304             scs_ptr->entropy_coding_process_init_count,
1305             EB_PacketizationProcessInitCount,
1306             &enc_handle_ptr->entropy_coding_results_producer_fifo_ptr_array,
1307             &enc_handle_ptr->entropy_coding_results_consumer_fifo_ptr_array,
1308             EB_TRUE,
1309             eb_vp9_entropy_coding_results_ctor,
1310             &entropy_coding_result_init_data);
1311         if (return_error == EB_ErrorInsufficientResources) {
1312             return EB_ErrorInsufficientResources;
1313         }
1314     }
1315 
1316     /************************************
1317      * App Callbacks
1318      ************************************/
1319     scs_ptr->encode_context_ptr->app_callback_ptr = enc_handle_ptr->app_callback_ptr_array[0];
1320 
1321     // Output Buffer Fifo Ptrs
1322     scs_ptr->encode_context_ptr->stream_output_fifo_ptr = (enc_handle_ptr->output_stream_buffer_producer_fifo_ptr_dbl_array[0])[0];
1323     if (scs_ptr->static_config.recon_file)
1324         scs_ptr->encode_context_ptr->recon_output_fifo_ptr = (enc_handle_ptr->output_recon_buffer_producer_fifo_ptr_dbl_array[0])[0];
1325     /************************************
1326      * Contexts
1327      ************************************/
1328 
1329      // Resource Coordination Context
1330     return_error = eb_vp9_resource_coordination_context_ctor(
1331         (ResourceCoordinationContext**)&enc_handle_ptr->resource_coordination_context_ptr,
1332         enc_handle_ptr->input_buffer_consumer_fifo_ptr_array[0],
1333         enc_handle_ptr->resource_coordination_results_producer_fifo_ptr_array[0],
1334         enc_handle_ptr->picture_parent_control_set_pool_producer_fifo_ptr_dbl_array[0],//ResourceCoordination works with ParentPCS
1335         enc_handle_ptr->sequence_control_set_instance_array,
1336         enc_handle_ptr->sequence_control_set_pool_producer_fifo_ptr_array[0],
1337         enc_handle_ptr->app_callback_ptr_array,
1338         enc_handle_ptr->compute_segments_total_count_array,
1339         enc_handle_ptr->encode_instance_total_count);
1340 
1341     if (return_error == EB_ErrorInsufficientResources) {
1342         return EB_ErrorInsufficientResources;
1343     }
1344     // Picture Analysis Context
1345     EB_MALLOC(EbPtr*, enc_handle_ptr->picture_analysis_context_ptr_array, sizeof(EbPtr) * scs_ptr->picture_analysis_process_init_count, EB_N_PTR);
1346 
1347     for (process_index = 0; process_index < scs_ptr->picture_analysis_process_init_count; ++process_index) {
1348 
1349         EbPictureBufferDescInitData  picture_buffer_desc_conf;
1350         picture_buffer_desc_conf.max_width = scs_ptr->max_input_luma_width;
1351         picture_buffer_desc_conf.max_height = scs_ptr->max_input_luma_height;
1352         picture_buffer_desc_conf.bit_depth = EB_8BIT;
1353         picture_buffer_desc_conf.buffer_enable_mask = PICTURE_BUFFER_DESC_Y_FLAG;
1354         picture_buffer_desc_conf.left_padding = 0;
1355         picture_buffer_desc_conf.right_padding = 0;
1356         picture_buffer_desc_conf.top_padding = 0;
1357         picture_buffer_desc_conf.bot_padding = 0;
1358         picture_buffer_desc_conf.split_mode = EB_FALSE;
1359 
1360         return_error = eb_vp9_picture_analysis_context_ctor(
1361             &picture_buffer_desc_conf,
1362             EB_TRUE,
1363             (PictureAnalysisContext**)&enc_handle_ptr->picture_analysis_context_ptr_array[process_index],
1364             enc_handle_ptr->resource_coordination_results_consumer_fifo_ptr_array[process_index],
1365             enc_handle_ptr->picture_analysis_results_producer_fifo_ptr_array[process_index],
1366             ((scs_ptr->max_input_luma_width + MAX_SB_SIZE_MINUS_1) / MAX_SB_SIZE) *
1367             ((scs_ptr->max_input_luma_height + MAX_SB_SIZE_MINUS_1) / MAX_SB_SIZE));
1368 
1369         if (return_error == EB_ErrorInsufficientResources) {
1370             return EB_ErrorInsufficientResources;
1371         }
1372     }
1373 
1374     // Picture Decision Context
1375     return_error = eb_vp9_picture_decision_context_ctor(
1376         (PictureDecisionContext**)&enc_handle_ptr->picture_decision_context_ptr,
1377         enc_handle_ptr->picture_analysis_results_consumer_fifo_ptr_array[0],
1378         enc_handle_ptr->picture_decision_results_producer_fifo_ptr_array[0]);
1379     if (return_error == EB_ErrorInsufficientResources) {
1380         return EB_ErrorInsufficientResources;
1381     }
1382 
1383     // Motion Analysis Context
1384     EB_MALLOC(EbPtr*, enc_handle_ptr->motion_estimation_context_ptr_array, sizeof(EbPtr) * scs_ptr->motion_estimation_process_init_count, EB_N_PTR);
1385 
1386     for (process_index = 0; process_index < scs_ptr->motion_estimation_process_init_count; ++process_index) {
1387 
1388         return_error = eb_vp9_motion_estimation_context_ctor(
1389             (MotionEstimationContext**)&enc_handle_ptr->motion_estimation_context_ptr_array[process_index],
1390             enc_handle_ptr->picture_decision_results_consumer_fifo_ptr_array[process_index],
1391             enc_handle_ptr->motion_estimation_results_producer_fifo_ptr_array[process_index]);
1392 
1393         if (return_error == EB_ErrorInsufficientResources) {
1394             return EB_ErrorInsufficientResources;
1395         }
1396     }
1397 
1398     // Initial Rate Control Context
1399     return_error = eb_vp9_initial_eb_vp9_rate_control_context_ctor(
1400         (InitialRateControlContext**)&enc_handle_ptr->initial_rate_control_context_ptr,
1401         enc_handle_ptr->motion_estimation_results_consumer_fifo_ptr_array[0],
1402         enc_handle_ptr->initial_rate_control_results_producer_fifo_ptr_array[0]);
1403     if (return_error == EB_ErrorInsufficientResources) {
1404         return EB_ErrorInsufficientResources;
1405     }
1406 
1407     // Source Based Operations Context
1408     EB_MALLOC(EbPtr*, enc_handle_ptr->source_based_operations_context_ptr_array, sizeof(EbPtr) * scs_ptr->source_based_operations_process_init_count, EB_N_PTR);
1409 
1410     for (process_index = 0; process_index < scs_ptr->source_based_operations_process_init_count; ++process_index) {
1411         return_error = eb_vp9_source_based_operations_context_ctor(
1412             (SourceBasedOperationsContext**)&enc_handle_ptr->source_based_operations_context_ptr_array[process_index],
1413             enc_handle_ptr->initial_rate_control_results_consumer_fifo_ptr_array[process_index],
1414             enc_handle_ptr->picture_demux_results_producer_fifo_ptr_array[process_index]);
1415         if (return_error == EB_ErrorInsufficientResources) {
1416             return EB_ErrorInsufficientResources;
1417         }
1418     }
1419 
1420     // Picture Manager Context
1421     return_error = eb_vp9_picture_manager_context_ctor(
1422         (PictureManagerContext**)&enc_handle_ptr->picture_manager_context_ptr,
1423         enc_handle_ptr->picture_demux_results_consumer_fifo_ptr_array[0],
1424         enc_handle_ptr->rate_control_tasks_producer_fifo_ptr_array[rate_control_port_lookup(RATE_CONTROL_INPUT_PORT_PICTURE_MANAGER, 0)],
1425         enc_handle_ptr->picture_control_set_pool_producer_fifo_ptr_dbl_array[0]);//The Child PCS Pool here
1426     if (return_error == EB_ErrorInsufficientResources) {
1427         return EB_ErrorInsufficientResources;
1428     }
1429     // Rate Control Context
1430     return_error = eb_vp9_rate_control_context_ctor(
1431         (RateControlContext**)&enc_handle_ptr->rate_control_context_ptr,
1432         enc_handle_ptr->rate_control_tasks_consumer_fifo_ptr_array[0],
1433         enc_handle_ptr->rate_control_results_producer_fifo_ptr_array[0],
1434         scs_ptr->intra_period);
1435     if (return_error == EB_ErrorInsufficientResources) {
1436         return EB_ErrorInsufficientResources;
1437     }
1438 
1439     // Mode Decision Configuration Contexts
1440     {
1441         // Mode Decision Configuration Contexts
1442         EB_MALLOC(EbPtr*, enc_handle_ptr->mode_decision_configuration_context_ptr_array, sizeof(EbPtr) * scs_ptr->mode_decision_configuration_process_init_count, EB_N_PTR);
1443 
1444         for (process_index = 0; process_index < scs_ptr->mode_decision_configuration_process_init_count; ++process_index) {
1445             return_error = eb_vp9_mode_decision_configuration_context_ctor(
1446                 (ModeDecisionConfigurationContext**)&enc_handle_ptr->mode_decision_configuration_context_ptr_array[process_index],
1447                 enc_handle_ptr->rate_control_results_consumer_fifo_ptr_array[process_index],
1448 
1449                 enc_handle_ptr->enc_dec_tasks_producer_fifo_ptr_array[enc_dec_port_lookup(ENCDEC_INPUT_PORT_MDC, process_index)],
1450                 ((scs_ptr->max_input_luma_width + MAX_SB_SIZE_MINUS_1) / MAX_SB_SIZE) *
1451                 ((scs_ptr->max_input_luma_height + MAX_SB_SIZE_MINUS_1) / MAX_SB_SIZE));
1452 
1453             if (return_error == EB_ErrorInsufficientResources) {
1454                 return EB_ErrorInsufficientResources;
1455             }
1456         }
1457     }
1458 
1459     maxpicture_width = 0;
1460     if (maxpicture_width < scs_ptr->max_input_luma_width) {
1461         maxpicture_width = scs_ptr->max_input_luma_width;
1462     }
1463 
1464     // EncDec Contexts
1465     EB_MALLOC(EbPtr*, enc_handle_ptr->enc_dec_context_ptr_array, sizeof(EbPtr) * scs_ptr->enc_dec_process_init_count, EB_N_PTR);
1466 
1467     for (process_index = 0; process_index < scs_ptr->enc_dec_process_init_count; ++process_index) {
1468         return_error = eb_vp9_enc_dec_context_ctor(
1469             (EncDecContext**)&enc_handle_ptr->enc_dec_context_ptr_array[process_index],
1470             enc_handle_ptr->enc_dec_tasks_consumer_fifo_ptr_array[process_index],
1471             enc_handle_ptr->enc_dec_results_producer_fifo_ptr_array[process_index],
1472             enc_handle_ptr->enc_dec_tasks_producer_fifo_ptr_array[enc_dec_port_lookup(ENCDEC_INPUT_PORT_ENCDEC, process_index)],
1473             enc_handle_ptr->picture_demux_results_producer_fifo_ptr_array[1 + process_index]);
1474 
1475         if (return_error == EB_ErrorInsufficientResources) {
1476             return EB_ErrorInsufficientResources;
1477         }
1478     }
1479 
1480     // Entropy Coding Contexts
1481     EB_MALLOC(EbPtr*, enc_handle_ptr->entropy_coding_context_ptr_array, sizeof(EbPtr) * scs_ptr->entropy_coding_process_init_count, EB_N_PTR);
1482 
1483     for (process_index = 0; process_index < scs_ptr->entropy_coding_process_init_count; ++process_index) {
1484         return_error = eb_vp9_entropy_coding_context_ctor(
1485             (EntropyCodingContext**)&enc_handle_ptr->entropy_coding_context_ptr_array[process_index],
1486             enc_handle_ptr->enc_dec_results_consumer_fifo_ptr_array[process_index],
1487             enc_handle_ptr->entropy_coding_results_producer_fifo_ptr_array[process_index],
1488             enc_handle_ptr->rate_control_tasks_producer_fifo_ptr_array[rate_control_port_lookup(RATE_CONTROL_INPUT_PORT_ENTROPY_CODING, process_index)],
1489             is16bit);
1490         if (return_error == EB_ErrorInsufficientResources) {
1491             return EB_ErrorInsufficientResources;
1492         }
1493     }
1494 
1495     // Packetization Context
1496     return_error = eb_vp9_packetization_context_ctor(
1497         (PacketizationContext**)&enc_handle_ptr->packetization_context_ptr,
1498         enc_handle_ptr->entropy_coding_results_consumer_fifo_ptr_array[0],
1499         enc_handle_ptr->rate_control_tasks_producer_fifo_ptr_array[rate_control_port_lookup(RATE_CONTROL_INPUT_PORT_PACKETIZATION, 0)]);
1500 
1501     if (return_error == EB_ErrorInsufficientResources) {
1502         return EB_ErrorInsufficientResources;
1503     }
1504     /************************************
1505      * Thread Handles
1506      ************************************/
1507     EbSvtVp9EncConfiguration   *config_ptr = &scs_ptr->static_config;
1508     eb_set_thread_management_parameters(config_ptr);
1509 
1510     // Resource Coordination
1511     EB_CREATETHREAD(EbHandle, enc_handle_ptr->resource_coordination_thread_handle, sizeof(EbHandle), EB_THREAD, eb_vp9_resource_coordination_kernel, enc_handle_ptr->resource_coordination_context_ptr);
1512 
1513     // Picture Analysis
1514     EB_MALLOC(EbHandle*, enc_handle_ptr->picture_analysis_thread_handle_array, sizeof(EbHandle) * scs_ptr->picture_analysis_process_init_count, EB_N_PTR);
1515 
1516     for (process_index = 0; process_index < scs_ptr->picture_analysis_process_init_count; ++process_index) {
1517         EB_CREATETHREAD(EbHandle, enc_handle_ptr->picture_analysis_thread_handle_array[process_index], sizeof(EbHandle), EB_THREAD, eb_vp9_picture_analysis_kernel, enc_handle_ptr->picture_analysis_context_ptr_array[process_index]);
1518     }
1519 
1520     // Picture Decision
1521     EB_CREATETHREAD(EbHandle, enc_handle_ptr->picture_decision_thread_handle, sizeof(EbHandle), EB_THREAD, eb_vp9_picture_decision_kernel, enc_handle_ptr->picture_decision_context_ptr);
1522 
1523     // Motion Estimation
1524     EB_MALLOC(EbHandle*, enc_handle_ptr->motion_estimation_thread_handle_array, sizeof(EbHandle) * scs_ptr->motion_estimation_process_init_count, EB_N_PTR);
1525 
1526     for (process_index = 0; process_index < scs_ptr->motion_estimation_process_init_count; ++process_index) {
1527         EB_CREATETHREAD(EbHandle, enc_handle_ptr->motion_estimation_thread_handle_array[process_index], sizeof(EbHandle), EB_THREAD, eb_vp9_motion_estimation_kernel, enc_handle_ptr->motion_estimation_context_ptr_array[process_index]);
1528     }
1529 
1530     // Initial Rate Control
1531     EB_CREATETHREAD(EbHandle, enc_handle_ptr->initial_rate_control_thread_handle, sizeof(EbHandle), EB_THREAD, eb_vp9_initial_eb_vp9_rate_control_kernel, enc_handle_ptr->initial_rate_control_context_ptr);
1532 
1533     // Source Based Oprations
1534     EB_MALLOC(EbHandle*, enc_handle_ptr->source_based_operations_thread_handle_array, sizeof(EbHandle) * scs_ptr->source_based_operations_process_init_count, EB_N_PTR);
1535 
1536     for (process_index = 0; process_index < scs_ptr->source_based_operations_process_init_count; ++process_index) {
1537         EB_CREATETHREAD(EbHandle, enc_handle_ptr->source_based_operations_thread_handle_array[process_index], sizeof(EbHandle), EB_THREAD, eb_vp9_source_based_operations_kernel, enc_handle_ptr->source_based_operations_context_ptr_array[process_index]);
1538     }
1539 
1540     // Picture Manager
1541     EB_CREATETHREAD(EbHandle, enc_handle_ptr->picture_manager_thread_handle, sizeof(EbHandle), EB_THREAD, eb_vp9_PictureManagerKernel, enc_handle_ptr->picture_manager_context_ptr);
1542 
1543     // Rate Control
1544     EB_CREATETHREAD(EbHandle, enc_handle_ptr->rate_control_thread_handle, sizeof(EbHandle), EB_THREAD, eb_vp9_rate_control_kernel, enc_handle_ptr->rate_control_context_ptr);
1545 
1546     // Mode Decision Configuration Process
1547     EB_MALLOC(EbHandle*, enc_handle_ptr->mode_decision_configuration_thread_handle_array, sizeof(EbHandle) * scs_ptr->mode_decision_configuration_process_init_count, EB_N_PTR);
1548 
1549     for (process_index = 0; process_index < scs_ptr->mode_decision_configuration_process_init_count; ++process_index) {
1550         EB_CREATETHREAD(EbHandle, enc_handle_ptr->mode_decision_configuration_thread_handle_array[process_index], sizeof(EbHandle), EB_THREAD, eb_vp9_mode_decision_configuration_kernel, enc_handle_ptr->mode_decision_configuration_context_ptr_array[process_index]);
1551     }
1552 
1553     // EncDec Process
1554     EB_MALLOC(EbHandle*, enc_handle_ptr->enc_dec_thread_handle_array, sizeof(EbHandle) * scs_ptr->enc_dec_process_init_count, EB_N_PTR);
1555 
1556     for (process_index = 0; process_index < scs_ptr->enc_dec_process_init_count; ++process_index) {
1557         EB_CREATETHREAD(EbHandle, enc_handle_ptr->enc_dec_thread_handle_array[process_index], sizeof(EbHandle), EB_THREAD, eb_vp9_enc_dec_kernel, enc_handle_ptr->enc_dec_context_ptr_array[process_index]);
1558     }
1559 
1560     // Entropy Coding Process
1561     EB_MALLOC(EbHandle*, enc_handle_ptr->entropy_coding_thread_handle_array, sizeof(EbHandle) * scs_ptr->entropy_coding_process_init_count, EB_N_PTR);
1562 
1563     for (process_index = 0; process_index < scs_ptr->entropy_coding_process_init_count; ++process_index) {
1564         EB_CREATETHREAD(EbHandle, enc_handle_ptr->entropy_coding_thread_handle_array[process_index], sizeof(EbHandle), EB_THREAD, eb_vp9_entropy_coding_kernel, enc_handle_ptr->entropy_coding_context_ptr_array[process_index]);
1565     }
1566 
1567     // Packetization
1568     EB_CREATETHREAD(EbHandle, enc_handle_ptr->packetization_thread_handle, sizeof(EbHandle), EB_THREAD, eb_vp9_packetization_kernel, enc_handle_ptr->packetization_context_ptr);
1569 
1570 #if DISPLAY_MEMORY
1571     EB_MEMORY();
1572 #endif
1573     return return_error;
1574 }
1575 
1576 /**********************************
1577  * DeInitialize Encoder Library
1578  **********************************/
1579 #if __unix__
1580 __attribute__((visibility("default")))
1581 #endif
eb_vp9_deinit_encoder(EbComponentType * svt_enc_component)1582 EB_API EbErrorType  eb_vp9_deinit_encoder(EbComponentType *svt_enc_component)
1583 {
1584     EbEncHandle *enc_handle_ptr = (EbEncHandle*)svt_enc_component->p_component_private;
1585     EbErrorType  return_error = EB_ErrorNone;
1586     int32_t              ptr_index = 0;
1587     EbMemoryMapEntry*   memory_entry = (EbMemoryMapEntry*)EB_NULL;
1588     if (enc_handle_ptr) {
1589         if (enc_handle_ptr->memory_map_index) {
1590             // Loop through the ptr table and free all malloc'd pointers per channel
1591             for (ptr_index = (enc_handle_ptr->memory_map_index) - 1; ptr_index >= 0; --ptr_index) {
1592                 memory_entry = &enc_handle_ptr->memory_map[ptr_index];
1593                 switch (memory_entry->ptr_type) {
1594                 case EB_N_PTR:
1595                     free(memory_entry->ptr);
1596                     break;
1597                 case EB_A_PTR:
1598 #ifdef _WIN32
1599                     _aligned_free(memory_entry->ptr);
1600 #else
1601                     free(memory_entry->ptr);
1602 #endif
1603                     break;
1604                 case EB_SEMAPHORE:
1605                     eb_vp9_destroy_semaphore(memory_entry->ptr);
1606                     break;
1607                 case EB_THREAD:
1608                     eb_vp9_destroy_thread(memory_entry->ptr);
1609                     break;
1610                 case EB_MUTEX:
1611                     eb_vp9_destroy_mutex(memory_entry->ptr);
1612                     break;
1613                 default:
1614                     return_error = EB_ErrorMax;
1615                     break;
1616                 }
1617             }
1618             if (enc_handle_ptr->memory_map != (EbMemoryMapEntry*)NULL) {
1619                 free(enc_handle_ptr->memory_map);
1620             }
1621 
1622             //(void)(enc_handle_ptr);
1623         }
1624     }
1625     return return_error;
1626 }
1627 
1628 /**********************************
1629  * GetHandle
1630  **********************************/
1631 #if defined(__unix__) || defined(__APPLE__)
1632 __attribute__((visibility("default")))
1633 #endif
eb_vp9_svt_release_out_buffer(EbBufferHeaderType ** p_buffer)1634 EB_API void eb_vp9_svt_release_out_buffer(
1635     EbBufferHeaderType  **p_buffer)
1636 {
1637     if (p_buffer && (*p_buffer)->wrapper_ptr)
1638         // Release out put buffer back into the pool
1639         eb_vp9_release_object((EbObjectWrapper  *)(*p_buffer)->wrapper_ptr);
1640     return;
1641 }
1642 
1643 /**********************************
1644 Set Default Library Params
1645 **********************************/
eb_vp9_svt_enc_init_parameter(EbSvtVp9EncConfiguration * config_ptr)1646 EbErrorType eb_vp9_svt_enc_init_parameter(
1647     EbSvtVp9EncConfiguration * config_ptr){
1648 
1649     EbErrorType                  return_error = EB_ErrorNone;
1650 
1651     if (!config_ptr) {
1652         SVT_LOG("SVT [ERROR]: The EbSvtVp9EncConfiguration structure is empty! \n");
1653         return EB_ErrorBadParameter;
1654     }
1655 
1656     config_ptr->frame_rate = 30 << 16;
1657     config_ptr->frame_rate_numerator = 0;
1658     config_ptr->frame_rate_denominator = 0;
1659     config_ptr->encoder_bit_depth = 8;
1660     config_ptr->source_width = 0;
1661     config_ptr->source_height = 0;
1662 
1663     config_ptr->qp = 50;
1664     config_ptr->use_qp_file = EB_FALSE;
1665     config_ptr->rate_control_mode = 0;
1666     config_ptr->target_bit_rate = 7000000;
1667     config_ptr->max_qp_allowed = MAX_QP_VALUE;
1668     config_ptr->min_qp_allowed = 0;
1669     config_ptr->base_layer_switch_mode = 0;
1670     config_ptr->enc_mode = 3;
1671     config_ptr->intra_period = 31;
1672     config_ptr->pred_structure = EB_PRED_RANDOM_ACCESS;
1673     config_ptr->loop_filter = EB_TRUE;
1674     config_ptr->use_default_me_hme = EB_TRUE;
1675     config_ptr->enable_hme_flag = EB_TRUE;
1676     config_ptr->search_area_width = 16;
1677     config_ptr->search_area_height = 7;
1678 
1679     // Bitstream options
1680     //config_ptr->codeVpsSpsPps = 0;
1681     //config_ptr->codeEosNal = 0;
1682 
1683     // Annex A parameters
1684     config_ptr->profile = 0;
1685     config_ptr->level = 0;
1686 
1687     // Latency
1688     config_ptr->injector_frame_rate = 60 << 16;
1689     config_ptr->speed_control_flag = 0;
1690 
1691     // ASM Type
1692     config_ptr->asm_type = 1;
1693 
1694     // Channel info
1695     //config_ptr->logicalProcessors = 0;
1696     //config_ptr->target_socket = -1;
1697     config_ptr->channel_id = 0;
1698     config_ptr->active_channel_count = 1;
1699 
1700     // Debug info
1701     config_ptr->recon_file = 0;
1702 
1703     return return_error;
1704 }
1705 /**********************************
1706 * GetHandle
1707 **********************************/
1708 #if defined(__unix__) || defined(__APPLE__)
1709 __attribute__((visibility("default")))
1710 #endif
eb_vp9_svt_init_handle(EbComponentType ** p_handle,void * p_app_data,EbSvtVp9EncConfiguration * config_ptr)1711 EB_API EbErrorType eb_vp9_svt_init_handle(
1712     EbComponentType          **p_handle,      // Function to be called in the future for manipulating the component
1713     void                      *p_app_data,
1714     EbSvtVp9EncConfiguration  *config_ptr) {   // Pointer passed back to the client during callbacks
1715 
1716     EbErrorType           return_error = EB_ErrorNone;
1717 
1718     *p_handle = (EbComponentType*)malloc(sizeof(EbComponentType));
1719 
1720     if (*p_handle != (EbComponentType*)NULL) {
1721 
1722         // Init Component OS objects (threads, semaphores, etc.)
1723         // also links the various Component control functions
1724         return_error = init_svt_vp9_encoder_handle(*p_handle);
1725 
1726         if (return_error == EB_ErrorNone) {
1727             ((EbComponentType*)(*p_handle))->p_application_private = p_app_data;
1728 
1729         }
1730         else if (return_error == EB_ErrorInsufficientResources) {
1731             eb_vp9_deinit_encoder((EbComponentType*)NULL);
1732             *p_handle = (EbComponentType*)NULL;
1733         }
1734         else {
1735             return_error = EB_ErrorInvalidComponent;
1736         }
1737     }
1738     else {
1739         SVT_LOG("Error: Component Struct Malloc Failed\n");
1740         return_error = EB_ErrorInsufficientResources;
1741     }
1742     return_error = eb_vp9_svt_enc_init_parameter(config_ptr);
1743 
1744     return return_error;
1745 }
1746 
1747 /**********************************
1748 * Encoder Componenet DeInit
1749 **********************************/
eb_svt_enc_component_de_init(EbComponentType * svt_enc_component)1750 static EbErrorType eb_svt_enc_component_de_init(
1751         EbComponentType  *svt_enc_component)
1752 {
1753     EbErrorType       return_error = EB_ErrorNone;
1754 
1755     if (svt_enc_component->p_component_private) {
1756         free((EbEncHandle *)svt_enc_component->p_component_private);
1757     }
1758     else {
1759         return_error = EB_ErrorUndefined;
1760     }
1761 
1762     return return_error;
1763 }
1764 
1765 /**********************************
1766 * eb_deinit_handle
1767 **********************************/
1768 #if defined(__unix__) || defined(__APPLE__)
1769 __attribute__((visibility("default")))
1770 #endif
eb_vp9_deinit_handle(EbComponentType * svt_enc_component)1771 EB_API EbErrorType eb_vp9_deinit_handle(
1772     EbComponentType  *svt_enc_component)
1773 {
1774     EbErrorType return_error = EB_ErrorNone;
1775 
1776     if (svt_enc_component) {
1777         return_error = eb_svt_enc_component_de_init(svt_enc_component);
1778 
1779         free(svt_enc_component);
1780     }
1781     else {
1782         return_error = EB_ErrorInvalidComponent;
1783     }
1784 
1785     return return_error;
1786 }
1787 
eb_vp9_set_parent_pcs(EbSvtVp9EncConfiguration * config)1788 uint32_t eb_vp9_set_parent_pcs(EbSvtVp9EncConfiguration*   config) {
1789 
1790     uint32_t fps = (uint32_t)((config->frame_rate > 1000) ? config->frame_rate >> 16 : config->frame_rate);
1791 
1792     fps = fps > 120 ? 120 : fps;
1793     fps = fps < 24 ? 24 : fps;
1794 
1795     return ((fps * 5) >> 2); // 1.25 sec worth of internal buffering
1796 }
1797 
eb_vp9_load_default_buffer_configuration_settings(SequenceControlSet * sequence_control_set_ptr)1798 void eb_vp9_load_default_buffer_configuration_settings(
1799     SequenceControlSet         *sequence_control_set_ptr){
1800 
1801     uint32_t me_seg_h       = (((sequence_control_set_ptr->max_input_luma_height + 32) / MAX_SB_SIZE) < 6) ? 1 : 6;
1802     uint32_t me_seg_w       = (((sequence_control_set_ptr->max_input_luma_width + 32) / MAX_SB_SIZE) < 10) ? 1 : 10;
1803 
1804     uint32_t enc_dec_seg_h  = ((sequence_control_set_ptr->max_input_luma_height + 32) / MAX_SB_SIZE);
1805     uint32_t enc_dec_seg_w  = ((sequence_control_set_ptr->max_input_luma_width + 32) / MAX_SB_SIZE);
1806     uint32_t input_pic      = eb_vp9_set_parent_pcs(&sequence_control_set_ptr->static_config);
1807 
1808     unsigned int lp_count = get_num_cores();
1809     unsigned int core_count = lp_count;
1810 #if defined(_WIN32) || defined(__unix__)
1811     if (sequence_control_set_ptr->static_config.target_socket != -1)
1812         core_count /= eb_vp9_num_groups;
1813     if (sequence_control_set_ptr->static_config.logical_processors != 0)
1814         core_count = sequence_control_set_ptr->static_config.logical_processors < core_count ?
1815         sequence_control_set_ptr->static_config.logical_processors : core_count;
1816 #endif
1817 
1818 #ifdef _WIN32
1819     //Handle special case on Windows
1820     //By default, on Windows an application is constrained to a single group
1821     if (sequence_control_set_ptr->static_config.target_socket == -1 &&
1822         sequence_control_set_ptr->static_config.logical_processors == 0)
1823         core_count /= eb_vp9_num_groups;
1824 
1825     //Affininty can only be set by group on Windows.
1826     //Run on both sockets if -lp is larger than logical processor per group.
1827     if (sequence_control_set_ptr->static_config.target_socket == -1 &&
1828         sequence_control_set_ptr->static_config.logical_processors > lp_count / eb_vp9_num_groups)
1829         core_count = lp_count;
1830 #endif
1831 
1832     // ME segments
1833     sequence_control_set_ptr->me_segment_row_count_array[0] = me_seg_h;
1834     sequence_control_set_ptr->me_segment_row_count_array[1] = me_seg_h;
1835     sequence_control_set_ptr->me_segment_row_count_array[2] = me_seg_h;
1836     sequence_control_set_ptr->me_segment_row_count_array[3] = me_seg_h;
1837     sequence_control_set_ptr->me_segment_row_count_array[4] = me_seg_h;
1838     sequence_control_set_ptr->me_segment_row_count_array[5] = me_seg_h;
1839 
1840     sequence_control_set_ptr->me_segment_column_count_array[0] = me_seg_w;
1841     sequence_control_set_ptr->me_segment_column_count_array[1] = me_seg_w;
1842     sequence_control_set_ptr->me_segment_column_count_array[2] = me_seg_w;
1843     sequence_control_set_ptr->me_segment_column_count_array[3] = me_seg_w;
1844     sequence_control_set_ptr->me_segment_column_count_array[4] = me_seg_w;
1845     sequence_control_set_ptr->me_segment_column_count_array[5] = me_seg_w;
1846     // EncDec segments
1847     sequence_control_set_ptr->enc_dec_segment_row_count_array[0] = enc_dec_seg_h;
1848     sequence_control_set_ptr->enc_dec_segment_row_count_array[1] = enc_dec_seg_h;
1849     sequence_control_set_ptr->enc_dec_segment_row_count_array[2] = enc_dec_seg_h;
1850     sequence_control_set_ptr->enc_dec_segment_row_count_array[3] = enc_dec_seg_h;
1851     sequence_control_set_ptr->enc_dec_segment_row_count_array[4] = enc_dec_seg_h;
1852     sequence_control_set_ptr->enc_dec_segment_row_count_array[5] = enc_dec_seg_h;
1853 
1854     sequence_control_set_ptr->enc_dec_segment_col_count_array[0] = enc_dec_seg_w;
1855     sequence_control_set_ptr->enc_dec_segment_col_count_array[1] = enc_dec_seg_w;
1856     sequence_control_set_ptr->enc_dec_segment_col_count_array[2] = enc_dec_seg_w;
1857     sequence_control_set_ptr->enc_dec_segment_col_count_array[3] = enc_dec_seg_w;
1858     sequence_control_set_ptr->enc_dec_segment_col_count_array[4] = enc_dec_seg_w;
1859     sequence_control_set_ptr->enc_dec_segment_col_count_array[5] = enc_dec_seg_w;
1860 
1861     //#====================== Data Structures and Picture Buffers ======================
1862     sequence_control_set_ptr->input_output_buffer_fifo_init_count       = input_pic + SCD_LAD + sequence_control_set_ptr->look_ahead_distance;
1863     sequence_control_set_ptr->picture_control_set_pool_init_count       = sequence_control_set_ptr->input_output_buffer_fifo_init_count;
1864     sequence_control_set_ptr->picture_control_set_pool_init_count_child = MAX(MIN(2, core_count / 2), core_count / 6);
1865     sequence_control_set_ptr->reference_picture_buffer_init_count       = MAX((uint32_t)(input_pic >> 1),
1866         (uint32_t)((1 << sequence_control_set_ptr->hierarchical_levels) + 2)) +
1867         sequence_control_set_ptr->look_ahead_distance + SCD_LAD;
1868     sequence_control_set_ptr->pa_reference_picture_buffer_init_count    = MAX((uint32_t)(input_pic >> 1),
1869         (uint32_t)((1 << sequence_control_set_ptr->hierarchical_levels) + 2)) +
1870         sequence_control_set_ptr->look_ahead_distance + SCD_LAD;
1871     sequence_control_set_ptr->output_recon_buffer_fifo_init_count       = sequence_control_set_ptr->reference_picture_buffer_init_count;
1872 
1873     //#====================== Inter process Fifos ======================
1874     sequence_control_set_ptr->resource_coordination_fifo_init_count       = 300;
1875     sequence_control_set_ptr->picture_analysis_fifo_init_count            = 300;
1876     sequence_control_set_ptr->picture_decision_fifo_init_count            = 300;
1877     sequence_control_set_ptr->initial_rate_control_fifo_init_count        = 300;
1878     sequence_control_set_ptr->picture_demux_fifo_init_count               = 300;
1879     sequence_control_set_ptr->rate_control_tasks_fifo_init_count          = 300;
1880     sequence_control_set_ptr->rate_control_fifo_init_count                = 301;
1881     sequence_control_set_ptr->mode_decision_configuration_fifo_init_count = 300;
1882     sequence_control_set_ptr->motion_estimation_fifo_init_count           = 300;
1883     sequence_control_set_ptr->entropy_coding_fifo_init_count              = 300;
1884     sequence_control_set_ptr->enc_dec_fifo_init_count                     = 300;
1885 
1886     //#====================== Processes number ======================
1887     sequence_control_set_ptr->total_process_init_count = 0;
1888     sequence_control_set_ptr->total_process_init_count += (sequence_control_set_ptr->picture_analysis_process_init_count            = MAX(MIN(15, core_count), core_count / 6));
1889     sequence_control_set_ptr->total_process_init_count += (sequence_control_set_ptr->motion_estimation_process_init_count           = MAX(MIN(20, core_count), core_count / 3));
1890     sequence_control_set_ptr->total_process_init_count += (sequence_control_set_ptr->source_based_operations_process_init_count     = MAX(MIN(3, core_count), core_count / 12));
1891     sequence_control_set_ptr->total_process_init_count += (sequence_control_set_ptr->mode_decision_configuration_process_init_count = MAX(MIN(3, core_count), core_count / 12));
1892     sequence_control_set_ptr->total_process_init_count += (sequence_control_set_ptr->enc_dec_process_init_count                     = MAX(MIN(40, core_count), core_count));
1893     sequence_control_set_ptr->total_process_init_count += (sequence_control_set_ptr->entropy_coding_process_init_count              = MAX(MIN(3, core_count), core_count / 12));
1894 
1895     sequence_control_set_ptr->total_process_init_count += 6; // single processes count
1896     SVT_LOG("Number of logical cores available: %u\nNumber of PPCS %u\n", core_count, input_pic);
1897 
1898     return;
1899 
1900 }
1901 
1902 // Sets the default intra period the closest possible to 1 second without breaking the minigop
compute_default_intra_period(SequenceControlSet * sequence_control_set_ptr)1903 static int32_t compute_default_intra_period(
1904     SequenceControlSet       *sequence_control_set_ptr) {
1905 
1906     int32_t intra_period = 0;
1907     EbSvtVp9EncConfiguration   *config = &sequence_control_set_ptr->static_config;
1908     int32_t fps = config->frame_rate < 1000 ?
1909         config->frame_rate :
1910         config->frame_rate >> 16;
1911     int32_t mini_gop_size = (1 << (sequence_control_set_ptr->hierarchical_levels));
1912     int32_t min_ip = ((int)((fps) / mini_gop_size)*(mini_gop_size));
1913     int32_t max_ip = ((int)((fps + mini_gop_size) / mini_gop_size)*(mini_gop_size));
1914 
1915     intra_period = (ABS((fps - max_ip)) > ABS((fps - min_ip))) ? min_ip : max_ip;
1916 
1917     return intra_period;
1918 }
1919 
set_default_configuration_parameters(SequenceControlSet * sequence_control_set_ptr)1920 static void set_default_configuration_parameters(
1921     SequenceControlSet         *sequence_control_set_ptr) {
1922 
1923     // No Cropping Window
1924     sequence_control_set_ptr->cropping_right_offset = 0;
1925     sequence_control_set_ptr->cropping_bottom_offset = 0;
1926 
1927     // Coding Structure
1928     sequence_control_set_ptr->enable_qp_scaling_flag = EB_TRUE;
1929 
1930     //Denoise
1931     sequence_control_set_ptr->enable_denoise_flag = EB_TRUE;
1932 
1933     return;
1934 }
1935 
compute_default_look_ahead(EbSvtVp9EncConfiguration * config,SequenceControlSet * scs_ptr)1936 static uint32_t compute_default_look_ahead(
1937     EbSvtVp9EncConfiguration*   config,
1938     SequenceControlSet*         scs_ptr){
1939 
1940     int32_t lad = 0;
1941     if (config->rate_control_mode == 0)
1942         lad = (2 << scs_ptr->hierarchical_levels) + 1;
1943     else
1944         lad = config->intra_period;
1945 
1946     return lad;
1947 }
1948 
copy_api_from_app(SequenceControlSet * sequence_control_set_ptr,EbSvtVp9EncConfiguration * p_component_parameter_structure)1949 static void copy_api_from_app(
1950     SequenceControlSet         *sequence_control_set_ptr,
1951     EbSvtVp9EncConfiguration     *p_component_parameter_structure) {
1952 
1953     sequence_control_set_ptr->max_input_luma_width = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->source_width;
1954     sequence_control_set_ptr->max_input_luma_height = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->source_height;
1955     sequence_control_set_ptr->frame_rate = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->frame_rate;
1956     sequence_control_set_ptr->chroma_width = sequence_control_set_ptr->max_input_luma_width >> 1;
1957     sequence_control_set_ptr->chroma_height = sequence_control_set_ptr->max_input_luma_height >> 1;
1958 
1959     sequence_control_set_ptr->video_usability_info_ptr->field_seq_flag = EB_FALSE;
1960     sequence_control_set_ptr->video_usability_info_ptr->frame_field_info_present_flag = EB_FALSE;
1961 
1962     // Coding Structure
1963     sequence_control_set_ptr->static_config.intra_period = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->intra_period;
1964     sequence_control_set_ptr->static_config.pred_structure = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->pred_structure;
1965     sequence_control_set_ptr->static_config.base_layer_switch_mode = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->base_layer_switch_mode;
1966     sequence_control_set_ptr->static_config.tune = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->tune;
1967     sequence_control_set_ptr->static_config.enc_mode = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->enc_mode;
1968 
1969     sequence_control_set_ptr->intra_period = sequence_control_set_ptr->static_config.intra_period;
1970     sequence_control_set_ptr->max_ref_count = 1;
1971 
1972     // Quantization
1973     sequence_control_set_ptr->qp = sequence_control_set_ptr->static_config.qp = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->qp;
1974     sequence_control_set_ptr->static_config.use_qp_file = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->use_qp_file;
1975 
1976     // Loop Filter
1977     sequence_control_set_ptr->static_config.loop_filter = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->loop_filter;
1978 
1979     // ME Tools
1980     sequence_control_set_ptr->static_config.use_default_me_hme = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->use_default_me_hme;
1981 
1982     // Default HME/ME settings
1983     sequence_control_set_ptr->static_config.enable_hme_flag = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->enable_hme_flag;
1984     sequence_control_set_ptr->static_config.search_area_width = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->search_area_width;
1985     sequence_control_set_ptr->static_config.search_area_height = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->search_area_height;
1986 
1987     sequence_control_set_ptr->static_config.recon_file = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->recon_file;
1988     sequence_control_set_ptr->encode_context_ptr->recon_port_active = (EB_BOOL)sequence_control_set_ptr->static_config.recon_file;
1989 
1990     // Rate Control
1991     sequence_control_set_ptr->static_config.rate_control_mode = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->rate_control_mode;
1992     sequence_control_set_ptr->static_config.vbv_max_rate = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->vbv_max_rate;
1993     sequence_control_set_ptr->static_config.vbv_buf_size = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->vbv_buf_size;
1994     sequence_control_set_ptr->static_config.frames_to_be_encoded = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->frames_to_be_encoded;
1995     sequence_control_set_ptr->frame_rate = sequence_control_set_ptr->static_config.frame_rate = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->frame_rate;
1996     sequence_control_set_ptr->static_config.target_bit_rate = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->target_bit_rate;
1997     sequence_control_set_ptr->encode_context_ptr->available_target_bitrate = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->target_bit_rate;
1998     sequence_control_set_ptr->static_config.max_qp_allowed = (sequence_control_set_ptr->static_config.rate_control_mode) ?
1999         ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->max_qp_allowed :
2000 #if VP9_RC
2001         MAX_QP_VALUE;
2002 #else
2003         51;
2004 #endif
2005 
2006     sequence_control_set_ptr->static_config.min_qp_allowed = (sequence_control_set_ptr->static_config.rate_control_mode) ?
2007         ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->min_qp_allowed :
2008         0;
2009 
2010     // Misc
2011     sequence_control_set_ptr->static_config.encoder_bit_depth = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->encoder_bit_depth;
2012 
2013     // Annex A parameters
2014     sequence_control_set_ptr->static_config.profile = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->profile;
2015     sequence_control_set_ptr->static_config.level = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->level;
2016 
2017     sequence_control_set_ptr->static_config.injector_frame_rate = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->injector_frame_rate;
2018     sequence_control_set_ptr->static_config.speed_control_flag = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->speed_control_flag;
2019 
2020     sequence_control_set_ptr->static_config.asm_type = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->asm_type;
2021 
2022     sequence_control_set_ptr->static_config.channel_id = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->channel_id;
2023     sequence_control_set_ptr->static_config.active_channel_count = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->active_channel_count;
2024 
2025     sequence_control_set_ptr->static_config.logical_processors = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->logical_processors;
2026     sequence_control_set_ptr->static_config.target_socket = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->target_socket;
2027 
2028     sequence_control_set_ptr->static_config.frame_rate_denominator = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->frame_rate_denominator;
2029     sequence_control_set_ptr->static_config.frame_rate_numerator = ((EbSvtVp9EncConfiguration*)p_component_parameter_structure)->frame_rate_numerator;
2030 
2031     // Set default hierarchical-levels
2032     if (sequence_control_set_ptr->static_config.tune != 0 && sequence_control_set_ptr->static_config.rate_control_mode == 0) {
2033         sequence_control_set_ptr->hierarchical_levels = 4;
2034         sequence_control_set_ptr->max_temporal_layers = 4;
2035     }
2036     else {
2037         sequence_control_set_ptr->hierarchical_levels = 3;
2038         sequence_control_set_ptr->max_temporal_layers = 3;
2039     }
2040 
2041     // Extract frame rate from Numerator and Denominator if not 0
2042     if (sequence_control_set_ptr->static_config.frame_rate_numerator != 0 && sequence_control_set_ptr->static_config.frame_rate_denominator != 0) {
2043         sequence_control_set_ptr->frame_rate = sequence_control_set_ptr->static_config.frame_rate = (((sequence_control_set_ptr->static_config.frame_rate_numerator << 8) / (sequence_control_set_ptr->static_config.frame_rate_denominator)) << 8);
2044     }
2045 
2046     // Get Default Intra Period if not specified
2047     if (sequence_control_set_ptr->static_config.intra_period == -2) {
2048         sequence_control_set_ptr->intra_period = (sequence_control_set_ptr->static_config.intra_period = compute_default_intra_period(sequence_control_set_ptr));
2049     }
2050 
2051     sequence_control_set_ptr->look_ahead_distance = compute_default_look_ahead(&sequence_control_set_ptr->static_config, sequence_control_set_ptr);
2052 
2053     return;
2054 }
2055 
2056 /******************************************
2057 * Verify Settings
2058 ******************************************/
2059 #define PowerOfTwoCheck(x) (((x) != 0) && (((x) & (~(x) + 1)) == (x)))
2060 
verify_settings(SequenceControlSet * sequence_control_set_ptr)2061 static EbErrorType  verify_settings(
2062     SequenceControlSet *sequence_control_set_ptr)
2063 {
2064     EbErrorType   return_error = EB_ErrorNone;
2065     const char   *level_idc;
2066     unsigned int  level_idx;
2067     EbSvtVp9EncConfiguration *config = &sequence_control_set_ptr->static_config;
2068     unsigned int channel_number = config->channel_id;
2069 
2070     switch (config->level) {
2071     case 10:
2072         level_idc = "1";
2073         level_idx = 0;
2074 
2075         break;
2076     case 20:
2077         level_idc = "2";
2078         level_idx = 1;
2079 
2080         break;
2081     case 21:
2082         level_idc = "2.1";
2083         level_idx = 2;
2084 
2085         break;
2086     case 30:
2087         level_idc = "3";
2088         level_idx = 3;
2089 
2090         break;
2091     case 31:
2092         level_idc = "3.1";
2093         level_idx = 4;
2094 
2095         break;
2096     case 40:
2097         level_idc = "4";
2098         level_idx = 5;
2099 
2100         break;
2101     case 41:
2102         level_idc = "4.1";
2103         level_idx = 6;
2104 
2105         break;
2106     case 50:
2107         level_idc = "5";
2108         level_idx = 7;
2109 
2110         break;
2111     case 51:
2112         level_idc = "5.1";
2113         level_idx = 8;
2114 
2115         break;
2116     case 52:
2117         level_idc = "5.2";
2118         level_idx = 9;
2119 
2120         break;
2121     case 60:
2122         level_idc = "6";
2123         level_idx = 10;
2124 
2125         break;
2126     case 61:
2127         level_idc = "6.1";
2128         level_idx = 11;
2129 
2130         break;
2131     case 62:
2132         level_idc = "6.2";
2133         level_idx = 12;
2134 
2135         break;
2136 
2137     case 0: // Level determined by the encoder
2138         level_idc = "0";
2139         level_idx = TOTAL_LEVEL_COUNT;
2140 
2141         break;
2142 
2143     default:
2144         level_idc = "unknown";
2145         level_idx = TOTAL_LEVEL_COUNT + 1;
2146 
2147         break;
2148     }
2149 
2150     if (level_idx > TOTAL_LEVEL_COUNT) {
2151         SVT_LOG("Error Instance %u: Unsupported level\n", channel_number + 1);
2152         return_error = EB_ErrorBadParameter;
2153     }
2154 
2155     if (sequence_control_set_ptr->max_input_luma_width < 64) {
2156         SVT_LOG("Error instance %u: Source Width must be at least 64\n", channel_number + 1);
2157         return_error = EB_ErrorBadParameter;
2158     }
2159     if (sequence_control_set_ptr->max_input_luma_height < 64) {
2160         SVT_LOG("Error instance %u: Source Height must be at least 64\n", channel_number + 1);
2161         return_error = EB_ErrorBadParameter;
2162     }
2163 
2164     if (config->pred_structure != 2) {
2165         SVT_LOG("Error instance %u: Pred Structure must be [2]\n", channel_number + 1);
2166         return_error = EB_ErrorBadParameter;
2167     }
2168 
2169     if (config->base_layer_switch_mode == 1 && config->pred_structure != 2) {
2170         SVT_LOG("Error Instance %u: Base Layer Switch Mode 1 only when Prediction Structure is Random Access\n", channel_number + 1);
2171         return_error = EB_ErrorBadParameter;
2172     }
2173 
2174     if (sequence_control_set_ptr->max_input_luma_width % 2) {
2175         SVT_LOG("Error Instance %u: Source Width must be even for YUV_420 colorspace \n", channel_number + 1);
2176         return_error = EB_ErrorBadParameter;
2177     }
2178     else if (sequence_control_set_ptr->max_input_luma_height % 2) {
2179         SVT_LOG("Error Instance %u: Source Height must be even for YUV_420 colorspace\n", channel_number + 1);
2180         return_error = EB_ErrorBadParameter;
2181     }
2182     if (sequence_control_set_ptr->max_input_luma_width > 8192) {
2183         SVT_LOG("Error instance %u: Source Width must be less than 8192\n", channel_number + 1);
2184         return_error = EB_ErrorBadParameter;
2185     }
2186 
2187     if (sequence_control_set_ptr->max_input_luma_width % 8 != 0) {
2188         SVT_LOG("Error instance %u: Source Width must be a multiple of 8\n", channel_number + 1);
2189         return_error = EB_ErrorBadParameter;
2190     }
2191 
2192     if (sequence_control_set_ptr->max_input_luma_height > 4320) {
2193         SVT_LOG("Error instance %u: Source Height must be less than 4320\n", channel_number + 1);
2194         return_error = EB_ErrorBadParameter;
2195     }
2196 
2197     if (sequence_control_set_ptr->max_input_luma_height % 8 != 0) {
2198         SVT_LOG("Error instance %u: Source Height must be a multiple of 8\n", channel_number + 1);
2199         return_error = EB_ErrorBadParameter;
2200     }
2201 
2202     uint32_t input_size = sequence_control_set_ptr->max_input_luma_width * sequence_control_set_ptr->max_input_luma_height;
2203 
2204     uint8_t input_resolution = (input_size < INPUT_SIZE_1080i_TH) ? INPUT_SIZE_576p_RANGE_OR_LOWER :
2205         (input_size < INPUT_SIZE_1080p_TH) ? INPUT_SIZE_1080i_RANGE :
2206         (input_size < INPUT_SIZE_4K_TH) ? INPUT_SIZE_1080p_RANGE :
2207         INPUT_SIZE_4K_RANGE;
2208 
2209     if (input_resolution <= INPUT_SIZE_1080i_RANGE) {
2210         if (config->enc_mode > 9) {
2211             SVT_LOG("Error instance %u: enc_mode must be [0 - 9] for this resolution\n", channel_number + 1);
2212             return_error = EB_ErrorBadParameter;
2213         }
2214 
2215     }
2216     else if (input_resolution == INPUT_SIZE_1080p_RANGE) {
2217         if (config->enc_mode > 10) {
2218             SVT_LOG("Error instance %u: enc_mode must be [0 - 10] for this resolution\n", channel_number + 1);
2219             return_error = EB_ErrorBadParameter;
2220         }
2221 
2222     }
2223     else {
2224         if (config->enc_mode > 12 && config->tune == 0) {
2225             SVT_LOG("Error instance %u: enc_mode must be [0 - 12] for this resolution\n", channel_number + 1);
2226             return_error = EB_ErrorBadParameter;
2227         }
2228         else if (config->enc_mode > 10 && config->tune >= 1) {
2229             SVT_LOG("Error instance %u: enc_mode must be [0 - 10] for this resolution\n", channel_number + 1);
2230             return_error = EB_ErrorBadParameter;
2231         }
2232     }
2233 
2234     // enc_mode
2235     sequence_control_set_ptr->max_enc_mode = MAX_SUPPORTED_MODES;
2236     if (input_resolution <= INPUT_SIZE_1080i_RANGE) {
2237         sequence_control_set_ptr->max_enc_mode = MAX_SUPPORTED_MODES_SUB1080P - 1;
2238         if (config->enc_mode > MAX_SUPPORTED_MODES_SUB1080P - 1) {
2239             SVT_LOG("Error instance %u: enc_mode must be [0 - %d]\n", channel_number + 1, MAX_SUPPORTED_MODES_SUB1080P - 1);
2240             return_error = EB_ErrorBadParameter;
2241         }
2242     }
2243     else if (input_resolution == INPUT_SIZE_1080p_RANGE) {
2244         sequence_control_set_ptr->max_enc_mode = MAX_SUPPORTED_MODES_1080P - 1;
2245         if (config->enc_mode > MAX_SUPPORTED_MODES_1080P - 1) {
2246             SVT_LOG("Error instance %u: enc_mode must be [0 - %d]\n", channel_number + 1, MAX_SUPPORTED_MODES_1080P - 1);
2247             return_error = EB_ErrorBadParameter;
2248         }
2249     }
2250     else {
2251         if (config->tune == 0)
2252             sequence_control_set_ptr->max_enc_mode = MAX_SUPPORTED_MODES_4K_SQ - 1;
2253         else
2254             sequence_control_set_ptr->max_enc_mode = MAX_SUPPORTED_MODES_4K_OQ - 1;
2255 
2256         if (config->enc_mode > MAX_SUPPORTED_MODES_4K_SQ - 1 && config->tune == 0) {
2257             SVT_LOG("Error instance %u: enc_mode must be [0 - %d]\n", channel_number + 1, MAX_SUPPORTED_MODES_4K_SQ - 1);
2258             return_error = EB_ErrorBadParameter;
2259         }
2260         else if (config->enc_mode > MAX_SUPPORTED_MODES_4K_OQ - 1 && config->tune >= 1) {
2261             SVT_LOG("Error instance %u: enc_mode must be [0 - %d]\n", channel_number + 1, MAX_SUPPORTED_MODES_4K_OQ - 1);
2262             return_error = EB_ErrorBadParameter;
2263         }
2264     }
2265 
2266     if (config->qp > MAX_QP_VALUE) {
2267         SVT_LOG("Error instance %u: QP must be [0 - %d]\n", channel_number + 1, MAX_QP_VALUE);
2268         return_error = EB_ErrorBadParameter;
2269     }
2270 
2271     if (config->intra_period < -2 || config->intra_period > 255) {
2272         SVT_LOG("Error Instance %u: The intra period must be [-2 - 255] \n", channel_number + 1);
2273         return_error = EB_ErrorBadParameter;
2274     }
2275 
2276     if (config->base_layer_switch_mode > 1) {
2277         SVT_LOG("Error Instance %u: Invalid Base Layer Switch Mode [0-1] \n", channel_number + 1);
2278         return_error = EB_ErrorBadParameter;
2279     }
2280 
2281     if (config->loop_filter > 1) {
2282         SVT_LOG("Error Instance %u: Invalid LoopFilterDisable. LoopFilterDisable must be [0 - 1]\n", channel_number + 1);
2283         return_error = EB_ErrorBadParameter;
2284     }
2285 
2286     if (config->use_default_me_hme > 1) {
2287         SVT_LOG("Error Instance %u: invalid use_default_me_hme. use_default_me_hme must be [0 - 1]\n", channel_number + 1);
2288         return_error = EB_ErrorBadParameter;
2289     }
2290     if (config->enable_hme_flag > 1) {
2291         SVT_LOG("Error Instance %u: invalid HME. HME must be [0 - 1]\n", channel_number + 1);
2292         return_error = EB_ErrorBadParameter;
2293     }
2294 
2295     if ((config->search_area_width > 256) || (config->search_area_width == 0)) {
2296         SVT_LOG("Error Instance %u: Invalid search_area_width. search_area_width must be [1 - 256]\n", channel_number + 1);
2297         return_error = EB_ErrorBadParameter;
2298 
2299     }
2300 
2301     if ((config->search_area_height > 256) || (config->search_area_height == 0)) {
2302         SVT_LOG("Error Instance %u: Invalid search_area_height. search_area_height must be [1 - 256]\n", channel_number + 1);
2303         return_error = EB_ErrorBadParameter;
2304 
2305     }
2306 
2307     if (level_idx < 13) {
2308         // Check if the current input video is conformant with the Level constraint
2309         if (config->level != 0 && ((uint64_t)sequence_control_set_ptr->max_input_luma_width * (uint64_t)sequence_control_set_ptr->max_input_luma_height > max_luma_picture_size[level_idx])) {
2310             SVT_LOG("Error Instance %u: The input luma picture size exceeds the maximum luma picture size allowed for level %s\n", channel_number + 1, level_idc);
2311             return_error = EB_ErrorBadParameter;
2312         }
2313 
2314         // Check if the current input video is conformant with the Level constraint
2315         if (config->level != 0 && ((uint64_t)config->frame_rate * (uint64_t)sequence_control_set_ptr->max_input_luma_width * (uint64_t)sequence_control_set_ptr->max_input_luma_height > (max_luma_sample_rate[level_idx] << 16))) {
2316             SVT_LOG("Error Instance %u: The input luma sample rate exceeds the maximum input sample rate allowed for level %s\n", channel_number + 1, level_idc);
2317             return_error = EB_ErrorBadParameter;
2318         }
2319 
2320     }
2321 
2322     // Check if the current input video is conformant with the Level constraint
2323     if (config->frame_rate > (240 << 16)) {
2324         SVT_LOG("Error Instance %u: The maximum allowed frame rate is 240 fps\n", channel_number + 1);
2325         return_error = EB_ErrorBadParameter;
2326     }
2327     // Check that the frame_rate is non-zero
2328     if (config->frame_rate <= 0) {
2329         SVT_LOG("Error Instance %u: The frame rate should be greater than 0 fps \n", channel_number + 1);
2330         return_error = EB_ErrorBadParameter;
2331     }
2332     if (config->intra_period < -2 || config->intra_period > 255) {
2333         SVT_LOG("Error Instance %u: The intra period must be [-2 - 255] \n", channel_number + 1);
2334         return_error = EB_ErrorBadParameter;
2335     }
2336 
2337     if (config->rate_control_mode > 2) {
2338         SVT_LOG("Error Instance %u: The rate control mode must be [0 - 2] \n", channel_number + 1);
2339         return_error = EB_ErrorBadParameter;
2340     }
2341 #if !VP9_RC
2342     if (config->rate_control_mode == 1 && config->tune > 0) {
2343         SVT_LOG("Error Instance %u: The rate control is not supported for OQ mode (Tune = 1 ) and VMAF mode (Tune = 2)\n", channel_number + 1);
2344         return_error = EB_ErrorBadParameter;
2345     }
2346 #endif
2347 
2348 #if VP9_RC
2349     if (config->max_qp_allowed > 63) {
2350         SVT_LOG("Error instance %u: max_qp_allowed must be [0 - 63]\n", channel_number + 1);
2351         return_error = EB_ErrorBadParameter;
2352     }
2353     else if (config->min_qp_allowed > 62) {
2354         SVT_LOG("Error instance %u: min_qp_allowed must be [0 - 62]\n", channel_number + 1);
2355         return_error = EB_ErrorBadParameter;
2356     }
2357 #else
2358     if (config->max_qp_allowed > 51) {
2359         SVT_LOG("Error instance %u: max_qp_allowed must be [0 - 51]\n", channel_number + 1);
2360         return_error = EB_ErrorBadParameter;
2361     }
2362     else if (config->min_qp_allowed > 50) {
2363         SVT_LOG("Error instance %u: min_qp_allowed must be [0 - 50]\n", channel_number + 1);
2364         return_error = EB_ErrorBadParameter;
2365     }
2366 #endif
2367     else if ((config->min_qp_allowed) > (config->max_qp_allowed)) {
2368         SVT_LOG("Error Instance %u:  min_qp_allowed must be smaller than max_qp_allowed\n", channel_number + 1);
2369         return_error = EB_ErrorBadParameter;
2370     }
2371 
2372     if (config->tune > 2) {
2373         SVT_LOG("Error instance %u : Invalid Tune. Tune must be [0 - 1]\n", channel_number + 1);
2374         return_error = EB_ErrorBadParameter;
2375     }
2376 
2377     if ((config->encoder_bit_depth != 8)) {
2378         SVT_LOG("Error instance %u: Only 8 bit is supported in this build \n", channel_number + 1);
2379         return_error = EB_ErrorBadParameter;
2380     }
2381     // Check if the encoder_bit_depth is conformant with the Profile constraint
2382     if (config->profile != 0) {
2383         SVT_LOG("Error instance %u: Only 420 8 bit is supported in this build\n", channel_number + 1);
2384         return_error = EB_ErrorBadParameter;
2385     }
2386 
2387     if (config->speed_control_flag > 1) {
2388         SVT_LOG("Error Instance %u: Invalid Speed Control flag [0 - 1]\n", channel_number + 1);
2389         return_error = EB_ErrorBadParameter;
2390     }
2391 
2392     if (((int32_t)(config->asm_type) < 0) || ((int32_t)(config->asm_type) > 1)) {
2393         SVT_LOG("Error Instance %u: Invalid asm type value [0: C Only, 1: Auto] .\n", channel_number + 1);
2394         return_error = EB_ErrorBadParameter;
2395     }
2396 
2397     if (config->target_socket != -1 && config->target_socket != 0 && config->target_socket != 1) {
2398         SVT_LOG("Error instance %u: Invalid target_socket. target_socket must be [-1 - 1] \n", channel_number + 1);
2399         return_error = EB_ErrorBadParameter;
2400     }
2401 
2402     return return_error;
2403 }
2404 
2405 /**********************************
2406 * Set Parameter
2407 **********************************/
set_param_based_on_input(SequenceControlSet * sequence_control_set_ptr)2408 static void set_param_based_on_input(
2409     SequenceControlSet       *sequence_control_set_ptr) {
2410 
2411     // Update picture width, and picture height
2412     if (sequence_control_set_ptr->max_input_luma_width % MIN_CU_SIZE) {
2413 
2414         sequence_control_set_ptr->max_input_pad_right = MIN_CU_SIZE - (sequence_control_set_ptr->max_input_luma_width % MIN_CU_SIZE);
2415         sequence_control_set_ptr->max_input_luma_width = sequence_control_set_ptr->max_input_luma_width + sequence_control_set_ptr->max_input_pad_right;
2416     }
2417     else {
2418 
2419         sequence_control_set_ptr->max_input_pad_right = 0;
2420     }
2421     if (sequence_control_set_ptr->max_input_luma_height % MIN_CU_SIZE) {
2422 
2423         sequence_control_set_ptr->max_input_pad_bottom = MIN_CU_SIZE - (sequence_control_set_ptr->max_input_luma_height % MIN_CU_SIZE);
2424         sequence_control_set_ptr->max_input_luma_height = sequence_control_set_ptr->max_input_luma_height + sequence_control_set_ptr->max_input_pad_bottom;
2425     }
2426     else {
2427         sequence_control_set_ptr->max_input_pad_bottom = 0;
2428     }
2429 
2430     sequence_control_set_ptr->max_input_chroma_width = sequence_control_set_ptr->max_input_luma_width >> 1;
2431     sequence_control_set_ptr->max_input_chroma_height = sequence_control_set_ptr->max_input_luma_height >> 1;
2432 
2433     // Configure the padding
2434     sequence_control_set_ptr->left_padding = MAX_CU_SIZE + 4;
2435     sequence_control_set_ptr->top_padding = MAX_CU_SIZE + 4;
2436     sequence_control_set_ptr->right_padding = MAX_CU_SIZE + 4;
2437     sequence_control_set_ptr->bot_padding = MAX_CU_SIZE + 4;
2438 
2439     sequence_control_set_ptr->chroma_width = sequence_control_set_ptr->max_input_luma_width >> 1;
2440     sequence_control_set_ptr->chroma_height = sequence_control_set_ptr->max_input_luma_height >> 1;
2441     sequence_control_set_ptr->luma_width = sequence_control_set_ptr->max_input_luma_width;
2442     sequence_control_set_ptr->luma_height = sequence_control_set_ptr->max_input_luma_height;
2443     sequence_control_set_ptr->static_config.source_width = sequence_control_set_ptr->max_input_luma_width;
2444     sequence_control_set_ptr->static_config.source_height = sequence_control_set_ptr->max_input_luma_height;
2445 
2446     eb_vp9_derive_input_resolution(
2447         sequence_control_set_ptr,
2448         sequence_control_set_ptr->luma_width*sequence_control_set_ptr->luma_height);
2449 
2450 }
print_lib_params(SequenceControlSet * scs)2451 static void print_lib_params(
2452     SequenceControlSet* scs) {
2453 
2454     EbSvtVp9EncConfiguration*   config = &scs->static_config;
2455 
2456     SVT_LOG("------------------------------------------- ");
2457     SVT_LOG("\nSVT [config]: Profile [0]\t");
2458 
2459     if (config->level != 0)
2460         SVT_LOG("Level %.1f\t", (float)(config->level / 10));
2461     else {
2462         SVT_LOG("Level (auto)\t");
2463     }
2464     SVT_LOG("\nSVT [config]: EncoderMode / Tune \t\t\t\t\t\t: %d / %d ", config->enc_mode, config->tune);
2465     SVT_LOG("\nSVT [config]: EncoderBitDepth \t\t\t\t\t\t\t: %d ", config->encoder_bit_depth);
2466     SVT_LOG("\nSVT [config]: SourceWidth / SourceHeight\t\t\t\t\t: %d / %d ", config->source_width, config->source_height);
2467     if (config->frame_rate_denominator != 0 && config->frame_rate_numerator != 0)
2468         SVT_LOG("\nSVT [config]: Fps_Numerator / Fps_Denominator / Gop Size\t\t: %d / %d / %d", config->frame_rate_numerator > (1 << 16) ? config->frame_rate_numerator >> 16 : config->frame_rate_numerator,
2469             config->frame_rate_denominator > (1 << 16) ? config->frame_rate_denominator >> 16 : config->frame_rate_denominator,
2470             config->intra_period + 1);
2471     else
2472         SVT_LOG("\nSVT [config]: FrameRate / Gop Size\t\t\t\t\t\t: %d / %d ", config->frame_rate > 1000 ? config->frame_rate >> 16 : config->frame_rate, config->intra_period + 1);
2473     SVT_LOG("\nSVT [config]: HierarchicalLevels / BaseLayerSwitchMode / PredStructure\t\t: %d / %d / %d ", scs->hierarchical_levels, config->base_layer_switch_mode, config->pred_structure);
2474     if (config->rate_control_mode == 2)
2475         SVT_LOG("\nSVT [config]: RCMode / TargetBitrate\t\t\t\t\t\t: CBR / %d ", config->target_bit_rate);
2476     else if (config->rate_control_mode == 1)
2477         SVT_LOG("\nSVT [config]: RCMode / TargetBitrate\t\t\t\t\t\t: VBR / %d ", config->target_bit_rate);
2478     else
2479         SVT_LOG("\nSVT [config]: BRC Mode / QP \t\t\t\t\t\t\t: CQP / %d ", scs->qp);
2480 #ifdef DEBUG_BUFFERS
2481     SVT_LOG("\nSVT [config]: INPUT / OUTPUT \t\t\t\t\t\t\t: %d / %d", scs->input_buffer_fifo_init_count, scs->output_stream_buffer_fifo_init_count);
2482     SVT_LOG("\nSVT [config]: CPCS / PAREF / REF \t\t\t\t\t\t: %d / %d / %d", scs->picture_control_set_pool_init_count_child, scs->pa_reference_picture_buffer_init_count, scs->reference_picture_buffer_init_count);
2483     SVT_LOG("\nSVT [config]: ME_SEG_W0 / ME_SEG_W1 / ME_SEG_W2 / ME_SEG_W3 \t\t\t: %d / %d / %d / %d ",
2484         scs->me_segment_column_count_array[0],
2485         scs->me_segment_column_count_array[1],
2486         scs->me_segment_column_count_array[2],
2487         scs->me_segment_column_count_array[3]);
2488     SVT_LOG("\nSVT [config]: ME_SEG_H0 / ME_SEG_H1 / ME_SEG_H2 / ME_SEG_H3 \t\t\t: %d / %d / %d / %d ",
2489         scs->me_segment_row_count_array[0],
2490         scs->me_segment_row_count_array[1],
2491         scs->me_segment_row_count_array[2],
2492         scs->me_segment_row_count_array[3]);
2493     SVT_LOG("\nSVT [config]: ME_SEG_W0 / ME_SEG_W1 / ME_SEG_W2 / ME_SEG_W3 \t\t\t: %d / %d / %d / %d ",
2494         scs->enc_dec_segment_col_count_array[0],
2495         scs->enc_dec_segment_col_count_array[1],
2496         scs->enc_dec_segment_col_count_array[2],
2497         scs->enc_dec_segment_col_count_array[3]);
2498     SVT_LOG("\nSVT [config]: ME_SEG_H0 / ME_SEG_H1 / ME_SEG_H2 / ME_SEG_H3 \t\t\t: %d / %d / %d / %d ",
2499         scs->enc_dec_segment_row_count_array[0],
2500         scs->enc_dec_segment_row_count_array[1],
2501         scs->enc_dec_segment_row_count_array[2],
2502         scs->enc_dec_segment_row_count_array[3]);
2503     SVT_LOG("\nSVT [config]: PA_P / ME_P / SBO_P / MDC_P / ED_P / EC_P \t\t\t: %d / %d / %d / %d / %d / %d ",
2504         scs->picture_analysis_process_init_count,
2505         scs->motion_estimation_process_init_count,
2506         scs->source_based_operations_process_init_count,
2507         scs->mode_decision_configuration_process_init_count,
2508         scs->enc_dec_process_init_count,
2509         scs->entropy_coding_process_init_count);
2510 #endif
2511     SVT_LOG("\n------------------------------------------- ");
2512     SVT_LOG("\n");
2513 
2514     fflush(stdout);
2515 }
2516 
2517 /**********************************
2518  * Set Parameter
2519  **********************************/
2520 #if __unix__
2521 __attribute__((visibility("default")))
2522 #endif
eb_vp9_svt_enc_set_parameter(EbComponentType * svt_enc_component,EbSvtVp9EncConfiguration * p_component_parameter_structure)2523 EB_API EbErrorType  eb_vp9_svt_enc_set_parameter(
2524     EbComponentType             *svt_enc_component,
2525     EbSvtVp9EncConfiguration    *p_component_parameter_structure){
2526 
2527     EbErrorType            return_error;
2528     EbEncHandle           *p_enc_comp_data;
2529     SequenceControlSet    *scs_ptr;
2530 
2531     if (svt_enc_component == (EbComponentType*)EB_NULL) {
2532         return EB_ErrorBadParameter;
2533     }
2534 
2535     return_error        = EB_ErrorNone;
2536     p_enc_comp_data     = (EbEncHandle*)svt_enc_component->p_component_private;
2537     scs_ptr             = p_enc_comp_data->sequence_control_set_instance_array[0]->sequence_control_set_ptr;
2538 
2539     // Acquire Config Mutex
2540     eb_vp9_block_on_mutex(p_enc_comp_data->sequence_control_set_instance_array[0]->config_mutex);
2541 
2542     set_default_configuration_parameters(scs_ptr);
2543 
2544     copy_api_from_app(
2545         scs_ptr,
2546         (EbSvtVp9EncConfiguration*)p_component_parameter_structure);
2547 
2548     return_error = (EbErrorType)verify_settings(scs_ptr);
2549 
2550     if (return_error == EB_ErrorBadParameter) {
2551         return EB_ErrorBadParameter;
2552     }
2553 
2554     set_param_based_on_input(scs_ptr);
2555 
2556     // Initialize the Prediction Structure Group
2557     return_error = (EbErrorType)eb_vp9_prediction_structure_group_ctor(
2558         &p_enc_comp_data->sequence_control_set_instance_array[0]->encode_context_ptr->prediction_structure_group_ptr,
2559         scs_ptr->static_config.base_layer_switch_mode);
2560     if (return_error == EB_ErrorInsufficientResources) {
2561         return EB_ErrorInsufficientResources;
2562     }
2563 
2564     // Set the Prediction Structure
2565     scs_ptr->pred_struct_ptr = eb_vp9_get_prediction_structure(
2566         p_enc_comp_data->sequence_control_set_instance_array[0]->encode_context_ptr->prediction_structure_group_ptr,
2567         scs_ptr->static_config.pred_structure,
2568         scs_ptr->max_ref_count,
2569         scs_ptr->max_temporal_layers);
2570 
2571     eb_vp9_load_default_buffer_configuration_settings(scs_ptr);
2572 
2573     print_lib_params(scs_ptr);
2574 
2575     // Release Config Mutex
2576     eb_vp9_release_mutex(p_enc_comp_data->sequence_control_set_instance_array[0]->config_mutex);
2577 
2578     return return_error;
2579 }
2580 
2581 /***********************************************
2582 **** Copy the input buffer from the
2583 **** sample application to the library buffers
2584 ************************************************/
copy_frame_buffer(SequenceControlSet * sequence_control_set_ptr,uint8_t * dst,uint8_t * src)2585 static EbErrorType copy_frame_buffer(
2586     SequenceControlSet               *sequence_control_set_ptr,
2587     uint8_t                          *dst,
2588     uint8_t                          *src){
2589 
2590     EbSvtVp9EncConfiguration        *config = &sequence_control_set_ptr->static_config;
2591     EbErrorType                      return_error = EB_ErrorNone;
2592 
2593     EbPictureBufferDesc             *input_picture_ptr = (EbPictureBufferDesc*)dst;
2594     EbSvtEncInput                   *input_ptr = (EbSvtEncInput*)src;
2595     uint16_t                         input_row_index;
2596     EbBool                           is16_bit_input = (EbBool)(config->encoder_bit_depth > EB_8BIT);
2597 
2598     // Need to include for Interlacing on the fly with pictureScanType = 1
2599 
2600     if (!is16_bit_input) {
2601 
2602         uint32_t     luma_buffer_offset = (input_picture_ptr->stride_y*sequence_control_set_ptr->top_padding + sequence_control_set_ptr->left_padding) << is16_bit_input;
2603         uint32_t     chroma_buffer_offset = (input_picture_ptr->stride_cr*(sequence_control_set_ptr->top_padding >> 1) + (sequence_control_set_ptr->left_padding >> 1)) << is16_bit_input;
2604         uint16_t     luma_stride = input_picture_ptr->stride_y << is16_bit_input;
2605         uint16_t     chroma_stride = input_picture_ptr->stride_cb << is16_bit_input;
2606         uint16_t     luma_width = (uint16_t)(input_picture_ptr->width - sequence_control_set_ptr->max_input_pad_right) << is16_bit_input;
2607         uint16_t     chroma_width = (luma_width >> 1) << is16_bit_input;
2608         uint16_t     luma_height = (uint16_t)(input_picture_ptr->height - sequence_control_set_ptr->max_input_pad_bottom);
2609 
2610         uint16_t     source_luma_stride = (uint16_t)(input_ptr->y_stride);
2611         uint16_t     source_cr_stride = (uint16_t)(input_ptr->cr_stride);
2612         uint16_t     source_cb_stride = (uint16_t)(input_ptr->cb_stride);
2613 
2614         //uint16_t     luma_height  = input_picture_ptr->maxHeight;
2615         // Y
2616         for (input_row_index = 0; input_row_index < luma_height; input_row_index++) {
2617 
2618             EB_MEMCPY((input_picture_ptr->buffer_y + luma_buffer_offset + luma_stride * input_row_index),
2619                 (input_ptr->luma + source_luma_stride * input_row_index),
2620                 luma_width);
2621         }
2622 
2623         // U
2624         for (input_row_index = 0; input_row_index < luma_height >> 1; input_row_index++) {
2625             EB_MEMCPY((input_picture_ptr->buffer_cb + chroma_buffer_offset + chroma_stride * input_row_index),
2626                 (input_ptr->cb + (source_cb_stride*input_row_index)),
2627                 chroma_width);
2628         }
2629 
2630         // V
2631         for (input_row_index = 0; input_row_index < luma_height >> 1; input_row_index++) {
2632             EB_MEMCPY((input_picture_ptr->buffer_cr + chroma_buffer_offset + chroma_stride * input_row_index),
2633                 (input_ptr->cr + (source_cr_stride*input_row_index)),
2634                 chroma_width);
2635         }
2636 
2637     }
2638 
2639     return return_error;
2640 }
2641 
copy_input_buffer(SequenceControlSet * sequenceControlSet,EbBufferHeaderType * dst,EbBufferHeaderType * src)2642 static void copy_input_buffer(
2643     SequenceControlSet*     sequenceControlSet,
2644     EbBufferHeaderType*     dst,
2645     EbBufferHeaderType*     src){
2646 
2647     // Copy the higher level structure
2648     dst->n_alloc_len = src->n_alloc_len;
2649     dst->n_filled_len = src->n_filled_len;
2650     dst->flags = src->flags;
2651     dst->pts = src->pts;
2652     dst->n_tick_count = src->n_tick_count;
2653     dst->size = src->size;
2654     dst->qp = src->qp;
2655     dst->pic_type = src->pic_type;
2656 
2657     // Copy the picture buffer
2658     if (src->p_buffer != NULL)
2659         copy_frame_buffer(sequenceControlSet, dst->p_buffer, src->p_buffer);
2660 }
2661 
copy_output_recon_buffer(EbBufferHeaderType * dst,EbBufferHeaderType * src)2662 static void copy_output_recon_buffer(
2663     EbBufferHeaderType   *dst,
2664     EbBufferHeaderType   *src){
2665 
2666     // copy output bitstream fileds
2667     dst->size = src->size;
2668     dst->n_alloc_len = src->n_alloc_len;
2669     dst->n_filled_len = src->n_filled_len;
2670     dst->p_app_private = src->p_app_private;
2671     dst->n_tick_count = src->n_tick_count;
2672     dst->pts = src->pts;
2673     dst->dts = src->dts;
2674     dst->flags = src->flags;
2675     dst->pic_type = src->pic_type;
2676     if (src->p_buffer)
2677         EB_MEMCPY(dst->p_buffer, src->p_buffer, src->n_filled_len);
2678 
2679     return;
2680 }
2681 /**********************************
2682 * Fill This Buffer
2683 **********************************/
2684 #if defined(__unix__) || defined(__APPLE__)
2685 __attribute__((visibility("default")))
2686 #endif
eb_vp9_svt_get_recon(EbComponentType * svt_enc_component,EbBufferHeaderType * p_buffer)2687 EB_API EbErrorType eb_vp9_svt_get_recon(
2688     EbComponentType      *svt_enc_component,
2689     EbBufferHeaderType   *p_buffer){
2690 
2691     EbErrorType           return_error    = EB_ErrorNone;
2692     EbEncHandle          *p_enc_comp_data = (EbEncHandle*)svt_enc_component->p_component_private;
2693     EbObjectWrapper      *eb_wrapper_ptr  = NULL;
2694     SequenceControlSet   *scs_ptr         = p_enc_comp_data->sequence_control_set_instance_array[0]->sequence_control_set_ptr;
2695 
2696     if (scs_ptr->static_config.recon_file) {
2697 
2698         eb_vp9_get_full_object_non_blocking(
2699             (p_enc_comp_data->output_recon_buffer_consumer_fifo_ptr_dbl_array[0])[0],
2700             &eb_wrapper_ptr);
2701 
2702         if (eb_wrapper_ptr) {
2703             EbBufferHeaderType* obj_ptr = (EbBufferHeaderType*)eb_wrapper_ptr->object_ptr;
2704             copy_output_recon_buffer(
2705                 p_buffer,
2706                 obj_ptr);
2707 
2708             if (p_buffer->flags != EB_BUFFERFLAG_EOS && p_buffer->flags != 0)
2709                 return_error = EB_ErrorMax;
2710 
2711             eb_vp9_release_object((EbObjectWrapper  *)eb_wrapper_ptr);
2712         }
2713         else {
2714             return_error = EB_NoErrorEmptyQueue;
2715         }
2716     }
2717     else {
2718         // recon is not enabled
2719         return_error = EB_ErrorMax;
2720     }
2721 
2722     return return_error;
2723 }
2724 
2725 /**********************************
2726 * Empty This Buffer
2727 **********************************/
2728 #if defined(__unix__) || defined(__APPLE__)
2729 __attribute__((visibility("default")))
2730 #endif
eb_vp9_svt_enc_send_picture(EbComponentType * svt_enc_component,EbBufferHeaderType * p_buffer)2731 EB_API EbErrorType eb_vp9_svt_enc_send_picture(
2732     EbComponentType      *svt_enc_component,
2733     EbBufferHeaderType   *p_buffer)
2734 {
2735     EbEncHandle          *enc_handle_ptr = (EbEncHandle*)svt_enc_component->p_component_private;
2736     EbObjectWrapper      *eb_wrapper_ptr;
2737 
2738     // Take the buffer and put it into our internal queue structure
2739     eb_vp9_get_empty_object(
2740         enc_handle_ptr->input_buffer_producer_fifo_ptr_array[0],
2741         &eb_wrapper_ptr);
2742 
2743     if (p_buffer != NULL) {
2744         copy_input_buffer(
2745             enc_handle_ptr->sequence_control_set_instance_array[0]->sequence_control_set_ptr,
2746             (EbBufferHeaderType*)eb_wrapper_ptr->object_ptr,
2747             p_buffer);
2748     }
2749 
2750     eb_vp9_post_full_object(eb_wrapper_ptr);
2751 
2752     return EB_ErrorNone;
2753 }
2754 
2755 /**********************************
2756 * eb_svt_get_packet sends out packet
2757 **********************************/
2758 #if defined(__unix__) || defined(__APPLE__)
2759 __attribute__((visibility("default")))
2760 #endif
eb_vp9_svt_get_packet(EbComponentType * svt_enc_component,EbBufferHeaderType ** p_buffer,unsigned char pic_send_done)2761 EB_API EbErrorType eb_vp9_svt_get_packet(
2762     EbComponentType      *svt_enc_component,
2763     EbBufferHeaderType  **p_buffer,
2764     unsigned char         pic_send_done){
2765 
2766     EbErrorType             return_error = EB_ErrorNone;
2767     EbEncHandle            *p_enc_comp_data = (EbEncHandle*)svt_enc_component->p_component_private;
2768     EbObjectWrapper        *eb_wrapper_ptr = NULL;
2769     EbBufferHeaderType     *packet;
2770     if (pic_send_done)
2771         eb_vp9_get_full_object(
2772         (p_enc_comp_data->output_stream_buffer_consumer_fifo_ptr_dbl_array[0])[0],
2773             &eb_wrapper_ptr);
2774     else
2775         eb_vp9_get_full_object_non_blocking(
2776         (p_enc_comp_data->output_stream_buffer_consumer_fifo_ptr_dbl_array[0])[0],
2777             &eb_wrapper_ptr);
2778 
2779     if (eb_wrapper_ptr) {
2780 
2781         packet = (EbBufferHeaderType*)eb_wrapper_ptr->object_ptr;
2782 
2783         if (packet->flags != EB_BUFFERFLAG_EOS &&
2784             packet->flags != EB_BUFFERFLAG_SHOW_EXT &&
2785             packet->flags != (EB_BUFFERFLAG_SHOW_EXT | EB_BUFFERFLAG_EOS) &&
2786             packet->flags != 0) {
2787             return_error = EB_ErrorMax;
2788         }
2789 
2790         // return the output stream buffer
2791         *p_buffer = packet;
2792 
2793         // save the wrapper pointer for the release
2794         (*p_buffer)->wrapper_ptr = (void*)eb_wrapper_ptr;
2795     }
2796     else
2797         return_error = EB_NoErrorEmptyQueue;
2798 
2799     return return_error;
2800 }
2801 
switch_to_real_time()2802 static void switch_to_real_time() {
2803 
2804 #if  __unix__
2805 
2806     struct sched_param schedParam = {
2807         .sched_priority = 99
2808     };
2809 
2810     int retValue = pthread_setschedparam(pthread_self(), SCHED_FIFO, &schedParam);
2811     if (retValue == EPERM)
2812         SVT_LOG("\n[WARNING] For best speed performance, run with sudo privileges !\n\n");
2813 
2814 #endif
2815 }
2816 
2817 /**************************************
2818  * EbBufferHeaderType Constructor
2819  **************************************/
eb_buffer_header_ctor(EbPtr * object_dbl_ptr,EbPtr object_init_data_ptr)2820 EbErrorType  eb_buffer_header_ctor(
2821     EbPtr  *object_dbl_ptr,
2822     EbPtr  object_init_data_ptr){
2823 
2824     *object_dbl_ptr = (EbPtr)EB_NULL;
2825     object_init_data_ptr = (EbPtr)EB_NULL;
2826 
2827     (void)object_dbl_ptr;
2828     (void)object_init_data_ptr;
2829 
2830     return EB_ErrorNone;
2831 }
2832 
2833 #if defined(__unix__) || defined(__APPLE__)
2834 __attribute__((visibility("default")))
2835 #endif
eb_vp9_svt_enc_stream_header(EbComponentType * svt_enc_component,EbBufferHeaderType ** output_stream_ptr)2836 EB_API EbErrorType eb_vp9_svt_enc_stream_header(
2837     EbComponentType           *svt_enc_component,
2838     EbBufferHeaderType        **output_stream_ptr) {
2839 
2840     EbErrorType             return_error = EB_ErrorNone;
2841     UNUSED(svt_enc_component);
2842     UNUSED(output_stream_ptr);
2843     return return_error;
2844 }
2845 //
2846 #if defined(__unix__) || defined(__APPLE__)
2847 __attribute__((visibility("default")))
2848 #endif
eb_vp9_svt_enc_eos_nal(EbComponentType * svt_enc_component,EbBufferHeaderType ** output_stream_ptr)2849 EB_API EbErrorType eb_vp9_svt_enc_eos_nal(
2850     EbComponentType           *svt_enc_component,
2851     EbBufferHeaderType       **output_stream_ptr
2852 )
2853 {
2854     EbErrorType           return_error = EB_ErrorNone;
2855     UNUSED(svt_enc_component);
2856     UNUSED(output_stream_ptr);
2857     return return_error;
2858 }
2859 
2860 /**********************************
2861 * Encoder Handle Initialization
2862 **********************************/
init_svt_vp9_encoder_handle(EbComponentType * h_component)2863 static EbErrorType init_svt_vp9_encoder_handle(
2864     EbComponentType * h_component){
2865 
2866     EbErrorType       return_error = EB_ErrorNone;
2867     EbComponentType  *svt_enc_component = (EbComponentType*)h_component;
2868 
2869     SVT_LOG("-------------------------------------------\n");
2870     SVT_LOG("SVT [version]\t: SVT-VP9 Encoder Lib v%d.%d.%d\n", SVT_VERSION_MAJOR, SVT_VERSION_MINOR, SVT_VERSION_PATCHLEVEL);
2871 #if ( defined( _MSC_VER ) && (_MSC_VER < 1910) )
2872     SVT_LOG("SVT [build]\t: Visual Studio 2013");
2873 #elif ( defined( _MSC_VER ) && (_MSC_VER >= 1910) )
2874     SVT_LOG("SVT [build]\t: Visual Studio 2017");
2875 #elif defined(__GNUC__)
2876     SVT_LOG("SVT [build]\t: GCC %d.%d.%d\t", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
2877 #else
2878     SVT_LOG("SVT [build]\t: unknown compiler");
2879 #endif
2880     SVT_LOG(" %u bit\n", (unsigned) sizeof(void*) * 8);
2881     SVT_LOG("LIB Build date: %s %s\n", __DATE__, __TIME__);
2882     SVT_LOG("-------------------------------------------\n");
2883 
2884     switch_to_real_time();
2885 
2886     // Set Component Size & Version
2887     svt_enc_component->n_size = sizeof(EbComponentType);
2888 
2889     // Encoder Private Handle Ctor
2890     return_error = (EbErrorType)eb_enc_handle_ctor(
2891         (EbEncHandle**) &(svt_enc_component->p_component_private),
2892         svt_enc_component);
2893 
2894     return return_error;
2895 }
2896 
2897 /* SAFE STRING LIBRARY */
2898 
2899 #ifndef EOK
2900 #define EOK             ( 0 )
2901 #endif
2902 
2903 #ifndef ESZEROL
2904 #define ESZEROL         ( 401 )       /* length is zero              */
2905 #endif
2906 
2907 #ifndef ESLEMIN
2908 #define ESLEMIN         ( 402 )       /* length is below min         */
2909 #endif
2910 
2911 #ifndef ESLEMAX
2912 #define ESLEMAX         ( 403 )       /* length exceeds max          */
2913 #endif
2914 
2915 #ifndef ESNULLP
2916 #define ESNULLP         ( 400 )       /* null ptr                    */
2917 #endif
2918 
2919 #ifndef ESOVRLP
2920 #define ESOVRLP         ( 404 )       /* overlap undefined           */
2921 #endif
2922 
2923 #ifndef ESEMPTY
2924 #define ESEMPTY         ( 405 )       /* empty string                */
2925 #endif
2926 
2927 #ifndef ESNOSPC
2928 #define ESNOSPC         ( 406 )       /* not enough space for s2     */
2929 #endif
2930 
2931 #ifndef ESUNTERM
2932 #define ESUNTERM        ( 407 )       /* unterminated string         */
2933 #endif
2934 
2935 #ifndef ESNODIFF
2936 #define ESNODIFF        ( 408 )       /* no difference               */
2937 #endif
2938 
2939 #ifndef ESNOTFND
2940 #define ESNOTFND        ( 409 )       /* not found                   */
2941 #endif
2942 
2943 #define RSIZE_MAX_MEM      ( 256UL << 20 )     /* 256MB */
2944 
2945 #define RCNEGATE(x)  (x)
2946 #define RSIZE_MAX_STR      ( 4UL << 10 )      /* 4KB */
2947 
2948 #ifndef sldebug_printf
2949 #define sldebug_printf(...)
2950 #endif
2951 
2952 /*
2953 * Function used by the libraries to invoke the registered
2954 * runtime-constraint handler. Always needed.
2955 */
2956 
2957 typedef void(*ConstraintHandler) (
2958     const char * /* msg */,
2959     void *       /* ptr */,
2960     Errno      /* error */);
2961 /*
2962 * Function used by the libraries to invoke the registered
2963 * runtime-constraint handler. Always needed.
2964 */
2965 static inline void invoke_safe_str_constraint_handler(
2966     const char *msg,
2967     void *ptr,
2968     Errno error);
2969 
invoke_safe_str_constraint_handler(const char * msg,void * ptr,Errno error)2970 static inline void invoke_safe_str_constraint_handler(
2971     const char *msg,
2972     void *ptr,
2973     Errno error)
2974 {
2975     (void)ptr;
2976     sldebug_printf("IGNORE CONSTRAINT HANDLER: (%u) %s\n", error,
2977     (msg) ? msg : "Null message");
2978 }
2979 
eb_vp9_strnlen_ss(const char * dest,rsize_t dmax)2980 EB_API rsize_t eb_vp9_strnlen_ss(const char *dest, rsize_t dmax)
2981 {
2982     rsize_t count = 0;
2983 
2984     if (dest == NULL) {
2985         return RCNEGATE(0);
2986     }
2987 
2988     if (dmax == 0) {
2989         invoke_safe_str_constraint_handler("strnlen_ss: dmax is 0",
2990             NULL, ESZEROL);
2991         return RCNEGATE(0);
2992     }
2993 
2994     if (dmax > RSIZE_MAX_STR) {
2995         invoke_safe_str_constraint_handler("strnlen_ss: dmax exceeds max",
2996             NULL, ESLEMAX);
2997         return RCNEGATE(0);
2998     }
2999 
3000     while (*dest && dmax) {
3001         count++;
3002         dmax--;
3003         dest++;
3004     }
3005 
3006     return RCNEGATE(count);
3007 }
3008 
3009 /* SAFE STRING LIBRARY */
3010