• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include "av1/common/warped_motion.h"
13 #include "av1/common/thread_common.h"
14 
15 #include "av1/encoder/allintra_vis.h"
16 #include "av1/encoder/bitstream.h"
17 #include "av1/encoder/encodeframe.h"
18 #include "av1/encoder/encoder.h"
19 #include "av1/encoder/encoder_alloc.h"
20 #include "av1/encoder/encodeframe_utils.h"
21 #include "av1/encoder/ethread.h"
22 #if !CONFIG_REALTIME_ONLY
23 #include "av1/encoder/firstpass.h"
24 #endif
25 #include "av1/encoder/global_motion.h"
26 #include "av1/encoder/global_motion_facade.h"
27 #include "av1/encoder/intra_mode_search_utils.h"
28 #include "av1/encoder/picklpf.h"
29 #include "av1/encoder/rdopt.h"
30 #include "aom_dsp/aom_dsp_common.h"
31 #include "av1/encoder/temporal_filter.h"
32 #include "av1/encoder/tpl_model.h"
33 
accumulate_rd_opt(ThreadData * td,ThreadData * td_t)34 static AOM_INLINE void accumulate_rd_opt(ThreadData *td, ThreadData *td_t) {
35   td->rd_counts.compound_ref_used_flag |=
36       td_t->rd_counts.compound_ref_used_flag;
37   td->rd_counts.skip_mode_used_flag |= td_t->rd_counts.skip_mode_used_flag;
38 
39   for (int i = 0; i < TX_SIZES_ALL; i++) {
40     for (int j = 0; j < TX_TYPES; j++)
41       td->rd_counts.tx_type_used[i][j] += td_t->rd_counts.tx_type_used[i][j];
42   }
43 
44   for (int i = 0; i < BLOCK_SIZES_ALL; i++) {
45     for (int j = 0; j < 2; j++) {
46       td->rd_counts.obmc_used[i][j] += td_t->rd_counts.obmc_used[i][j];
47     }
48   }
49 
50   for (int i = 0; i < 2; i++) {
51     td->rd_counts.warped_used[i] += td_t->rd_counts.warped_used[i];
52   }
53 
54   td->rd_counts.seg_tmp_pred_cost[0] += td_t->rd_counts.seg_tmp_pred_cost[0];
55   td->rd_counts.seg_tmp_pred_cost[1] += td_t->rd_counts.seg_tmp_pred_cost[1];
56 
57   td->rd_counts.newmv_or_intra_blocks += td_t->rd_counts.newmv_or_intra_blocks;
58 }
59 
update_delta_lf_for_row_mt(AV1_COMP * cpi)60 static AOM_INLINE void update_delta_lf_for_row_mt(AV1_COMP *cpi) {
61   AV1_COMMON *cm = &cpi->common;
62   MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
63   const int mib_size = cm->seq_params->mib_size;
64   const int frame_lf_count =
65       av1_num_planes(cm) > 1 ? FRAME_LF_COUNT : FRAME_LF_COUNT - 2;
66   for (int row = 0; row < cm->tiles.rows; row++) {
67     for (int col = 0; col < cm->tiles.cols; col++) {
68       TileDataEnc *tile_data = &cpi->tile_data[row * cm->tiles.cols + col];
69       const TileInfo *const tile_info = &tile_data->tile_info;
70       for (int mi_row = tile_info->mi_row_start; mi_row < tile_info->mi_row_end;
71            mi_row += mib_size) {
72         if (mi_row == tile_info->mi_row_start)
73           av1_reset_loop_filter_delta(xd, av1_num_planes(cm));
74         for (int mi_col = tile_info->mi_col_start;
75              mi_col < tile_info->mi_col_end; mi_col += mib_size) {
76           const int idx_str = cm->mi_params.mi_stride * mi_row + mi_col;
77           MB_MODE_INFO **mi = cm->mi_params.mi_grid_base + idx_str;
78           MB_MODE_INFO *mbmi = mi[0];
79           if (mbmi->skip_txfm == 1 &&
80               (mbmi->bsize == cm->seq_params->sb_size)) {
81             for (int lf_id = 0; lf_id < frame_lf_count; ++lf_id)
82               mbmi->delta_lf[lf_id] = xd->delta_lf[lf_id];
83             mbmi->delta_lf_from_base = xd->delta_lf_from_base;
84           } else {
85             if (cm->delta_q_info.delta_lf_multi) {
86               for (int lf_id = 0; lf_id < frame_lf_count; ++lf_id)
87                 xd->delta_lf[lf_id] = mbmi->delta_lf[lf_id];
88             } else {
89               xd->delta_lf_from_base = mbmi->delta_lf_from_base;
90             }
91           }
92         }
93       }
94     }
95   }
96 }
97 
av1_row_mt_sync_read_dummy(AV1EncRowMultiThreadSync * row_mt_sync,int r,int c)98 void av1_row_mt_sync_read_dummy(AV1EncRowMultiThreadSync *row_mt_sync, int r,
99                                 int c) {
100   (void)row_mt_sync;
101   (void)r;
102   (void)c;
103   return;
104 }
105 
av1_row_mt_sync_write_dummy(AV1EncRowMultiThreadSync * row_mt_sync,int r,int c,int cols)106 void av1_row_mt_sync_write_dummy(AV1EncRowMultiThreadSync *row_mt_sync, int r,
107                                  int c, int cols) {
108   (void)row_mt_sync;
109   (void)r;
110   (void)c;
111   (void)cols;
112   return;
113 }
114 
av1_row_mt_sync_read(AV1EncRowMultiThreadSync * row_mt_sync,int r,int c)115 void av1_row_mt_sync_read(AV1EncRowMultiThreadSync *row_mt_sync, int r, int c) {
116 #if CONFIG_MULTITHREAD
117   const int nsync = row_mt_sync->sync_range;
118 
119   if (r) {
120     pthread_mutex_t *const mutex = &row_mt_sync->mutex_[r - 1];
121     pthread_mutex_lock(mutex);
122 
123     while (c > row_mt_sync->num_finished_cols[r - 1] - nsync -
124                    row_mt_sync->intrabc_extra_top_right_sb_delay) {
125       pthread_cond_wait(&row_mt_sync->cond_[r - 1], mutex);
126     }
127     pthread_mutex_unlock(mutex);
128   }
129 #else
130   (void)row_mt_sync;
131   (void)r;
132   (void)c;
133 #endif  // CONFIG_MULTITHREAD
134 }
135 
av1_row_mt_sync_write(AV1EncRowMultiThreadSync * row_mt_sync,int r,int c,int cols)136 void av1_row_mt_sync_write(AV1EncRowMultiThreadSync *row_mt_sync, int r, int c,
137                            int cols) {
138 #if CONFIG_MULTITHREAD
139   const int nsync = row_mt_sync->sync_range;
140   int cur;
141   // Only signal when there are enough encoded blocks for next row to run.
142   int sig = 1;
143 
144   if (c < cols - 1) {
145     cur = c;
146     if (c % nsync) sig = 0;
147   } else {
148     cur = cols + nsync + row_mt_sync->intrabc_extra_top_right_sb_delay;
149   }
150 
151   if (sig) {
152     pthread_mutex_lock(&row_mt_sync->mutex_[r]);
153 
154     row_mt_sync->num_finished_cols[r] = cur;
155 
156     pthread_cond_signal(&row_mt_sync->cond_[r]);
157     pthread_mutex_unlock(&row_mt_sync->mutex_[r]);
158   }
159 #else
160   (void)row_mt_sync;
161   (void)r;
162   (void)c;
163   (void)cols;
164 #endif  // CONFIG_MULTITHREAD
165 }
166 
167 // Allocate memory for row synchronization
row_mt_sync_mem_alloc(AV1EncRowMultiThreadSync * row_mt_sync,AV1_COMMON * cm,int rows)168 static void row_mt_sync_mem_alloc(AV1EncRowMultiThreadSync *row_mt_sync,
169                                   AV1_COMMON *cm, int rows) {
170 #if CONFIG_MULTITHREAD
171   int i;
172 
173   CHECK_MEM_ERROR(cm, row_mt_sync->mutex_,
174                   aom_malloc(sizeof(*row_mt_sync->mutex_) * rows));
175   if (row_mt_sync->mutex_) {
176     for (i = 0; i < rows; ++i) {
177       pthread_mutex_init(&row_mt_sync->mutex_[i], NULL);
178     }
179   }
180 
181   CHECK_MEM_ERROR(cm, row_mt_sync->cond_,
182                   aom_malloc(sizeof(*row_mt_sync->cond_) * rows));
183   if (row_mt_sync->cond_) {
184     for (i = 0; i < rows; ++i) {
185       pthread_cond_init(&row_mt_sync->cond_[i], NULL);
186     }
187   }
188 #endif  // CONFIG_MULTITHREAD
189 
190   CHECK_MEM_ERROR(cm, row_mt_sync->num_finished_cols,
191                   aom_malloc(sizeof(*row_mt_sync->num_finished_cols) * rows));
192 
193   row_mt_sync->rows = rows;
194   // Set up nsync.
195   row_mt_sync->sync_range = 1;
196 }
197 
198 // Deallocate row based multi-threading synchronization related mutex and data
row_mt_sync_mem_dealloc(AV1EncRowMultiThreadSync * row_mt_sync)199 static void row_mt_sync_mem_dealloc(AV1EncRowMultiThreadSync *row_mt_sync) {
200   if (row_mt_sync != NULL) {
201 #if CONFIG_MULTITHREAD
202     int i;
203 
204     if (row_mt_sync->mutex_ != NULL) {
205       for (i = 0; i < row_mt_sync->rows; ++i) {
206         pthread_mutex_destroy(&row_mt_sync->mutex_[i]);
207       }
208       aom_free(row_mt_sync->mutex_);
209     }
210     if (row_mt_sync->cond_ != NULL) {
211       for (i = 0; i < row_mt_sync->rows; ++i) {
212         pthread_cond_destroy(&row_mt_sync->cond_[i]);
213       }
214       aom_free(row_mt_sync->cond_);
215     }
216 #endif  // CONFIG_MULTITHREAD
217     aom_free(row_mt_sync->num_finished_cols);
218 
219     // clear the structure as the source of this call may be dynamic change
220     // in tiles in which case this call will be followed by an _alloc()
221     // which may fail.
222     av1_zero(*row_mt_sync);
223   }
224 }
225 
get_sb_rows_in_frame(AV1_COMMON * cm)226 static AOM_INLINE int get_sb_rows_in_frame(AV1_COMMON *cm) {
227   return CEIL_POWER_OF_TWO(cm->mi_params.mi_rows,
228                            cm->seq_params->mib_size_log2);
229 }
230 
row_mt_mem_alloc(AV1_COMP * cpi,int max_rows,int max_cols,int alloc_row_ctx)231 static void row_mt_mem_alloc(AV1_COMP *cpi, int max_rows, int max_cols,
232                              int alloc_row_ctx) {
233   struct AV1Common *cm = &cpi->common;
234   AV1EncRowMultiThreadInfo *const enc_row_mt = &cpi->mt_info.enc_row_mt;
235   const int tile_cols = cm->tiles.cols;
236   const int tile_rows = cm->tiles.rows;
237   int tile_col, tile_row;
238 
239   av1_row_mt_mem_dealloc(cpi);
240 
241   // Allocate memory for row based multi-threading
242   for (tile_row = 0; tile_row < tile_rows; tile_row++) {
243     for (tile_col = 0; tile_col < tile_cols; tile_col++) {
244       int tile_index = tile_row * tile_cols + tile_col;
245       TileDataEnc *const this_tile = &cpi->tile_data[tile_index];
246 
247       row_mt_sync_mem_alloc(&this_tile->row_mt_sync, cm, max_rows);
248 
249       this_tile->row_ctx = NULL;
250       if (alloc_row_ctx) {
251         assert(max_cols > 0);
252         const int num_row_ctx = AOMMAX(1, (max_cols - 1));
253         CHECK_MEM_ERROR(cm, this_tile->row_ctx,
254                         (FRAME_CONTEXT *)aom_memalign(
255                             16, num_row_ctx * sizeof(*this_tile->row_ctx)));
256       }
257     }
258   }
259   const int sb_rows = get_sb_rows_in_frame(cm);
260   CHECK_MEM_ERROR(
261       cm, enc_row_mt->num_tile_cols_done,
262       aom_malloc(sizeof(*enc_row_mt->num_tile_cols_done) * sb_rows));
263 
264   enc_row_mt->allocated_tile_cols = tile_cols;
265   enc_row_mt->allocated_tile_rows = tile_rows;
266   enc_row_mt->allocated_rows = max_rows;
267   enc_row_mt->allocated_cols = max_cols - 1;
268   enc_row_mt->allocated_sb_rows = sb_rows;
269 }
270 
av1_row_mt_mem_dealloc(AV1_COMP * cpi)271 void av1_row_mt_mem_dealloc(AV1_COMP *cpi) {
272   AV1EncRowMultiThreadInfo *const enc_row_mt = &cpi->mt_info.enc_row_mt;
273   const int tile_cols = enc_row_mt->allocated_tile_cols;
274   const int tile_rows = enc_row_mt->allocated_tile_rows;
275   int tile_col, tile_row;
276 
277   // Free row based multi-threading sync memory
278   for (tile_row = 0; tile_row < tile_rows; tile_row++) {
279     for (tile_col = 0; tile_col < tile_cols; tile_col++) {
280       int tile_index = tile_row * tile_cols + tile_col;
281       TileDataEnc *const this_tile = &cpi->tile_data[tile_index];
282 
283       row_mt_sync_mem_dealloc(&this_tile->row_mt_sync);
284 
285       if (cpi->oxcf.algo_cfg.cdf_update_mode) aom_free(this_tile->row_ctx);
286     }
287   }
288   aom_free(enc_row_mt->num_tile_cols_done);
289   enc_row_mt->num_tile_cols_done = NULL;
290   enc_row_mt->allocated_rows = 0;
291   enc_row_mt->allocated_cols = 0;
292   enc_row_mt->allocated_tile_cols = 0;
293   enc_row_mt->allocated_tile_rows = 0;
294   enc_row_mt->allocated_sb_rows = 0;
295 }
296 
assign_tile_to_thread(int * thread_id_to_tile_id,int num_tiles,int num_workers)297 static AOM_INLINE void assign_tile_to_thread(int *thread_id_to_tile_id,
298                                              int num_tiles, int num_workers) {
299   int tile_id = 0;
300   int i;
301 
302   for (i = 0; i < num_workers; i++) {
303     thread_id_to_tile_id[i] = tile_id++;
304     if (tile_id == num_tiles) tile_id = 0;
305   }
306 }
307 
get_next_job(TileDataEnc * const tile_data,int * current_mi_row,int mib_size)308 static AOM_INLINE int get_next_job(TileDataEnc *const tile_data,
309                                    int *current_mi_row, int mib_size) {
310   AV1EncRowMultiThreadSync *const row_mt_sync = &tile_data->row_mt_sync;
311   const int mi_row_end = tile_data->tile_info.mi_row_end;
312 
313   if (row_mt_sync->next_mi_row < mi_row_end) {
314     *current_mi_row = row_mt_sync->next_mi_row;
315     row_mt_sync->num_threads_working++;
316     row_mt_sync->next_mi_row += mib_size;
317     return 1;
318   }
319   return 0;
320 }
321 
switch_tile_and_get_next_job(AV1_COMMON * const cm,TileDataEnc * const tile_data,int * cur_tile_id,int * current_mi_row,int * end_of_frame,int is_firstpass,const BLOCK_SIZE fp_block_size)322 static AOM_INLINE void switch_tile_and_get_next_job(
323     AV1_COMMON *const cm, TileDataEnc *const tile_data, int *cur_tile_id,
324     int *current_mi_row, int *end_of_frame, int is_firstpass,
325     const BLOCK_SIZE fp_block_size) {
326   const int tile_cols = cm->tiles.cols;
327   const int tile_rows = cm->tiles.rows;
328 
329   int tile_id = -1;  // Stores the tile ID with minimum proc done
330   int max_mis_to_encode = 0;
331   int min_num_threads_working = INT_MAX;
332 
333   for (int tile_row = 0; tile_row < tile_rows; tile_row++) {
334     for (int tile_col = 0; tile_col < tile_cols; tile_col++) {
335       int tile_index = tile_row * tile_cols + tile_col;
336       TileDataEnc *const this_tile = &tile_data[tile_index];
337       AV1EncRowMultiThreadSync *const row_mt_sync = &this_tile->row_mt_sync;
338 
339 #if CONFIG_REALTIME_ONLY
340       int num_b_rows_in_tile =
341           av1_get_sb_rows_in_tile(cm, &this_tile->tile_info);
342       int num_b_cols_in_tile =
343           av1_get_sb_cols_in_tile(cm, &this_tile->tile_info);
344 #else
345       int num_b_rows_in_tile =
346           is_firstpass
347               ? av1_get_unit_rows_in_tile(&this_tile->tile_info, fp_block_size)
348               : av1_get_sb_rows_in_tile(cm, &this_tile->tile_info);
349       int num_b_cols_in_tile =
350           is_firstpass
351               ? av1_get_unit_cols_in_tile(&this_tile->tile_info, fp_block_size)
352               : av1_get_sb_cols_in_tile(cm, &this_tile->tile_info);
353 #endif
354       int theoretical_limit_on_threads =
355           AOMMIN((num_b_cols_in_tile + 1) >> 1, num_b_rows_in_tile);
356       int num_threads_working = row_mt_sync->num_threads_working;
357 
358       if (num_threads_working < theoretical_limit_on_threads) {
359         int num_mis_to_encode =
360             this_tile->tile_info.mi_row_end - row_mt_sync->next_mi_row;
361 
362         // Tile to be processed by this thread is selected on the basis of
363         // availability of jobs:
364         // 1) If jobs are available, tile to be processed is chosen on the
365         // basis of minimum number of threads working for that tile. If two or
366         // more tiles have same number of threads working for them, then the
367         // tile with maximum number of jobs available will be chosen.
368         // 2) If no jobs are available, then end_of_frame is reached.
369         if (num_mis_to_encode > 0) {
370           if (num_threads_working < min_num_threads_working) {
371             min_num_threads_working = num_threads_working;
372             max_mis_to_encode = 0;
373           }
374           if (num_threads_working == min_num_threads_working &&
375               num_mis_to_encode > max_mis_to_encode) {
376             tile_id = tile_index;
377             max_mis_to_encode = num_mis_to_encode;
378           }
379         }
380       }
381     }
382   }
383   if (tile_id == -1) {
384     *end_of_frame = 1;
385   } else {
386     // Update the current tile id to the tile id that will be processed next,
387     // which will be the least processed tile.
388     *cur_tile_id = tile_id;
389     const int unit_height = mi_size_high[fp_block_size];
390     get_next_job(&tile_data[tile_id], current_mi_row,
391                  is_firstpass ? unit_height : cm->seq_params->mib_size);
392   }
393 }
394 
395 #if !CONFIG_REALTIME_ONLY
fp_enc_row_mt_worker_hook(void * arg1,void * unused)396 static int fp_enc_row_mt_worker_hook(void *arg1, void *unused) {
397   EncWorkerData *const thread_data = (EncWorkerData *)arg1;
398   AV1_COMP *const cpi = thread_data->cpi;
399   AV1_COMMON *const cm = &cpi->common;
400   int thread_id = thread_data->thread_id;
401   AV1EncRowMultiThreadInfo *const enc_row_mt = &cpi->mt_info.enc_row_mt;
402   int cur_tile_id = enc_row_mt->thread_id_to_tile_id[thread_id];
403 #if CONFIG_MULTITHREAD
404   pthread_mutex_t *enc_row_mt_mutex_ = enc_row_mt->mutex_;
405 #endif
406   (void)unused;
407 
408   assert(cur_tile_id != -1);
409 
410   const BLOCK_SIZE fp_block_size = cpi->fp_block_size;
411   const int unit_height = mi_size_high[fp_block_size];
412   int end_of_frame = 0;
413   while (1) {
414     int current_mi_row = -1;
415 #if CONFIG_MULTITHREAD
416     pthread_mutex_lock(enc_row_mt_mutex_);
417 #endif
418     if (!get_next_job(&cpi->tile_data[cur_tile_id], &current_mi_row,
419                       unit_height)) {
420       // No jobs are available for the current tile. Query for the status of
421       // other tiles and get the next job if available
422       switch_tile_and_get_next_job(cm, cpi->tile_data, &cur_tile_id,
423                                    &current_mi_row, &end_of_frame, 1,
424                                    fp_block_size);
425     }
426 #if CONFIG_MULTITHREAD
427     pthread_mutex_unlock(enc_row_mt_mutex_);
428 #endif
429     if (end_of_frame == 1) break;
430 
431     TileDataEnc *const this_tile = &cpi->tile_data[cur_tile_id];
432     AV1EncRowMultiThreadSync *const row_mt_sync = &this_tile->row_mt_sync;
433     ThreadData *td = thread_data->td;
434 
435     assert(current_mi_row != -1 &&
436            current_mi_row < this_tile->tile_info.mi_row_end);
437 
438     const int unit_height_log2 = mi_size_high_log2[fp_block_size];
439     av1_first_pass_row(cpi, td, this_tile, current_mi_row >> unit_height_log2,
440                        fp_block_size);
441 #if CONFIG_MULTITHREAD
442     pthread_mutex_lock(enc_row_mt_mutex_);
443 #endif
444     row_mt_sync->num_threads_working--;
445 #if CONFIG_MULTITHREAD
446     pthread_mutex_unlock(enc_row_mt_mutex_);
447 #endif
448   }
449 
450   return 1;
451 }
452 #endif
453 
launch_loop_filter_rows(AV1_COMMON * cm,EncWorkerData * thread_data,AV1EncRowMultiThreadInfo * enc_row_mt,int mib_size_log2)454 static void launch_loop_filter_rows(AV1_COMMON *cm, EncWorkerData *thread_data,
455                                     AV1EncRowMultiThreadInfo *enc_row_mt,
456                                     int mib_size_log2) {
457   AV1LfSync *const lf_sync = (AV1LfSync *)thread_data->lf_sync;
458   const int sb_rows = get_sb_rows_in_frame(cm);
459   AV1LfMTInfo *cur_job_info;
460   (void)enc_row_mt;
461 #if CONFIG_MULTITHREAD
462   pthread_mutex_t *enc_row_mt_mutex_ = enc_row_mt->mutex_;
463 #endif
464 
465   while ((cur_job_info = get_lf_job_info(lf_sync)) != NULL) {
466     LFWorkerData *const lf_data = (LFWorkerData *)thread_data->lf_data;
467     const int lpf_opt_level = cur_job_info->lpf_opt_level;
468     (void)sb_rows;
469 #if CONFIG_MULTITHREAD
470     const int cur_sb_row = cur_job_info->mi_row >> mib_size_log2;
471     const int next_sb_row = AOMMIN(sb_rows - 1, cur_sb_row + 1);
472     // Wait for current and next superblock row to finish encoding.
473     pthread_mutex_lock(enc_row_mt_mutex_);
474     while (enc_row_mt->num_tile_cols_done[cur_sb_row] < cm->tiles.cols ||
475            enc_row_mt->num_tile_cols_done[next_sb_row] < cm->tiles.cols) {
476       pthread_cond_wait(enc_row_mt->cond_, enc_row_mt_mutex_);
477     }
478     pthread_mutex_unlock(enc_row_mt_mutex_);
479 #endif
480     av1_thread_loop_filter_rows(
481         lf_data->frame_buffer, lf_data->cm, lf_data->planes, lf_data->xd,
482         cur_job_info->mi_row, cur_job_info->plane, cur_job_info->dir,
483         lpf_opt_level, lf_sync, lf_data->params_buf, lf_data->tx_buf,
484         mib_size_log2);
485   }
486 }
487 
enc_row_mt_worker_hook(void * arg1,void * unused)488 static int enc_row_mt_worker_hook(void *arg1, void *unused) {
489   EncWorkerData *const thread_data = (EncWorkerData *)arg1;
490   AV1_COMP *const cpi = thread_data->cpi;
491   AV1_COMMON *const cm = &cpi->common;
492   int thread_id = thread_data->thread_id;
493   AV1EncRowMultiThreadInfo *const enc_row_mt = &cpi->mt_info.enc_row_mt;
494   int cur_tile_id = enc_row_mt->thread_id_to_tile_id[thread_id];
495   const int mib_size_log2 = cm->seq_params->mib_size_log2;
496 #if CONFIG_MULTITHREAD
497   pthread_mutex_t *enc_row_mt_mutex_ = enc_row_mt->mutex_;
498 #endif
499   (void)unused;
500   // Preallocate the pc_tree for realtime coding to reduce the cost of memory
501   // allocation.
502   thread_data->td->rt_pc_root =
503       cpi->sf.rt_sf.use_nonrd_pick_mode
504           ? av1_alloc_pc_tree_node(cm->seq_params->sb_size)
505           : NULL;
506 
507   assert(cur_tile_id != -1);
508 
509   const BLOCK_SIZE fp_block_size = cpi->fp_block_size;
510   int end_of_frame = 0;
511 
512   // When master thread does not have a valid job to process, xd->tile_ctx
513   // is not set and it contains NULL pointer. This can result in NULL pointer
514   // access violation if accessed beyond the encode stage. Hence, updating
515   // thread_data->td->mb.e_mbd.tile_ctx is initialized with common frame
516   // context to avoid NULL pointer access in subsequent stages.
517   thread_data->td->mb.e_mbd.tile_ctx = cm->fc;
518   while (1) {
519     int current_mi_row = -1;
520 #if CONFIG_MULTITHREAD
521     pthread_mutex_lock(enc_row_mt_mutex_);
522 #endif
523     if (!get_next_job(&cpi->tile_data[cur_tile_id], &current_mi_row,
524                       cm->seq_params->mib_size)) {
525       // No jobs are available for the current tile. Query for the status of
526       // other tiles and get the next job if available
527       switch_tile_and_get_next_job(cm, cpi->tile_data, &cur_tile_id,
528                                    &current_mi_row, &end_of_frame, 0,
529                                    fp_block_size);
530     }
531 #if CONFIG_MULTITHREAD
532     pthread_mutex_unlock(enc_row_mt_mutex_);
533 #endif
534     if (end_of_frame == 1) break;
535 
536     TileDataEnc *const this_tile = &cpi->tile_data[cur_tile_id];
537     AV1EncRowMultiThreadSync *const row_mt_sync = &this_tile->row_mt_sync;
538     const TileInfo *const tile_info = &this_tile->tile_info;
539     const int tile_row = tile_info->tile_row;
540     const int tile_col = tile_info->tile_col;
541     ThreadData *td = thread_data->td;
542     const int sb_row = current_mi_row >> mib_size_log2;
543 
544     assert(current_mi_row != -1 && current_mi_row <= tile_info->mi_row_end);
545 
546     td->mb.e_mbd.tile_ctx = td->tctx;
547     td->mb.tile_pb_ctx = &this_tile->tctx;
548     td->abs_sum_level = 0;
549 
550     if (this_tile->allow_update_cdf) {
551       td->mb.row_ctx = this_tile->row_ctx;
552       if (current_mi_row == tile_info->mi_row_start)
553         memcpy(td->mb.e_mbd.tile_ctx, &this_tile->tctx, sizeof(FRAME_CONTEXT));
554     } else {
555       memcpy(td->mb.e_mbd.tile_ctx, &this_tile->tctx, sizeof(FRAME_CONTEXT));
556     }
557 
558     av1_init_above_context(&cm->above_contexts, av1_num_planes(cm), tile_row,
559                            &td->mb.e_mbd);
560 
561     cfl_init(&td->mb.e_mbd.cfl, cm->seq_params);
562     if (td->mb.txfm_search_info.mb_rd_record != NULL) {
563       av1_crc32c_calculator_init(
564           &td->mb.txfm_search_info.mb_rd_record->crc_calculator);
565     }
566 
567     av1_encode_sb_row(cpi, td, tile_row, tile_col, current_mi_row);
568 #if CONFIG_MULTITHREAD
569     pthread_mutex_lock(enc_row_mt_mutex_);
570 #endif
571     this_tile->abs_sum_level += td->abs_sum_level;
572     row_mt_sync->num_threads_working--;
573     enc_row_mt->num_tile_cols_done[sb_row]++;
574 #if CONFIG_MULTITHREAD
575     pthread_cond_broadcast(enc_row_mt->cond_);
576     pthread_mutex_unlock(enc_row_mt_mutex_);
577 #endif
578   }
579   if (cpi->mt_info.pipeline_lpf_mt_with_enc &&
580       (cm->lf.filter_level[PLANE_TYPE_Y] ||
581        cm->lf.filter_level[PLANE_TYPE_UV])) {
582     // Loop-filter a superblock row if encoding of the current and next
583     // superblock row is complete.
584     // TODO(deepa.kg @ittiam.com) Evaluate encoder speed by interleaving
585     // encoding and loop filter stage.
586     launch_loop_filter_rows(cm, thread_data, enc_row_mt, mib_size_log2);
587   }
588   av1_free_pc_tree_recursive(thread_data->td->rt_pc_root, av1_num_planes(cm), 0,
589                              0);
590   return 1;
591 }
592 
enc_worker_hook(void * arg1,void * unused)593 static int enc_worker_hook(void *arg1, void *unused) {
594   EncWorkerData *const thread_data = (EncWorkerData *)arg1;
595   AV1_COMP *const cpi = thread_data->cpi;
596   const AV1_COMMON *const cm = &cpi->common;
597   const int tile_cols = cm->tiles.cols;
598   const int tile_rows = cm->tiles.rows;
599   int t;
600 
601   (void)unused;
602   // Preallocate the pc_tree for realtime coding to reduce the cost of memory
603   // allocation.
604   thread_data->td->rt_pc_root =
605       cpi->sf.rt_sf.use_nonrd_pick_mode
606           ? av1_alloc_pc_tree_node(cm->seq_params->sb_size)
607           : NULL;
608 
609   for (t = thread_data->start; t < tile_rows * tile_cols;
610        t += cpi->mt_info.num_workers) {
611     int tile_row = t / tile_cols;
612     int tile_col = t % tile_cols;
613 
614     TileDataEnc *const this_tile =
615         &cpi->tile_data[tile_row * cm->tiles.cols + tile_col];
616     thread_data->td->mb.e_mbd.tile_ctx = &this_tile->tctx;
617     thread_data->td->mb.tile_pb_ctx = &this_tile->tctx;
618     av1_encode_tile(cpi, thread_data->td, tile_row, tile_col);
619   }
620 
621   av1_free_pc_tree_recursive(thread_data->td->rt_pc_root, av1_num_planes(cm), 0,
622                              0);
623 
624   return 1;
625 }
626 
av1_init_frame_mt(AV1_PRIMARY * ppi,AV1_COMP * cpi)627 void av1_init_frame_mt(AV1_PRIMARY *ppi, AV1_COMP *cpi) {
628   cpi->mt_info.workers = ppi->p_mt_info.workers;
629   cpi->mt_info.num_workers = ppi->p_mt_info.num_workers;
630   cpi->mt_info.tile_thr_data = ppi->p_mt_info.tile_thr_data;
631   int i;
632   for (i = MOD_FP; i < NUM_MT_MODULES; i++) {
633     cpi->mt_info.num_mod_workers[i] =
634         AOMMIN(cpi->mt_info.num_workers, ppi->p_mt_info.num_mod_workers[i]);
635   }
636 }
637 
av1_init_cdef_worker(AV1_COMP * cpi)638 void av1_init_cdef_worker(AV1_COMP *cpi) {
639   // The allocation is done only for level 0 parallel frames. No change
640   // in config is supported in the middle of a parallel encode set, since the
641   // rest of the MT modules also do not support dynamic change of config.
642   if (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) return;
643   PrimaryMultiThreadInfo *const p_mt_info = &cpi->ppi->p_mt_info;
644   int num_cdef_workers = av1_get_num_mod_workers_for_alloc(p_mt_info, MOD_CDEF);
645 
646   av1_alloc_cdef_buffers(&cpi->common, &p_mt_info->cdef_worker,
647                          &cpi->mt_info.cdef_sync, num_cdef_workers, 1);
648   cpi->mt_info.cdef_worker = p_mt_info->cdef_worker;
649 }
650 
651 #if !CONFIG_REALTIME_ONLY
av1_init_lr_mt_buffers(AV1_COMP * cpi)652 void av1_init_lr_mt_buffers(AV1_COMP *cpi) {
653   AV1_COMMON *const cm = &cpi->common;
654   AV1LrSync *lr_sync = &cpi->mt_info.lr_row_sync;
655   if (lr_sync->sync_range) {
656     int num_lr_workers =
657         av1_get_num_mod_workers_for_alloc(&cpi->ppi->p_mt_info, MOD_LR);
658     if (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
659       return;
660     lr_sync->lrworkerdata[num_lr_workers - 1].rst_tmpbuf = cm->rst_tmpbuf;
661     lr_sync->lrworkerdata[num_lr_workers - 1].rlbs = cm->rlbs;
662   }
663 }
664 #endif
665 
666 #if CONFIG_MULTITHREAD
av1_init_mt_sync(AV1_COMP * cpi,int is_first_pass)667 void av1_init_mt_sync(AV1_COMP *cpi, int is_first_pass) {
668   AV1_COMMON *const cm = &cpi->common;
669   MultiThreadInfo *const mt_info = &cpi->mt_info;
670 
671   // Initialize enc row MT object.
672   if (is_first_pass || cpi->oxcf.row_mt == 1) {
673     AV1EncRowMultiThreadInfo *enc_row_mt = &mt_info->enc_row_mt;
674     if (enc_row_mt->mutex_ == NULL) {
675       CHECK_MEM_ERROR(cm, enc_row_mt->mutex_,
676                       aom_malloc(sizeof(*(enc_row_mt->mutex_))));
677       if (enc_row_mt->mutex_) pthread_mutex_init(enc_row_mt->mutex_, NULL);
678     }
679     if (enc_row_mt->cond_ == NULL) {
680       CHECK_MEM_ERROR(cm, enc_row_mt->cond_,
681                       aom_malloc(sizeof(*(enc_row_mt->cond_))));
682       if (enc_row_mt->cond_) pthread_cond_init(enc_row_mt->cond_, NULL);
683     }
684   }
685 
686   if (!is_first_pass) {
687     // Initialize global motion MT object.
688     AV1GlobalMotionSync *gm_sync = &mt_info->gm_sync;
689     if (gm_sync->mutex_ == NULL) {
690       CHECK_MEM_ERROR(cm, gm_sync->mutex_,
691                       aom_malloc(sizeof(*(gm_sync->mutex_))));
692       if (gm_sync->mutex_) pthread_mutex_init(gm_sync->mutex_, NULL);
693     }
694 #if !CONFIG_REALTIME_ONLY
695     // Initialize temporal filtering MT object.
696     AV1TemporalFilterSync *tf_sync = &mt_info->tf_sync;
697     if (tf_sync->mutex_ == NULL) {
698       CHECK_MEM_ERROR(cm, tf_sync->mutex_,
699                       aom_malloc(sizeof(*tf_sync->mutex_)));
700       if (tf_sync->mutex_) pthread_mutex_init(tf_sync->mutex_, NULL);
701     }
702 #endif  // !CONFIG_REALTIME_ONLY
703         // Initialize CDEF MT object.
704     AV1CdefSync *cdef_sync = &mt_info->cdef_sync;
705     if (cdef_sync->mutex_ == NULL) {
706       CHECK_MEM_ERROR(cm, cdef_sync->mutex_,
707                       aom_malloc(sizeof(*(cdef_sync->mutex_))));
708       if (cdef_sync->mutex_) pthread_mutex_init(cdef_sync->mutex_, NULL);
709     }
710 
711     // Initialize loop filter MT object.
712     AV1LfSync *lf_sync = &mt_info->lf_row_sync;
713     // Number of superblock rows
714     const int sb_rows =
715         CEIL_POWER_OF_TWO(cm->height >> MI_SIZE_LOG2, MAX_MIB_SIZE_LOG2);
716     PrimaryMultiThreadInfo *const p_mt_info = &cpi->ppi->p_mt_info;
717     int num_lf_workers = av1_get_num_mod_workers_for_alloc(p_mt_info, MOD_LPF);
718 
719     if (!lf_sync->sync_range || sb_rows != lf_sync->rows ||
720         num_lf_workers > lf_sync->num_workers) {
721       av1_loop_filter_dealloc(lf_sync);
722       av1_loop_filter_alloc(lf_sync, cm, sb_rows, cm->width, num_lf_workers);
723     }
724 
725 #if !CONFIG_REALTIME_ONLY
726     if (is_restoration_used(cm)) {
727       // Initialize loop restoration MT object.
728       AV1LrSync *lr_sync = &mt_info->lr_row_sync;
729       int rst_unit_size;
730       if (cm->width * cm->height > 352 * 288)
731         rst_unit_size = RESTORATION_UNITSIZE_MAX;
732       else
733         rst_unit_size = (RESTORATION_UNITSIZE_MAX >> 1);
734       int num_rows_lr = av1_lr_count_units_in_tile(rst_unit_size, cm->height);
735       int num_lr_workers = av1_get_num_mod_workers_for_alloc(p_mt_info, MOD_LR);
736       if (!lr_sync->sync_range || num_rows_lr > lr_sync->rows ||
737           num_lr_workers > lr_sync->num_workers ||
738           MAX_MB_PLANE > lr_sync->num_planes) {
739         av1_loop_restoration_dealloc(lr_sync, num_lr_workers);
740         av1_loop_restoration_alloc(lr_sync, cm, num_lr_workers, num_rows_lr,
741                                    MAX_MB_PLANE, cm->width);
742       }
743     }
744 #endif
745 
746     // Initialization of pack bitstream MT object.
747     AV1EncPackBSSync *pack_bs_sync = &mt_info->pack_bs_sync;
748     if (pack_bs_sync->mutex_ == NULL) {
749       CHECK_MEM_ERROR(cm, pack_bs_sync->mutex_,
750                       aom_malloc(sizeof(*pack_bs_sync->mutex_)));
751       if (pack_bs_sync->mutex_) pthread_mutex_init(pack_bs_sync->mutex_, NULL);
752     }
753   }
754 }
755 #endif  // CONFIG_MULTITHREAD
756 
757 // Computes the number of workers to be considered while allocating memory for a
758 // multi-threaded module under FPMT.
av1_get_num_mod_workers_for_alloc(PrimaryMultiThreadInfo * const p_mt_info,MULTI_THREADED_MODULES mod_name)759 int av1_get_num_mod_workers_for_alloc(PrimaryMultiThreadInfo *const p_mt_info,
760                                       MULTI_THREADED_MODULES mod_name) {
761   int num_mod_workers = p_mt_info->num_mod_workers[mod_name];
762   if (p_mt_info->num_mod_workers[MOD_FRAME_ENC] > 1) {
763     // TODO(anyone): Change num_mod_workers to num_mod_workers[MOD_FRAME_ENC].
764     // As frame parallel jobs will only perform multi-threading for the encode
765     // stage, we can limit the allocations according to num_enc_workers per
766     // frame parallel encode(a.k.a num_mod_workers[MOD_FRAME_ENC]).
767     num_mod_workers = p_mt_info->num_workers;
768   }
769   return num_mod_workers;
770 }
771 
av1_init_tile_thread_data(AV1_PRIMARY * ppi,int is_first_pass)772 void av1_init_tile_thread_data(AV1_PRIMARY *ppi, int is_first_pass) {
773   PrimaryMultiThreadInfo *const p_mt_info = &ppi->p_mt_info;
774 
775   assert(p_mt_info->workers != NULL);
776   assert(p_mt_info->tile_thr_data != NULL);
777 
778   int num_workers = p_mt_info->num_workers;
779   int num_enc_workers = av1_get_num_mod_workers_for_alloc(p_mt_info, MOD_ENC);
780   for (int i = num_workers - 1; i >= 0; i--) {
781     EncWorkerData *const thread_data = &p_mt_info->tile_thr_data[i];
782 
783     if (i > 0) {
784       // Allocate thread data.
785       AOM_CHECK_MEM_ERROR(&ppi->error, thread_data->td,
786                           aom_memalign(32, sizeof(*thread_data->td)));
787       av1_zero(*thread_data->td);
788       thread_data->original_td = thread_data->td;
789 
790       // Set up shared coeff buffers.
791       av1_setup_shared_coeff_buffer(
792           &ppi->seq_params, &thread_data->td->shared_coeff_buf, &ppi->error);
793       AOM_CHECK_MEM_ERROR(
794           &ppi->error, thread_data->td->tmp_conv_dst,
795           aom_memalign(32, MAX_SB_SIZE * MAX_SB_SIZE *
796                                sizeof(*thread_data->td->tmp_conv_dst)));
797 
798       if (i < p_mt_info->num_mod_workers[MOD_FP]) {
799         // Set up firstpass PICK_MODE_CONTEXT.
800         thread_data->td->firstpass_ctx = av1_alloc_pmc(
801             ppi->cpi, BLOCK_16X16, &thread_data->td->shared_coeff_buf);
802       }
803 
804       if (!is_first_pass && i < num_enc_workers) {
805         // Set up sms_tree.
806         av1_setup_sms_tree(ppi->cpi, thread_data->td);
807 
808         for (int x = 0; x < 2; x++)
809           for (int y = 0; y < 2; y++)
810             AOM_CHECK_MEM_ERROR(
811                 &ppi->error, thread_data->td->hash_value_buffer[x][y],
812                 (uint32_t *)aom_malloc(
813                     AOM_BUFFER_SIZE_FOR_BLOCK_HASH *
814                     sizeof(*thread_data->td->hash_value_buffer[0][0])));
815 
816         // Allocate frame counters in thread data.
817         AOM_CHECK_MEM_ERROR(&ppi->error, thread_data->td->counts,
818                             aom_calloc(1, sizeof(*thread_data->td->counts)));
819 
820         // Allocate buffers used by palette coding mode.
821         AOM_CHECK_MEM_ERROR(
822             &ppi->error, thread_data->td->palette_buffer,
823             aom_memalign(16, sizeof(*thread_data->td->palette_buffer)));
824 
825         // The buffers 'tmp_pred_bufs[]', 'comp_rd_buffer' and 'obmc_buffer' are
826         // used in inter frames to store intermediate inter mode prediction
827         // results and are not required for allintra encoding mode. Hence, the
828         // memory allocations for these buffers are avoided for allintra
829         // encoding mode.
830         if (ppi->cpi->oxcf.kf_cfg.key_freq_max != 0) {
831           alloc_obmc_buffers(&thread_data->td->obmc_buffer, &ppi->error);
832 
833           alloc_compound_type_rd_buffers(&ppi->error,
834                                          &thread_data->td->comp_rd_buffer);
835 
836           for (int j = 0; j < 2; ++j) {
837             AOM_CHECK_MEM_ERROR(
838                 &ppi->error, thread_data->td->tmp_pred_bufs[j],
839                 aom_memalign(32,
840                              2 * MAX_MB_PLANE * MAX_SB_SQUARE *
841                                  sizeof(*thread_data->td->tmp_pred_bufs[j])));
842           }
843         }
844 
845         if (is_gradient_caching_for_hog_enabled(ppi->cpi)) {
846           const int plane_types = PLANE_TYPES >> ppi->seq_params.monochrome;
847           AOM_CHECK_MEM_ERROR(
848               &ppi->error, thread_data->td->pixel_gradient_info,
849               aom_malloc(sizeof(*thread_data->td->pixel_gradient_info) *
850                          plane_types * MAX_SB_SQUARE));
851         }
852 
853         if (is_src_var_for_4x4_sub_blocks_caching_enabled(ppi->cpi)) {
854           const BLOCK_SIZE sb_size = ppi->cpi->common.seq_params->sb_size;
855           const int mi_count_in_sb =
856               mi_size_wide[sb_size] * mi_size_high[sb_size];
857 
858           AOM_CHECK_MEM_ERROR(
859               &ppi->error, thread_data->td->src_var_info_of_4x4_sub_blocks,
860               aom_malloc(
861                   sizeof(*thread_data->td->src_var_info_of_4x4_sub_blocks) *
862                   mi_count_in_sb));
863         }
864 
865         if (ppi->cpi->sf.part_sf.partition_search_type == VAR_BASED_PARTITION) {
866           const int num_64x64_blocks =
867               (ppi->seq_params.sb_size == BLOCK_64X64) ? 1 : 4;
868           AOM_CHECK_MEM_ERROR(
869               &ppi->error, thread_data->td->vt64x64,
870               aom_malloc(sizeof(*thread_data->td->vt64x64) * num_64x64_blocks));
871         }
872       }
873     }
874 
875     if (!is_first_pass && ppi->cpi->oxcf.row_mt == 1 && i < num_enc_workers) {
876       if (i == 0) {
877         for (int j = 0; j < ppi->num_fp_contexts; j++) {
878           AOM_CHECK_MEM_ERROR(&ppi->error, ppi->parallel_cpi[j]->td.tctx,
879                               (FRAME_CONTEXT *)aom_memalign(
880                                   16, sizeof(*ppi->parallel_cpi[j]->td.tctx)));
881         }
882       } else {
883         AOM_CHECK_MEM_ERROR(
884             &ppi->error, thread_data->td->tctx,
885             (FRAME_CONTEXT *)aom_memalign(16, sizeof(*thread_data->td->tctx)));
886       }
887     }
888   }
889 }
890 
av1_create_workers(AV1_PRIMARY * ppi,int num_workers)891 void av1_create_workers(AV1_PRIMARY *ppi, int num_workers) {
892   PrimaryMultiThreadInfo *const p_mt_info = &ppi->p_mt_info;
893   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
894 
895   AOM_CHECK_MEM_ERROR(&ppi->error, p_mt_info->workers,
896                       aom_malloc(num_workers * sizeof(*p_mt_info->workers)));
897 
898   AOM_CHECK_MEM_ERROR(
899       &ppi->error, p_mt_info->tile_thr_data,
900       aom_calloc(num_workers, sizeof(*p_mt_info->tile_thr_data)));
901 
902   for (int i = num_workers - 1; i >= 0; i--) {
903     AVxWorker *const worker = &p_mt_info->workers[i];
904     EncWorkerData *const thread_data = &p_mt_info->tile_thr_data[i];
905 
906     winterface->init(worker);
907     worker->thread_name = "aom enc worker";
908 
909     thread_data->thread_id = i;
910     // Set the starting tile for each thread.
911     thread_data->start = i;
912 
913     if (i > 0) {
914       // Create threads
915       if (!winterface->reset(worker))
916         aom_internal_error(&ppi->error, AOM_CODEC_ERROR,
917                            "Tile encoder thread creation failed");
918     }
919     winterface->sync(worker);
920 
921     ++p_mt_info->num_workers;
922   }
923 }
924 
925 // This function returns 1 if frame parallel encode is supported for
926 // the current configuration. Returns 0 otherwise.
is_fpmt_config(AV1_PRIMARY * ppi,AV1EncoderConfig * oxcf)927 static AOM_INLINE int is_fpmt_config(AV1_PRIMARY *ppi, AV1EncoderConfig *oxcf) {
928   // FPMT is enabled for AOM_Q and AOM_VBR.
929   // TODO(Tarun): Test and enable resize config.
930   if (oxcf->rc_cfg.mode == AOM_CBR || oxcf->rc_cfg.mode == AOM_CQ) {
931     return 0;
932   }
933   if (ppi->use_svc) {
934     return 0;
935   }
936   if (oxcf->tile_cfg.enable_large_scale_tile) {
937     return 0;
938   }
939   if (oxcf->dec_model_cfg.timing_info_present) {
940     return 0;
941   }
942   if (oxcf->mode != GOOD) {
943     return 0;
944   }
945   if (oxcf->tool_cfg.error_resilient_mode) {
946     return 0;
947   }
948   if (oxcf->resize_cfg.resize_mode) {
949     return 0;
950   }
951   if (oxcf->pass != AOM_RC_SECOND_PASS) {
952     return 0;
953   }
954   if (oxcf->max_threads < 2) {
955     return 0;
956   }
957   if (!oxcf->fp_mt) {
958     return 0;
959   }
960 
961   return 1;
962 }
963 
av1_check_fpmt_config(AV1_PRIMARY * const ppi,AV1EncoderConfig * const oxcf)964 int av1_check_fpmt_config(AV1_PRIMARY *const ppi,
965                           AV1EncoderConfig *const oxcf) {
966   if (is_fpmt_config(ppi, oxcf)) return 1;
967   // Reset frame parallel configuration for unsupported config
968   if (ppi->num_fp_contexts > 1) {
969     for (int i = 1; i < ppi->num_fp_contexts; i++) {
970       // Release the previously-used frame-buffer
971       if (ppi->parallel_cpi[i]->common.cur_frame != NULL) {
972         --ppi->parallel_cpi[i]->common.cur_frame->ref_count;
973         ppi->parallel_cpi[i]->common.cur_frame = NULL;
974       }
975     }
976 
977     int cur_gf_index = ppi->cpi->gf_frame_index;
978     int reset_size = AOMMAX(0, ppi->gf_group.size - cur_gf_index);
979     av1_zero_array(&ppi->gf_group.frame_parallel_level[cur_gf_index],
980                    reset_size);
981     av1_zero_array(&ppi->gf_group.is_frame_non_ref[cur_gf_index], reset_size);
982     av1_zero_array(&ppi->gf_group.src_offset[cur_gf_index], reset_size);
983     memset(&ppi->gf_group.skip_frame_refresh[cur_gf_index][0], INVALID_IDX,
984            sizeof(ppi->gf_group.skip_frame_refresh[cur_gf_index][0]) *
985                reset_size * REF_FRAMES);
986     memset(&ppi->gf_group.skip_frame_as_ref[cur_gf_index], INVALID_IDX,
987            sizeof(ppi->gf_group.skip_frame_as_ref[cur_gf_index]) * reset_size);
988     ppi->num_fp_contexts = 1;
989   }
990   return 0;
991 }
992 
993 // A large value for threads used to compute the max num_enc_workers
994 // possible for each resolution.
995 #define MAX_THREADS 100
996 
997 // Computes the max number of enc workers possible for each resolution.
compute_max_num_enc_workers(CommonModeInfoParams * const mi_params,int mib_size_log2)998 static AOM_INLINE int compute_max_num_enc_workers(
999     CommonModeInfoParams *const mi_params, int mib_size_log2) {
1000   int num_sb_rows = CEIL_POWER_OF_TWO(mi_params->mi_rows, mib_size_log2);
1001   int num_sb_cols = CEIL_POWER_OF_TWO(mi_params->mi_cols, mib_size_log2);
1002 
1003   return AOMMIN((num_sb_cols + 1) >> 1, num_sb_rows);
1004 }
1005 
1006 // Computes the number of frame parallel(fp) contexts to be created
1007 // based on the number of max_enc_workers.
av1_compute_num_fp_contexts(AV1_PRIMARY * ppi,AV1EncoderConfig * oxcf)1008 int av1_compute_num_fp_contexts(AV1_PRIMARY *ppi, AV1EncoderConfig *oxcf) {
1009   ppi->p_mt_info.num_mod_workers[MOD_FRAME_ENC] = 0;
1010   if (!av1_check_fpmt_config(ppi, oxcf)) {
1011     return 1;
1012   }
1013   int max_num_enc_workers = compute_max_num_enc_workers(
1014       &ppi->cpi->common.mi_params, ppi->cpi->common.seq_params->mib_size_log2);
1015   // Scaling factors and rounding factors used to tune worker_per_frame
1016   // computation.
1017   int rounding_factor[2] = { 2, 4 };
1018   int scaling_factor[2] = { 4, 8 };
1019   int is_480p_or_lesser =
1020       AOMMIN(oxcf->frm_dim_cfg.width, oxcf->frm_dim_cfg.height) <= 480;
1021   int is_sb_64 = 0;
1022   if (ppi->cpi != NULL)
1023     is_sb_64 = ppi->cpi->common.seq_params->sb_size == BLOCK_64X64;
1024   // A parallel frame encode has at least 1/4th the
1025   // theoretical limit of max enc workers in default case. For resolutions
1026   // larger than 480p, if SB size is 64x64, optimal performance is obtained with
1027   // limit of 1/8.
1028   int index = (!is_480p_or_lesser && is_sb_64) ? 1 : 0;
1029   int workers_per_frame =
1030       AOMMAX(1, (max_num_enc_workers + rounding_factor[index]) /
1031                     scaling_factor[index]);
1032   int max_threads = oxcf->max_threads;
1033   int num_fp_contexts = max_threads / workers_per_frame;
1034   // Based on empirical results, FPMT gains with multi-tile are significant when
1035   // more parallel frames are available. Use FPMT with multi-tile encode only
1036   // when sufficient threads are available for parallel encode of
1037   // MAX_PARALLEL_FRAMES frames.
1038   if (oxcf->tile_cfg.tile_columns > 0 || oxcf->tile_cfg.tile_rows > 0) {
1039     if (num_fp_contexts < MAX_PARALLEL_FRAMES) num_fp_contexts = 1;
1040   }
1041 
1042   num_fp_contexts = AOMMAX(1, AOMMIN(num_fp_contexts, MAX_PARALLEL_FRAMES));
1043   // Limit recalculated num_fp_contexts to ppi->num_fp_contexts.
1044   num_fp_contexts = (ppi->num_fp_contexts == 1)
1045                         ? num_fp_contexts
1046                         : AOMMIN(num_fp_contexts, ppi->num_fp_contexts);
1047   if (num_fp_contexts > 1) {
1048     ppi->p_mt_info.num_mod_workers[MOD_FRAME_ENC] =
1049         AOMMIN(max_num_enc_workers * num_fp_contexts, oxcf->max_threads);
1050   }
1051   return num_fp_contexts;
1052 }
1053 
1054 // Computes the number of workers to process each of the parallel frames.
compute_num_workers_per_frame(const int num_workers,const int parallel_frame_count)1055 static AOM_INLINE int compute_num_workers_per_frame(
1056     const int num_workers, const int parallel_frame_count) {
1057   // Number of level 2 workers per frame context (floor division).
1058   int workers_per_frame = (num_workers / parallel_frame_count);
1059   return workers_per_frame;
1060 }
1061 
1062 // Prepare level 1 workers. This function is only called for
1063 // parallel_frame_count > 1. This function populates the mt_info structure of
1064 // frame level contexts appropriately by dividing the total number of available
1065 // workers amongst the frames as level 2 workers. It also populates the hook and
1066 // data members of level 1 workers.
prepare_fpmt_workers(AV1_PRIMARY * ppi,AV1_COMP_DATA * first_cpi_data,AVxWorkerHook hook,int parallel_frame_count)1067 static AOM_INLINE void prepare_fpmt_workers(AV1_PRIMARY *ppi,
1068                                             AV1_COMP_DATA *first_cpi_data,
1069                                             AVxWorkerHook hook,
1070                                             int parallel_frame_count) {
1071   assert(parallel_frame_count <= ppi->num_fp_contexts &&
1072          parallel_frame_count > 1);
1073 
1074   PrimaryMultiThreadInfo *const p_mt_info = &ppi->p_mt_info;
1075   int num_workers = p_mt_info->num_workers;
1076 
1077   int frame_idx = 0;
1078   int i = 0;
1079   while (i < num_workers) {
1080     // Assign level 1 worker
1081     AVxWorker *frame_worker = p_mt_info->p_workers[frame_idx] =
1082         &p_mt_info->workers[i];
1083     AV1_COMP *cur_cpi = ppi->parallel_cpi[frame_idx];
1084     MultiThreadInfo *mt_info = &cur_cpi->mt_info;
1085     AV1_COMMON *const cm = &cur_cpi->common;
1086     const int num_planes = av1_num_planes(cm);
1087 
1088     // Assign start of level 2 worker pool
1089     mt_info->workers = &p_mt_info->workers[i];
1090     mt_info->tile_thr_data = &p_mt_info->tile_thr_data[i];
1091     // Assign number of workers for each frame in the parallel encode set.
1092     mt_info->num_workers = compute_num_workers_per_frame(
1093         num_workers - i, parallel_frame_count - frame_idx);
1094     for (int j = MOD_FP; j < NUM_MT_MODULES; j++) {
1095       mt_info->num_mod_workers[j] =
1096           AOMMIN(mt_info->num_workers, ppi->p_mt_info.num_mod_workers[j]);
1097     }
1098     if (ppi->p_mt_info.cdef_worker != NULL) {
1099       mt_info->cdef_worker = &ppi->p_mt_info.cdef_worker[i];
1100 
1101       // Back up the original cdef_worker pointers.
1102       mt_info->restore_state_buf.cdef_srcbuf = mt_info->cdef_worker->srcbuf;
1103       for (int plane = 0; plane < num_planes; plane++)
1104         mt_info->restore_state_buf.cdef_colbuf[plane] =
1105             mt_info->cdef_worker->colbuf[plane];
1106     }
1107 #if !CONFIG_REALTIME_ONLY
1108     if (is_restoration_used(cm)) {
1109       // Back up the original LR buffers before update.
1110       int idx = i + mt_info->num_workers - 1;
1111       mt_info->restore_state_buf.rst_tmpbuf =
1112           mt_info->lr_row_sync.lrworkerdata[idx].rst_tmpbuf;
1113       mt_info->restore_state_buf.rlbs =
1114           mt_info->lr_row_sync.lrworkerdata[idx].rlbs;
1115 
1116       // Update LR buffers.
1117       mt_info->lr_row_sync.lrworkerdata[idx].rst_tmpbuf = cm->rst_tmpbuf;
1118       mt_info->lr_row_sync.lrworkerdata[idx].rlbs = cm->rlbs;
1119     }
1120 #endif
1121 
1122     // At this stage, the thread specific CDEF buffers for the current frame's
1123     // 'common' and 'cdef_sync' only need to be allocated. 'cdef_worker' has
1124     // already been allocated across parallel frames.
1125     av1_alloc_cdef_buffers(cm, &p_mt_info->cdef_worker, &mt_info->cdef_sync,
1126                            p_mt_info->num_workers, 0);
1127 
1128     frame_worker->hook = hook;
1129     frame_worker->data1 = cur_cpi;
1130     frame_worker->data2 = (frame_idx == 0)
1131                               ? first_cpi_data
1132                               : &ppi->parallel_frames_data[frame_idx - 1];
1133     frame_idx++;
1134     i += mt_info->num_workers;
1135   }
1136   p_mt_info->p_num_workers = parallel_frame_count;
1137 }
1138 
1139 // Launch level 1 workers to perform frame parallel encode.
launch_fpmt_workers(AV1_PRIMARY * ppi)1140 static AOM_INLINE void launch_fpmt_workers(AV1_PRIMARY *ppi) {
1141   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
1142   int num_workers = ppi->p_mt_info.p_num_workers;
1143 
1144   for (int i = num_workers - 1; i >= 0; i--) {
1145     AVxWorker *const worker = ppi->p_mt_info.p_workers[i];
1146     if (i == 0)
1147       winterface->execute(worker);
1148     else
1149       winterface->launch(worker);
1150   }
1151 }
1152 
1153 // Synchronize level 1 workers.
sync_fpmt_workers(AV1_PRIMARY * ppi)1154 static AOM_INLINE void sync_fpmt_workers(AV1_PRIMARY *ppi) {
1155   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
1156   int num_workers = ppi->p_mt_info.p_num_workers;
1157   int had_error = 0;
1158   // Points to error in the earliest display order frame in the parallel set.
1159   const struct aom_internal_error_info *error;
1160 
1161   // Encoding ends.
1162   for (int i = num_workers - 1; i >= 0; i--) {
1163     AVxWorker *const worker = ppi->p_mt_info.p_workers[i];
1164     if (!winterface->sync(worker)) {
1165       had_error = 1;
1166       error = ((AV1_COMP *)worker->data1)->common.error;
1167     }
1168   }
1169 
1170   if (had_error)
1171     aom_internal_error(&ppi->error, error->error_code, "%s", error->detail);
1172 }
1173 
1174 // Restore worker states after parallel encode.
restore_workers_after_fpmt(AV1_PRIMARY * ppi,int parallel_frame_count)1175 static AOM_INLINE void restore_workers_after_fpmt(AV1_PRIMARY *ppi,
1176                                                   int parallel_frame_count) {
1177   assert(parallel_frame_count <= ppi->num_fp_contexts &&
1178          parallel_frame_count > 1);
1179   (void)parallel_frame_count;
1180 
1181   PrimaryMultiThreadInfo *const p_mt_info = &ppi->p_mt_info;
1182   int num_workers = p_mt_info->num_workers;
1183 
1184   int frame_idx = 0;
1185   int i = 0;
1186   while (i < num_workers) {
1187     AV1_COMP *cur_cpi = ppi->parallel_cpi[frame_idx];
1188     MultiThreadInfo *mt_info = &cur_cpi->mt_info;
1189     const AV1_COMMON *const cm = &cur_cpi->common;
1190     const int num_planes = av1_num_planes(cm);
1191 
1192     // Restore the original cdef_worker pointers.
1193     if (ppi->p_mt_info.cdef_worker != NULL) {
1194       mt_info->cdef_worker->srcbuf = mt_info->restore_state_buf.cdef_srcbuf;
1195       for (int plane = 0; plane < num_planes; plane++)
1196         mt_info->cdef_worker->colbuf[plane] =
1197             mt_info->restore_state_buf.cdef_colbuf[plane];
1198     }
1199 #if !CONFIG_REALTIME_ONLY
1200     if (is_restoration_used(cm)) {
1201       // Restore the original LR buffers.
1202       int idx = i + mt_info->num_workers - 1;
1203       mt_info->lr_row_sync.lrworkerdata[idx].rst_tmpbuf =
1204           mt_info->restore_state_buf.rst_tmpbuf;
1205       mt_info->lr_row_sync.lrworkerdata[idx].rlbs =
1206           mt_info->restore_state_buf.rlbs;
1207     }
1208 #endif
1209 
1210     frame_idx++;
1211     i += mt_info->num_workers;
1212   }
1213 }
1214 
get_compressed_data_hook(void * arg1,void * arg2)1215 static int get_compressed_data_hook(void *arg1, void *arg2) {
1216   AV1_COMP *cpi = (AV1_COMP *)arg1;
1217   AV1_COMP_DATA *cpi_data = (AV1_COMP_DATA *)arg2;
1218   int status = av1_get_compressed_data(cpi, cpi_data);
1219 
1220   // AOM_CODEC_OK(0) means no error.
1221   return !status;
1222 }
1223 
1224 // This function encodes the raw frame data for each frame in parallel encode
1225 // set, and outputs the frame bit stream to the designated buffers.
av1_compress_parallel_frames(AV1_PRIMARY * const ppi,AV1_COMP_DATA * const first_cpi_data)1226 int av1_compress_parallel_frames(AV1_PRIMARY *const ppi,
1227                                  AV1_COMP_DATA *const first_cpi_data) {
1228   // Bitmask for the frame buffers referenced by cpi->scaled_ref_buf
1229   // corresponding to frames in the current parallel encode set.
1230   int ref_buffers_used_map = 0;
1231   int frames_in_parallel_set = av1_init_parallel_frame_context(
1232       first_cpi_data, ppi, &ref_buffers_used_map);
1233   prepare_fpmt_workers(ppi, first_cpi_data, get_compressed_data_hook,
1234                        frames_in_parallel_set);
1235   launch_fpmt_workers(ppi);
1236   sync_fpmt_workers(ppi);
1237   restore_workers_after_fpmt(ppi, frames_in_parallel_set);
1238 
1239   // Release cpi->scaled_ref_buf corresponding to frames in the current parallel
1240   // encode set.
1241   for (int i = 0; i < frames_in_parallel_set; ++i) {
1242     av1_release_scaled_references_fpmt(ppi->parallel_cpi[i]);
1243   }
1244   av1_decrement_ref_counts_fpmt(ppi->cpi->common.buffer_pool,
1245                                 ref_buffers_used_map);
1246   return AOM_CODEC_OK;
1247 }
1248 
launch_workers(MultiThreadInfo * const mt_info,int num_workers)1249 static AOM_INLINE void launch_workers(MultiThreadInfo *const mt_info,
1250                                       int num_workers) {
1251   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
1252   for (int i = num_workers - 1; i >= 0; i--) {
1253     AVxWorker *const worker = &mt_info->workers[i];
1254     if (i == 0)
1255       winterface->execute(worker);
1256     else
1257       winterface->launch(worker);
1258   }
1259 }
1260 
sync_enc_workers(MultiThreadInfo * const mt_info,AV1_COMMON * const cm,int num_workers)1261 static AOM_INLINE void sync_enc_workers(MultiThreadInfo *const mt_info,
1262                                         AV1_COMMON *const cm, int num_workers) {
1263   const AVxWorkerInterface *const winterface = aom_get_worker_interface();
1264   int had_error = 0;
1265 
1266   // Encoding ends.
1267   for (int i = num_workers - 1; i > 0; i--) {
1268     AVxWorker *const worker = &mt_info->workers[i];
1269     had_error |= !winterface->sync(worker);
1270   }
1271 
1272   if (had_error)
1273     aom_internal_error(cm->error, AOM_CODEC_ERROR,
1274                        "Failed to encode tile data");
1275 }
1276 
accumulate_counters_enc_workers(AV1_COMP * cpi,int num_workers)1277 static AOM_INLINE void accumulate_counters_enc_workers(AV1_COMP *cpi,
1278                                                        int num_workers) {
1279   for (int i = num_workers - 1; i >= 0; i--) {
1280     AVxWorker *const worker = &cpi->mt_info.workers[i];
1281     EncWorkerData *const thread_data = (EncWorkerData *)worker->data1;
1282     cpi->intrabc_used |= thread_data->td->intrabc_used;
1283     cpi->deltaq_used |= thread_data->td->deltaq_used;
1284     // Accumulate rtc counters.
1285     if (!frame_is_intra_only(&cpi->common))
1286       av1_accumulate_rtc_counters(cpi, &thread_data->td->mb);
1287     if (thread_data->td != &cpi->td) {
1288       // Keep these conditional expressions in sync with the corresponding ones
1289       // in prepare_enc_workers().
1290       if (cpi->sf.inter_sf.mv_cost_upd_level != INTERNAL_COST_UPD_OFF) {
1291         aom_free(thread_data->td->mb.mv_costs);
1292       }
1293       if (cpi->sf.intra_sf.dv_cost_upd_level != INTERNAL_COST_UPD_OFF) {
1294         aom_free(thread_data->td->mb.dv_costs);
1295       }
1296     }
1297     av1_dealloc_mb_data(&cpi->common, &thread_data->td->mb);
1298 
1299     // Accumulate counters.
1300     if (i > 0) {
1301       av1_accumulate_frame_counts(&cpi->counts, thread_data->td->counts);
1302       accumulate_rd_opt(&cpi->td, thread_data->td);
1303       cpi->td.mb.txfm_search_info.txb_split_count +=
1304           thread_data->td->mb.txfm_search_info.txb_split_count;
1305 #if CONFIG_SPEED_STATS
1306       cpi->td.mb.txfm_search_info.tx_search_count +=
1307           thread_data->td->mb.txfm_search_info.tx_search_count;
1308 #endif  // CONFIG_SPEED_STATS
1309     }
1310   }
1311 }
1312 
prepare_enc_workers(AV1_COMP * cpi,AVxWorkerHook hook,int num_workers)1313 static AOM_INLINE void prepare_enc_workers(AV1_COMP *cpi, AVxWorkerHook hook,
1314                                            int num_workers) {
1315   MultiThreadInfo *const mt_info = &cpi->mt_info;
1316   AV1_COMMON *const cm = &cpi->common;
1317   MACROBLOCKD *xd = &cpi->td.mb.e_mbd;
1318   for (int i = num_workers - 1; i >= 0; i--) {
1319     AVxWorker *const worker = &mt_info->workers[i];
1320     EncWorkerData *const thread_data = &mt_info->tile_thr_data[i];
1321 
1322     // Initialize loopfilter data
1323     thread_data->lf_sync = &mt_info->lf_row_sync;
1324     thread_data->lf_data = &thread_data->lf_sync->lfdata[i];
1325     loop_filter_data_reset(thread_data->lf_data, &cm->cur_frame->buf, cm, xd);
1326 
1327     worker->hook = hook;
1328     worker->data1 = thread_data;
1329     worker->data2 = NULL;
1330 
1331     thread_data->thread_id = i;
1332     // Set the starting tile for each thread.
1333     thread_data->start = i;
1334 
1335     thread_data->cpi = cpi;
1336     if (i == 0) {
1337       thread_data->td = &cpi->td;
1338     } else {
1339       thread_data->td = thread_data->original_td;
1340     }
1341 
1342     thread_data->td->intrabc_used = 0;
1343     thread_data->td->deltaq_used = 0;
1344     thread_data->td->abs_sum_level = 0;
1345     thread_data->td->rd_counts.seg_tmp_pred_cost[0] = 0;
1346     thread_data->td->rd_counts.seg_tmp_pred_cost[1] = 0;
1347 
1348     // Before encoding a frame, copy the thread data from cpi.
1349     if (thread_data->td != &cpi->td) {
1350       thread_data->td->mb = cpi->td.mb;
1351       thread_data->td->rd_counts = cpi->td.rd_counts;
1352       thread_data->td->mb.obmc_buffer = thread_data->td->obmc_buffer;
1353 
1354       for (int x = 0; x < 2; x++) {
1355         for (int y = 0; y < 2; y++) {
1356           memcpy(thread_data->td->hash_value_buffer[x][y],
1357                  cpi->td.mb.intrabc_hash_info.hash_value_buffer[x][y],
1358                  AOM_BUFFER_SIZE_FOR_BLOCK_HASH *
1359                      sizeof(*thread_data->td->hash_value_buffer[0][0]));
1360           thread_data->td->mb.intrabc_hash_info.hash_value_buffer[x][y] =
1361               thread_data->td->hash_value_buffer[x][y];
1362         }
1363       }
1364       // Keep these conditional expressions in sync with the corresponding ones
1365       // in accumulate_counters_enc_workers().
1366       if (cpi->sf.inter_sf.mv_cost_upd_level != INTERNAL_COST_UPD_OFF) {
1367         CHECK_MEM_ERROR(cm, thread_data->td->mb.mv_costs,
1368                         (MvCosts *)aom_malloc(sizeof(MvCosts)));
1369         memcpy(thread_data->td->mb.mv_costs, cpi->td.mb.mv_costs,
1370                sizeof(MvCosts));
1371       }
1372       if (cpi->sf.intra_sf.dv_cost_upd_level != INTERNAL_COST_UPD_OFF) {
1373         // Reset dv_costs to NULL for worker threads when dv cost update is
1374         // enabled so that only dv_cost_upd_level needs to be checked before the
1375         // aom_free() call for the same.
1376         thread_data->td->mb.dv_costs = NULL;
1377         if (av1_need_dv_costs(cpi)) {
1378           CHECK_MEM_ERROR(cm, thread_data->td->mb.dv_costs,
1379                           (IntraBCMVCosts *)aom_malloc(sizeof(IntraBCMVCosts)));
1380           memcpy(thread_data->td->mb.dv_costs, cpi->td.mb.dv_costs,
1381                  sizeof(IntraBCMVCosts));
1382         }
1383       }
1384     }
1385     av1_alloc_mb_data(cpi, &thread_data->td->mb);
1386 
1387     // Reset rtc counters.
1388     av1_init_rtc_counters(&thread_data->td->mb);
1389 
1390     if (thread_data->td->counts != &cpi->counts) {
1391       memcpy(thread_data->td->counts, &cpi->counts, sizeof(cpi->counts));
1392     }
1393 
1394     if (i > 0) {
1395       thread_data->td->mb.palette_buffer = thread_data->td->palette_buffer;
1396       thread_data->td->mb.comp_rd_buffer = thread_data->td->comp_rd_buffer;
1397       thread_data->td->mb.tmp_conv_dst = thread_data->td->tmp_conv_dst;
1398       for (int j = 0; j < 2; ++j) {
1399         thread_data->td->mb.tmp_pred_bufs[j] =
1400             thread_data->td->tmp_pred_bufs[j];
1401       }
1402       thread_data->td->mb.pixel_gradient_info =
1403           thread_data->td->pixel_gradient_info;
1404 
1405       thread_data->td->mb.src_var_info_of_4x4_sub_blocks =
1406           thread_data->td->src_var_info_of_4x4_sub_blocks;
1407 
1408       thread_data->td->mb.e_mbd.tmp_conv_dst = thread_data->td->mb.tmp_conv_dst;
1409       for (int j = 0; j < 2; ++j) {
1410         thread_data->td->mb.e_mbd.tmp_obmc_bufs[j] =
1411             thread_data->td->mb.tmp_pred_bufs[j];
1412       }
1413     }
1414   }
1415 }
1416 
1417 #if !CONFIG_REALTIME_ONLY
fp_prepare_enc_workers(AV1_COMP * cpi,AVxWorkerHook hook,int num_workers)1418 static AOM_INLINE void fp_prepare_enc_workers(AV1_COMP *cpi, AVxWorkerHook hook,
1419                                               int num_workers) {
1420   AV1_COMMON *const cm = &cpi->common;
1421   MultiThreadInfo *const mt_info = &cpi->mt_info;
1422   for (int i = num_workers - 1; i >= 0; i--) {
1423     AVxWorker *const worker = &mt_info->workers[i];
1424     EncWorkerData *const thread_data = &mt_info->tile_thr_data[i];
1425 
1426     worker->hook = hook;
1427     worker->data1 = thread_data;
1428     worker->data2 = NULL;
1429 
1430     thread_data->thread_id = i;
1431     // Set the starting tile for each thread.
1432     thread_data->start = i;
1433 
1434     thread_data->cpi = cpi;
1435     if (i == 0) {
1436       thread_data->td = &cpi->td;
1437     } else {
1438       thread_data->td = thread_data->original_td;
1439     }
1440 
1441     // Before encoding a frame, copy the thread data from cpi.
1442     if (thread_data->td != &cpi->td) {
1443       thread_data->td->mb = cpi->td.mb;
1444       // Keep this conditional expression in sync with the corresponding one
1445       // in av1_fp_encode_tiles_row_mt().
1446       if (cpi->sf.inter_sf.mv_cost_upd_level != INTERNAL_COST_UPD_OFF) {
1447         CHECK_MEM_ERROR(cm, thread_data->td->mb.mv_costs,
1448                         (MvCosts *)aom_malloc(sizeof(MvCosts)));
1449         memcpy(thread_data->td->mb.mv_costs, cpi->td.mb.mv_costs,
1450                sizeof(MvCosts));
1451       }
1452     }
1453 
1454     av1_alloc_mb_data(cpi, &thread_data->td->mb);
1455   }
1456 }
1457 #endif
1458 
1459 // Computes the number of workers for row multi-threading of encoding stage
compute_num_enc_row_mt_workers(AV1_COMMON * const cm,int max_threads)1460 static AOM_INLINE int compute_num_enc_row_mt_workers(AV1_COMMON *const cm,
1461                                                      int max_threads) {
1462   TileInfo tile_info;
1463   const int tile_cols = cm->tiles.cols;
1464   const int tile_rows = cm->tiles.rows;
1465   int total_num_threads_row_mt = 0;
1466   for (int row = 0; row < tile_rows; row++) {
1467     for (int col = 0; col < tile_cols; col++) {
1468       av1_tile_init(&tile_info, cm, row, col);
1469       const int num_sb_rows_in_tile = av1_get_sb_rows_in_tile(cm, &tile_info);
1470       const int num_sb_cols_in_tile = av1_get_sb_cols_in_tile(cm, &tile_info);
1471       total_num_threads_row_mt +=
1472           AOMMIN((num_sb_cols_in_tile + 1) >> 1, num_sb_rows_in_tile);
1473     }
1474   }
1475   return AOMMIN(max_threads, total_num_threads_row_mt);
1476 }
1477 
1478 // Computes the number of workers for tile multi-threading of encoding stage
compute_num_enc_tile_mt_workers(AV1_COMMON * const cm,int max_threads)1479 static AOM_INLINE int compute_num_enc_tile_mt_workers(AV1_COMMON *const cm,
1480                                                       int max_threads) {
1481   const int tile_cols = cm->tiles.cols;
1482   const int tile_rows = cm->tiles.rows;
1483   return AOMMIN(max_threads, tile_cols * tile_rows);
1484 }
1485 
1486 // Find max worker of all MT stages
av1_get_max_num_workers(const AV1_COMP * cpi)1487 int av1_get_max_num_workers(const AV1_COMP *cpi) {
1488   int max_num_workers = 0;
1489   for (int i = MOD_FP; i < NUM_MT_MODULES; i++)
1490     max_num_workers =
1491         AOMMAX(cpi->ppi->p_mt_info.num_mod_workers[i], max_num_workers);
1492   assert(max_num_workers >= 1);
1493   return AOMMIN(max_num_workers, cpi->oxcf.max_threads);
1494 }
1495 
1496 // Computes the number of workers for encoding stage (row/tile multi-threading)
av1_compute_num_enc_workers(AV1_COMP * cpi,int max_workers)1497 int av1_compute_num_enc_workers(AV1_COMP *cpi, int max_workers) {
1498   if (max_workers <= 1) return 1;
1499   if (cpi->oxcf.row_mt)
1500     return compute_num_enc_row_mt_workers(&cpi->common, max_workers);
1501   else
1502     return compute_num_enc_tile_mt_workers(&cpi->common, max_workers);
1503 }
1504 
av1_encode_tiles_mt(AV1_COMP * cpi)1505 void av1_encode_tiles_mt(AV1_COMP *cpi) {
1506   AV1_COMMON *const cm = &cpi->common;
1507   MultiThreadInfo *const mt_info = &cpi->mt_info;
1508   const int tile_cols = cm->tiles.cols;
1509   const int tile_rows = cm->tiles.rows;
1510   int num_workers = mt_info->num_mod_workers[MOD_ENC];
1511 
1512   assert(IMPLIES(cpi->tile_data == NULL,
1513                  cpi->allocated_tiles < tile_cols * tile_rows));
1514   if (cpi->allocated_tiles < tile_cols * tile_rows) av1_alloc_tile_data(cpi);
1515 
1516   av1_init_tile_data(cpi);
1517   num_workers = AOMMIN(num_workers, mt_info->num_workers);
1518 
1519   prepare_enc_workers(cpi, enc_worker_hook, num_workers);
1520   launch_workers(&cpi->mt_info, num_workers);
1521   sync_enc_workers(&cpi->mt_info, cm, num_workers);
1522   accumulate_counters_enc_workers(cpi, num_workers);
1523 }
1524 
1525 // Accumulate frame counts. FRAME_COUNTS consist solely of 'unsigned int'
1526 // members, so we treat it as an array, and sum over the whole length.
av1_accumulate_frame_counts(FRAME_COUNTS * acc_counts,const FRAME_COUNTS * counts)1527 void av1_accumulate_frame_counts(FRAME_COUNTS *acc_counts,
1528                                  const FRAME_COUNTS *counts) {
1529   unsigned int *const acc = (unsigned int *)acc_counts;
1530   const unsigned int *const cnt = (const unsigned int *)counts;
1531 
1532   const unsigned int n_counts = sizeof(FRAME_COUNTS) / sizeof(unsigned int);
1533 
1534   for (unsigned int i = 0; i < n_counts; i++) acc[i] += cnt[i];
1535 }
1536 
1537 // Computes the maximum number of sb rows and sb_cols across tiles which are
1538 // used to allocate memory for multi-threaded encoding with row-mt=1.
compute_max_sb_rows_cols(const AV1_COMMON * cm,int * max_sb_rows_in_tile,int * max_sb_cols_in_tile)1539 static AOM_INLINE void compute_max_sb_rows_cols(const AV1_COMMON *cm,
1540                                                 int *max_sb_rows_in_tile,
1541                                                 int *max_sb_cols_in_tile) {
1542   const int tile_rows = cm->tiles.rows;
1543   const int mib_size_log2 = cm->seq_params->mib_size_log2;
1544   const int num_mi_rows = cm->mi_params.mi_rows;
1545   const int *const row_start_sb = cm->tiles.row_start_sb;
1546   for (int row = 0; row < tile_rows; row++) {
1547     const int mi_row_start = row_start_sb[row] << mib_size_log2;
1548     const int mi_row_end =
1549         AOMMIN(row_start_sb[row + 1] << mib_size_log2, num_mi_rows);
1550     const int num_sb_rows_in_tile =
1551         CEIL_POWER_OF_TWO(mi_row_end - mi_row_start, mib_size_log2);
1552     *max_sb_rows_in_tile = AOMMAX(*max_sb_rows_in_tile, num_sb_rows_in_tile);
1553   }
1554 
1555   const int tile_cols = cm->tiles.cols;
1556   const int num_mi_cols = cm->mi_params.mi_cols;
1557   const int *const col_start_sb = cm->tiles.col_start_sb;
1558   for (int col = 0; col < tile_cols; col++) {
1559     const int mi_col_start = col_start_sb[col] << mib_size_log2;
1560     const int mi_col_end =
1561         AOMMIN(col_start_sb[col + 1] << mib_size_log2, num_mi_cols);
1562     const int num_sb_cols_in_tile =
1563         CEIL_POWER_OF_TWO(mi_col_end - mi_col_start, mib_size_log2);
1564     *max_sb_cols_in_tile = AOMMAX(*max_sb_cols_in_tile, num_sb_cols_in_tile);
1565   }
1566 }
1567 
1568 #if !CONFIG_REALTIME_ONLY
1569 // Computes the number of workers for firstpass stage (row/tile multi-threading)
av1_fp_compute_num_enc_workers(AV1_COMP * cpi)1570 int av1_fp_compute_num_enc_workers(AV1_COMP *cpi) {
1571   AV1_COMMON *cm = &cpi->common;
1572   const int tile_cols = cm->tiles.cols;
1573   const int tile_rows = cm->tiles.rows;
1574   int total_num_threads_row_mt = 0;
1575   TileInfo tile_info;
1576 
1577   if (cpi->oxcf.max_threads <= 1) return 1;
1578 
1579   for (int row = 0; row < tile_rows; row++) {
1580     for (int col = 0; col < tile_cols; col++) {
1581       av1_tile_init(&tile_info, cm, row, col);
1582       const int num_mb_rows_in_tile =
1583           av1_get_unit_rows_in_tile(&tile_info, cpi->fp_block_size);
1584       const int num_mb_cols_in_tile =
1585           av1_get_unit_cols_in_tile(&tile_info, cpi->fp_block_size);
1586       total_num_threads_row_mt +=
1587           AOMMIN((num_mb_cols_in_tile + 1) >> 1, num_mb_rows_in_tile);
1588     }
1589   }
1590   return AOMMIN(cpi->oxcf.max_threads, total_num_threads_row_mt);
1591 }
1592 
1593 // Computes the maximum number of mb_rows for row multi-threading of firstpass
1594 // stage
fp_compute_max_mb_rows(const AV1_COMMON * cm,BLOCK_SIZE fp_block_size)1595 static AOM_INLINE int fp_compute_max_mb_rows(const AV1_COMMON *cm,
1596                                              BLOCK_SIZE fp_block_size) {
1597   const int tile_rows = cm->tiles.rows;
1598   const int unit_height_log2 = mi_size_high_log2[fp_block_size];
1599   const int mib_size_log2 = cm->seq_params->mib_size_log2;
1600   const int num_mi_rows = cm->mi_params.mi_rows;
1601   const int *const row_start_sb = cm->tiles.row_start_sb;
1602   int max_mb_rows = 0;
1603 
1604   for (int row = 0; row < tile_rows; row++) {
1605     const int mi_row_start = row_start_sb[row] << mib_size_log2;
1606     const int mi_row_end =
1607         AOMMIN(row_start_sb[row + 1] << mib_size_log2, num_mi_rows);
1608     const int num_mb_rows_in_tile =
1609         CEIL_POWER_OF_TWO(mi_row_end - mi_row_start, unit_height_log2);
1610     max_mb_rows = AOMMAX(max_mb_rows, num_mb_rows_in_tile);
1611   }
1612   return max_mb_rows;
1613 }
1614 #endif
1615 
lpf_pipeline_mt_init(AV1_COMP * cpi)1616 static void lpf_pipeline_mt_init(AV1_COMP *cpi) {
1617   // Pipelining of loop-filtering after encoding is enabled when loop-filter
1618   // level is chosen based on quantizer and frame type. It is disabled in case
1619   // of 'LOOPFILTER_SELECTIVELY' as the stats collected during encoding stage
1620   // decides the filter level. Loop-filtering is disabled in case
1621   // of non-reference frames and for frames with intra block copy tool enabled.
1622   AV1_COMMON *cm = &cpi->common;
1623   const int use_loopfilter = is_loopfilter_used(cm);
1624   const int use_superres = av1_superres_scaled(cm);
1625   const int use_cdef = is_cdef_used(cm);
1626   const int use_restoration = is_restoration_used(cm);
1627 
1628   const unsigned int skip_apply_postproc_filters =
1629       derive_skip_apply_postproc_filters(cpi, use_loopfilter, use_cdef,
1630                                          use_superres, use_restoration);
1631   cpi->mt_info.pipeline_lpf_mt_with_enc =
1632       (cpi->oxcf.mode == REALTIME) && (cpi->oxcf.speed >= 5) &&
1633       (cpi->sf.lpf_sf.lpf_pick == LPF_PICK_FROM_Q) &&
1634       (cpi->oxcf.algo_cfg.loopfilter_control != LOOPFILTER_SELECTIVELY) &&
1635       !cpi->ppi->rtc_ref.non_reference_frame && !cm->features.allow_intrabc &&
1636       ((skip_apply_postproc_filters & SKIP_APPLY_LOOPFILTER) == 0);
1637 
1638   if (!cpi->mt_info.pipeline_lpf_mt_with_enc) return;
1639 
1640   set_postproc_filter_default_params(cm);
1641 
1642   if (!use_loopfilter) return;
1643 
1644   const LPF_PICK_METHOD method = cpi->sf.lpf_sf.lpf_pick;
1645   assert(method == LPF_PICK_FROM_Q);
1646   assert(cpi->oxcf.algo_cfg.loopfilter_control != LOOPFILTER_SELECTIVELY);
1647 
1648   av1_pick_filter_level(cpi->source, cpi, method);
1649 
1650   struct loopfilter *lf = &cm->lf;
1651   const int plane_start = 0;
1652   const int plane_end = av1_num_planes(cm);
1653   int planes_to_lf[MAX_MB_PLANE];
1654   if ((lf->filter_level[PLANE_TYPE_Y] || lf->filter_level[PLANE_TYPE_UV]) &&
1655       check_planes_to_loop_filter(lf, planes_to_lf, plane_start, plane_end)) {
1656     int lpf_opt_level = get_lpf_opt_level(&cpi->sf);
1657     assert(lpf_opt_level == 2);
1658 
1659     const int start_mi_row = 0;
1660     const int end_mi_row = start_mi_row + cm->mi_params.mi_rows;
1661 
1662     av1_loop_filter_frame_init(cm, plane_start, plane_end);
1663 
1664     assert(cpi->mt_info.num_mod_workers[MOD_ENC] ==
1665            cpi->mt_info.num_mod_workers[MOD_LPF]);
1666     loop_filter_frame_mt_init(cm, start_mi_row, end_mi_row, planes_to_lf,
1667                               cpi->mt_info.num_mod_workers[MOD_LPF],
1668                               &cpi->mt_info.lf_row_sync, lpf_opt_level,
1669                               cm->seq_params->mib_size_log2);
1670   }
1671 }
1672 
av1_encode_tiles_row_mt(AV1_COMP * cpi)1673 void av1_encode_tiles_row_mt(AV1_COMP *cpi) {
1674   AV1_COMMON *const cm = &cpi->common;
1675   MultiThreadInfo *const mt_info = &cpi->mt_info;
1676   AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt;
1677   const int tile_cols = cm->tiles.cols;
1678   const int tile_rows = cm->tiles.rows;
1679   const int sb_rows_in_frame = get_sb_rows_in_frame(cm);
1680   int *thread_id_to_tile_id = enc_row_mt->thread_id_to_tile_id;
1681   int max_sb_rows_in_tile = 0, max_sb_cols_in_tile = 0;
1682   int num_workers = mt_info->num_mod_workers[MOD_ENC];
1683 
1684   compute_max_sb_rows_cols(cm, &max_sb_rows_in_tile, &max_sb_cols_in_tile);
1685   const bool alloc_row_mt_mem =
1686       (enc_row_mt->allocated_tile_cols != tile_cols ||
1687        enc_row_mt->allocated_tile_rows != tile_rows ||
1688        enc_row_mt->allocated_rows != max_sb_rows_in_tile ||
1689        enc_row_mt->allocated_cols != (max_sb_cols_in_tile - 1) ||
1690        enc_row_mt->allocated_sb_rows != sb_rows_in_frame);
1691   const bool alloc_tile_data = cpi->allocated_tiles < tile_cols * tile_rows;
1692 
1693   assert(IMPLIES(cpi->tile_data == NULL, alloc_tile_data));
1694   if (alloc_tile_data) {
1695     av1_alloc_tile_data(cpi);
1696   }
1697 
1698   assert(IMPLIES(alloc_tile_data, alloc_row_mt_mem));
1699   if (alloc_row_mt_mem) {
1700     row_mt_mem_alloc(cpi, max_sb_rows_in_tile, max_sb_cols_in_tile,
1701                      cpi->oxcf.algo_cfg.cdf_update_mode);
1702   }
1703 
1704   lpf_pipeline_mt_init(cpi);
1705 
1706   av1_init_tile_data(cpi);
1707 
1708   memset(thread_id_to_tile_id, -1,
1709          sizeof(*thread_id_to_tile_id) * MAX_NUM_THREADS);
1710   memset(enc_row_mt->num_tile_cols_done, 0,
1711          sizeof(*enc_row_mt->num_tile_cols_done) * sb_rows_in_frame);
1712 
1713   for (int tile_row = 0; tile_row < tile_rows; tile_row++) {
1714     for (int tile_col = 0; tile_col < tile_cols; tile_col++) {
1715       int tile_index = tile_row * tile_cols + tile_col;
1716       TileDataEnc *const this_tile = &cpi->tile_data[tile_index];
1717       AV1EncRowMultiThreadSync *const row_mt_sync = &this_tile->row_mt_sync;
1718 
1719       // Initialize num_finished_cols to -1 for all rows.
1720       memset(row_mt_sync->num_finished_cols, -1,
1721              sizeof(*row_mt_sync->num_finished_cols) * max_sb_rows_in_tile);
1722       row_mt_sync->next_mi_row = this_tile->tile_info.mi_row_start;
1723       row_mt_sync->num_threads_working = 0;
1724       row_mt_sync->intrabc_extra_top_right_sb_delay =
1725           av1_get_intrabc_extra_top_right_sb_delay(cm);
1726 
1727       av1_inter_mode_data_init(this_tile);
1728       av1_zero_above_context(cm, &cpi->td.mb.e_mbd,
1729                              this_tile->tile_info.mi_col_start,
1730                              this_tile->tile_info.mi_col_end, tile_row);
1731     }
1732   }
1733 
1734   num_workers = AOMMIN(num_workers, mt_info->num_workers);
1735 
1736   assign_tile_to_thread(thread_id_to_tile_id, tile_cols * tile_rows,
1737                         num_workers);
1738   prepare_enc_workers(cpi, enc_row_mt_worker_hook, num_workers);
1739   launch_workers(&cpi->mt_info, num_workers);
1740   sync_enc_workers(&cpi->mt_info, cm, num_workers);
1741   if (cm->delta_q_info.delta_lf_present_flag) update_delta_lf_for_row_mt(cpi);
1742   accumulate_counters_enc_workers(cpi, num_workers);
1743 }
1744 
1745 #if !CONFIG_REALTIME_ONLY
av1_fp_encode_tiles_row_mt(AV1_COMP * cpi)1746 void av1_fp_encode_tiles_row_mt(AV1_COMP *cpi) {
1747   AV1_COMMON *const cm = &cpi->common;
1748   MultiThreadInfo *const mt_info = &cpi->mt_info;
1749   AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt;
1750   const int tile_cols = cm->tiles.cols;
1751   const int tile_rows = cm->tiles.rows;
1752   int *thread_id_to_tile_id = enc_row_mt->thread_id_to_tile_id;
1753   int num_workers = 0;
1754   int max_mb_rows = 0;
1755 
1756   max_mb_rows = fp_compute_max_mb_rows(cm, cpi->fp_block_size);
1757   const bool alloc_row_mt_mem = enc_row_mt->allocated_tile_cols != tile_cols ||
1758                                 enc_row_mt->allocated_tile_rows != tile_rows ||
1759                                 enc_row_mt->allocated_rows != max_mb_rows;
1760   const bool alloc_tile_data = cpi->allocated_tiles < tile_cols * tile_rows;
1761 
1762   assert(IMPLIES(cpi->tile_data == NULL, alloc_tile_data));
1763   if (alloc_tile_data) {
1764     av1_alloc_tile_data(cpi);
1765   }
1766 
1767   assert(IMPLIES(alloc_tile_data, alloc_row_mt_mem));
1768   if (alloc_row_mt_mem) {
1769     row_mt_mem_alloc(cpi, max_mb_rows, -1, 0);
1770   }
1771 
1772   av1_init_tile_data(cpi);
1773 
1774   // For pass = 1, compute the no. of workers needed. For single-pass encode
1775   // (pass = 0), no. of workers are already computed.
1776   if (mt_info->num_mod_workers[MOD_FP] == 0)
1777     num_workers = av1_fp_compute_num_enc_workers(cpi);
1778   else
1779     num_workers = mt_info->num_mod_workers[MOD_FP];
1780 
1781   memset(thread_id_to_tile_id, -1,
1782          sizeof(*thread_id_to_tile_id) * MAX_NUM_THREADS);
1783 
1784   for (int tile_row = 0; tile_row < tile_rows; tile_row++) {
1785     for (int tile_col = 0; tile_col < tile_cols; tile_col++) {
1786       int tile_index = tile_row * tile_cols + tile_col;
1787       TileDataEnc *const this_tile = &cpi->tile_data[tile_index];
1788       AV1EncRowMultiThreadSync *const row_mt_sync = &this_tile->row_mt_sync;
1789 
1790       // Initialize num_finished_cols to -1 for all rows.
1791       memset(row_mt_sync->num_finished_cols, -1,
1792              sizeof(*row_mt_sync->num_finished_cols) * max_mb_rows);
1793       row_mt_sync->next_mi_row = this_tile->tile_info.mi_row_start;
1794       row_mt_sync->num_threads_working = 0;
1795 
1796       // intraBC mode is not evaluated during first-pass encoding. Hence, no
1797       // additional top-right delay is required.
1798       row_mt_sync->intrabc_extra_top_right_sb_delay = 0;
1799     }
1800   }
1801 
1802   num_workers = AOMMIN(num_workers, mt_info->num_workers);
1803   assign_tile_to_thread(thread_id_to_tile_id, tile_cols * tile_rows,
1804                         num_workers);
1805   fp_prepare_enc_workers(cpi, fp_enc_row_mt_worker_hook, num_workers);
1806   launch_workers(&cpi->mt_info, num_workers);
1807   sync_enc_workers(&cpi->mt_info, cm, num_workers);
1808   for (int i = num_workers - 1; i >= 0; i--) {
1809     EncWorkerData *const thread_data = &cpi->mt_info.tile_thr_data[i];
1810     if (thread_data->td != &cpi->td) {
1811       // Keep this conditional expression in sync with the corresponding one
1812       // in fp_prepare_enc_workers().
1813       if (cpi->sf.inter_sf.mv_cost_upd_level != INTERNAL_COST_UPD_OFF) {
1814         aom_free(thread_data->td->mb.mv_costs);
1815       }
1816       assert(!thread_data->td->mb.dv_costs);
1817     }
1818     av1_dealloc_mb_data(cm, &thread_data->td->mb);
1819   }
1820 }
1821 
av1_tpl_row_mt_sync_read_dummy(AV1TplRowMultiThreadSync * tpl_mt_sync,int r,int c)1822 void av1_tpl_row_mt_sync_read_dummy(AV1TplRowMultiThreadSync *tpl_mt_sync,
1823                                     int r, int c) {
1824   (void)tpl_mt_sync;
1825   (void)r;
1826   (void)c;
1827   return;
1828 }
1829 
av1_tpl_row_mt_sync_write_dummy(AV1TplRowMultiThreadSync * tpl_mt_sync,int r,int c,int cols)1830 void av1_tpl_row_mt_sync_write_dummy(AV1TplRowMultiThreadSync *tpl_mt_sync,
1831                                      int r, int c, int cols) {
1832   (void)tpl_mt_sync;
1833   (void)r;
1834   (void)c;
1835   (void)cols;
1836   return;
1837 }
1838 
av1_tpl_row_mt_sync_read(AV1TplRowMultiThreadSync * tpl_row_mt_sync,int r,int c)1839 void av1_tpl_row_mt_sync_read(AV1TplRowMultiThreadSync *tpl_row_mt_sync, int r,
1840                               int c) {
1841 #if CONFIG_MULTITHREAD
1842   int nsync = tpl_row_mt_sync->sync_range;
1843 
1844   if (r) {
1845     pthread_mutex_t *const mutex = &tpl_row_mt_sync->mutex_[r - 1];
1846     pthread_mutex_lock(mutex);
1847 
1848     while (c > tpl_row_mt_sync->num_finished_cols[r - 1] - nsync)
1849       pthread_cond_wait(&tpl_row_mt_sync->cond_[r - 1], mutex);
1850     pthread_mutex_unlock(mutex);
1851   }
1852 #else
1853   (void)tpl_row_mt_sync;
1854   (void)r;
1855   (void)c;
1856 #endif  // CONFIG_MULTITHREAD
1857 }
1858 
av1_tpl_row_mt_sync_write(AV1TplRowMultiThreadSync * tpl_row_mt_sync,int r,int c,int cols)1859 void av1_tpl_row_mt_sync_write(AV1TplRowMultiThreadSync *tpl_row_mt_sync, int r,
1860                                int c, int cols) {
1861 #if CONFIG_MULTITHREAD
1862   int nsync = tpl_row_mt_sync->sync_range;
1863   int cur;
1864   // Only signal when there are enough encoded blocks for next row to run.
1865   int sig = 1;
1866 
1867   if (c < cols - 1) {
1868     cur = c;
1869     if (c % nsync) sig = 0;
1870   } else {
1871     cur = cols + nsync;
1872   }
1873 
1874   if (sig) {
1875     pthread_mutex_lock(&tpl_row_mt_sync->mutex_[r]);
1876 
1877     tpl_row_mt_sync->num_finished_cols[r] = cur;
1878 
1879     pthread_cond_signal(&tpl_row_mt_sync->cond_[r]);
1880     pthread_mutex_unlock(&tpl_row_mt_sync->mutex_[r]);
1881   }
1882 #else
1883   (void)tpl_row_mt_sync;
1884   (void)r;
1885   (void)c;
1886   (void)cols;
1887 #endif  // CONFIG_MULTITHREAD
1888 }
1889 
1890 // Each worker calls tpl_worker_hook() and computes the tpl data.
tpl_worker_hook(void * arg1,void * unused)1891 static int tpl_worker_hook(void *arg1, void *unused) {
1892   (void)unused;
1893   EncWorkerData *thread_data = (EncWorkerData *)arg1;
1894   AV1_COMP *cpi = thread_data->cpi;
1895   AV1_COMMON *cm = &cpi->common;
1896   MACROBLOCK *x = &thread_data->td->mb;
1897   MACROBLOCKD *xd = &x->e_mbd;
1898   TplTxfmStats *tpl_txfm_stats = &thread_data->td->tpl_txfm_stats;
1899   CommonModeInfoParams *mi_params = &cm->mi_params;
1900   BLOCK_SIZE bsize = convert_length_to_bsize(cpi->ppi->tpl_data.tpl_bsize_1d);
1901   TX_SIZE tx_size = max_txsize_lookup[bsize];
1902   int mi_height = mi_size_high[bsize];
1903   int num_active_workers = cpi->ppi->tpl_data.tpl_mt_sync.num_threads_working;
1904 
1905   av1_init_tpl_txfm_stats(tpl_txfm_stats);
1906 
1907   for (int mi_row = thread_data->start * mi_height; mi_row < mi_params->mi_rows;
1908        mi_row += num_active_workers * mi_height) {
1909     // Motion estimation row boundary
1910     av1_set_mv_row_limits(mi_params, &x->mv_limits, mi_row, mi_height,
1911                           cpi->oxcf.border_in_pixels);
1912     xd->mb_to_top_edge = -GET_MV_SUBPEL(mi_row * MI_SIZE);
1913     xd->mb_to_bottom_edge =
1914         GET_MV_SUBPEL((mi_params->mi_rows - mi_height - mi_row) * MI_SIZE);
1915     av1_mc_flow_dispenser_row(cpi, tpl_txfm_stats, x, mi_row, bsize, tx_size);
1916   }
1917   return 1;
1918 }
1919 
1920 // Deallocate tpl synchronization related mutex and data.
av1_tpl_dealloc(AV1TplRowMultiThreadSync * tpl_sync)1921 void av1_tpl_dealloc(AV1TplRowMultiThreadSync *tpl_sync) {
1922   assert(tpl_sync != NULL);
1923 
1924 #if CONFIG_MULTITHREAD
1925   if (tpl_sync->mutex_ != NULL) {
1926     for (int i = 0; i < tpl_sync->rows; ++i)
1927       pthread_mutex_destroy(&tpl_sync->mutex_[i]);
1928     aom_free(tpl_sync->mutex_);
1929   }
1930   if (tpl_sync->cond_ != NULL) {
1931     for (int i = 0; i < tpl_sync->rows; ++i)
1932       pthread_cond_destroy(&tpl_sync->cond_[i]);
1933     aom_free(tpl_sync->cond_);
1934   }
1935 #endif  // CONFIG_MULTITHREAD
1936 
1937   aom_free(tpl_sync->num_finished_cols);
1938   // clear the structure as the source of this call may be a resize in which
1939   // case this call will be followed by an _alloc() which may fail.
1940   av1_zero(*tpl_sync);
1941 }
1942 
1943 // Allocate memory for tpl row synchronization.
av1_tpl_alloc(AV1TplRowMultiThreadSync * tpl_sync,AV1_COMMON * cm,int mb_rows)1944 void av1_tpl_alloc(AV1TplRowMultiThreadSync *tpl_sync, AV1_COMMON *cm,
1945                    int mb_rows) {
1946   tpl_sync->rows = mb_rows;
1947 #if CONFIG_MULTITHREAD
1948   {
1949     CHECK_MEM_ERROR(cm, tpl_sync->mutex_,
1950                     aom_malloc(sizeof(*tpl_sync->mutex_) * mb_rows));
1951     if (tpl_sync->mutex_) {
1952       for (int i = 0; i < mb_rows; ++i)
1953         pthread_mutex_init(&tpl_sync->mutex_[i], NULL);
1954     }
1955 
1956     CHECK_MEM_ERROR(cm, tpl_sync->cond_,
1957                     aom_malloc(sizeof(*tpl_sync->cond_) * mb_rows));
1958     if (tpl_sync->cond_) {
1959       for (int i = 0; i < mb_rows; ++i)
1960         pthread_cond_init(&tpl_sync->cond_[i], NULL);
1961     }
1962   }
1963 #endif  // CONFIG_MULTITHREAD
1964   CHECK_MEM_ERROR(cm, tpl_sync->num_finished_cols,
1965                   aom_malloc(sizeof(*tpl_sync->num_finished_cols) * mb_rows));
1966 
1967   // Set up nsync.
1968   tpl_sync->sync_range = 1;
1969 }
1970 
1971 // Each worker is prepared by assigning the hook function and individual thread
1972 // data.
prepare_tpl_workers(AV1_COMP * cpi,AVxWorkerHook hook,int num_workers)1973 static AOM_INLINE void prepare_tpl_workers(AV1_COMP *cpi, AVxWorkerHook hook,
1974                                            int num_workers) {
1975   MultiThreadInfo *mt_info = &cpi->mt_info;
1976   for (int i = num_workers - 1; i >= 0; i--) {
1977     AVxWorker *worker = &mt_info->workers[i];
1978     EncWorkerData *thread_data = &mt_info->tile_thr_data[i];
1979 
1980     worker->hook = hook;
1981     worker->data1 = thread_data;
1982     worker->data2 = NULL;
1983 
1984     thread_data->thread_id = i;
1985     // Set the starting tile for each thread.
1986     thread_data->start = i;
1987 
1988     thread_data->cpi = cpi;
1989     if (i == 0) {
1990       thread_data->td = &cpi->td;
1991     } else {
1992       thread_data->td = thread_data->original_td;
1993     }
1994 
1995     // Before encoding a frame, copy the thread data from cpi.
1996     if (thread_data->td != &cpi->td) {
1997       thread_data->td->mb = cpi->td.mb;
1998       // OBMC buffers are used only to init MS params and remain unused when
1999       // called from tpl, hence set the buffers to defaults.
2000       av1_init_obmc_buffer(&thread_data->td->mb.obmc_buffer);
2001       thread_data->td->mb.tmp_conv_dst = thread_data->td->tmp_conv_dst;
2002       thread_data->td->mb.e_mbd.tmp_conv_dst = thread_data->td->mb.tmp_conv_dst;
2003     }
2004   }
2005 }
2006 
2007 // Accumulate transform stats after tpl.
tpl_accumulate_txfm_stats(ThreadData * main_td,const MultiThreadInfo * mt_info,int num_workers)2008 static void tpl_accumulate_txfm_stats(ThreadData *main_td,
2009                                       const MultiThreadInfo *mt_info,
2010                                       int num_workers) {
2011   TplTxfmStats *accumulated_stats = &main_td->tpl_txfm_stats;
2012   for (int i = num_workers - 1; i >= 0; i--) {
2013     AVxWorker *const worker = &mt_info->workers[i];
2014     EncWorkerData *const thread_data = (EncWorkerData *)worker->data1;
2015     ThreadData *td = thread_data->td;
2016     if (td != main_td) {
2017       const TplTxfmStats *tpl_txfm_stats = &td->tpl_txfm_stats;
2018       av1_accumulate_tpl_txfm_stats(tpl_txfm_stats, accumulated_stats);
2019     }
2020   }
2021 }
2022 
2023 // Implements multi-threading for tpl.
av1_mc_flow_dispenser_mt(AV1_COMP * cpi)2024 void av1_mc_flow_dispenser_mt(AV1_COMP *cpi) {
2025   AV1_COMMON *cm = &cpi->common;
2026   CommonModeInfoParams *mi_params = &cm->mi_params;
2027   MultiThreadInfo *mt_info = &cpi->mt_info;
2028   TplParams *tpl_data = &cpi->ppi->tpl_data;
2029   AV1TplRowMultiThreadSync *tpl_sync = &tpl_data->tpl_mt_sync;
2030   int mb_rows = mi_params->mb_rows;
2031   int num_workers =
2032       AOMMIN(mt_info->num_mod_workers[MOD_TPL], mt_info->num_workers);
2033 
2034   if (mb_rows != tpl_sync->rows) {
2035     av1_tpl_dealloc(tpl_sync);
2036     av1_tpl_alloc(tpl_sync, cm, mb_rows);
2037   }
2038   tpl_sync->num_threads_working = num_workers;
2039 
2040   // Initialize cur_mb_col to -1 for all MB rows.
2041   memset(tpl_sync->num_finished_cols, -1,
2042          sizeof(*tpl_sync->num_finished_cols) * mb_rows);
2043 
2044   prepare_tpl_workers(cpi, tpl_worker_hook, num_workers);
2045   launch_workers(&cpi->mt_info, num_workers);
2046   sync_enc_workers(&cpi->mt_info, cm, num_workers);
2047   tpl_accumulate_txfm_stats(&cpi->td, &cpi->mt_info, num_workers);
2048 }
2049 
2050 // Deallocate memory for temporal filter multi-thread synchronization.
av1_tf_mt_dealloc(AV1TemporalFilterSync * tf_sync)2051 void av1_tf_mt_dealloc(AV1TemporalFilterSync *tf_sync) {
2052   assert(tf_sync != NULL);
2053 #if CONFIG_MULTITHREAD
2054   if (tf_sync->mutex_ != NULL) {
2055     pthread_mutex_destroy(tf_sync->mutex_);
2056     aom_free(tf_sync->mutex_);
2057   }
2058 #endif  // CONFIG_MULTITHREAD
2059   tf_sync->next_tf_row = 0;
2060 }
2061 
2062 // Checks if a job is available. If job is available,
2063 // populates next_tf_row and returns 1, else returns 0.
tf_get_next_job(AV1TemporalFilterSync * tf_mt_sync,int * current_mb_row,int mb_rows)2064 static AOM_INLINE int tf_get_next_job(AV1TemporalFilterSync *tf_mt_sync,
2065                                       int *current_mb_row, int mb_rows) {
2066   int do_next_row = 0;
2067 #if CONFIG_MULTITHREAD
2068   pthread_mutex_t *tf_mutex_ = tf_mt_sync->mutex_;
2069   pthread_mutex_lock(tf_mutex_);
2070 #endif
2071   if (tf_mt_sync->next_tf_row < mb_rows) {
2072     *current_mb_row = tf_mt_sync->next_tf_row;
2073     tf_mt_sync->next_tf_row++;
2074     do_next_row = 1;
2075   }
2076 #if CONFIG_MULTITHREAD
2077   pthread_mutex_unlock(tf_mutex_);
2078 #endif
2079   return do_next_row;
2080 }
2081 
2082 // Hook function for each thread in temporal filter multi-threading.
tf_worker_hook(void * arg1,void * unused)2083 static int tf_worker_hook(void *arg1, void *unused) {
2084   (void)unused;
2085   EncWorkerData *thread_data = (EncWorkerData *)arg1;
2086   AV1_COMP *cpi = thread_data->cpi;
2087   ThreadData *td = thread_data->td;
2088   TemporalFilterCtx *tf_ctx = &cpi->tf_ctx;
2089   AV1TemporalFilterSync *tf_sync = &cpi->mt_info.tf_sync;
2090   const struct scale_factors *scale = &cpi->tf_ctx.sf;
2091   const int num_planes = av1_num_planes(&cpi->common);
2092   assert(num_planes >= 1 && num_planes <= MAX_MB_PLANE);
2093 
2094   MACROBLOCKD *mbd = &td->mb.e_mbd;
2095   uint8_t *input_buffer[MAX_MB_PLANE];
2096   MB_MODE_INFO **input_mb_mode_info;
2097   tf_save_state(mbd, &input_mb_mode_info, input_buffer, num_planes);
2098   tf_setup_macroblockd(mbd, &td->tf_data, scale);
2099 
2100   int current_mb_row = -1;
2101 
2102   while (tf_get_next_job(tf_sync, &current_mb_row, tf_ctx->mb_rows))
2103     av1_tf_do_filtering_row(cpi, td, current_mb_row);
2104 
2105   tf_restore_state(mbd, input_mb_mode_info, input_buffer, num_planes);
2106 
2107   return 1;
2108 }
2109 
2110 // Assigns temporal filter hook function and thread data to each worker.
prepare_tf_workers(AV1_COMP * cpi,AVxWorkerHook hook,int num_workers,int is_highbitdepth)2111 static void prepare_tf_workers(AV1_COMP *cpi, AVxWorkerHook hook,
2112                                int num_workers, int is_highbitdepth) {
2113   MultiThreadInfo *mt_info = &cpi->mt_info;
2114   mt_info->tf_sync.next_tf_row = 0;
2115   for (int i = num_workers - 1; i >= 0; i--) {
2116     AVxWorker *worker = &mt_info->workers[i];
2117     EncWorkerData *thread_data = &mt_info->tile_thr_data[i];
2118 
2119     worker->hook = hook;
2120     worker->data1 = thread_data;
2121     worker->data2 = NULL;
2122 
2123     thread_data->thread_id = i;
2124     // Set the starting tile for each thread.
2125     thread_data->start = i;
2126 
2127     thread_data->cpi = cpi;
2128     if (i == 0) {
2129       thread_data->td = &cpi->td;
2130     } else {
2131       thread_data->td = thread_data->original_td;
2132     }
2133 
2134     // Before encoding a frame, copy the thread data from cpi.
2135     if (thread_data->td != &cpi->td) {
2136       thread_data->td->mb = cpi->td.mb;
2137       // OBMC buffers are used only to init MS params and remain unused when
2138       // called from tf, hence set the buffers to defaults.
2139       av1_init_obmc_buffer(&thread_data->td->mb.obmc_buffer);
2140       if (!tf_alloc_and_reset_data(&thread_data->td->tf_data,
2141                                    cpi->tf_ctx.num_pels, is_highbitdepth)) {
2142         aom_internal_error(cpi->common.error, AOM_CODEC_MEM_ERROR,
2143                            "Error allocating temporal filter data");
2144       }
2145     }
2146   }
2147 }
2148 
2149 // Deallocate thread specific data for temporal filter.
tf_dealloc_thread_data(AV1_COMP * cpi,int num_workers,int is_highbitdepth)2150 static void tf_dealloc_thread_data(AV1_COMP *cpi, int num_workers,
2151                                    int is_highbitdepth) {
2152   MultiThreadInfo *mt_info = &cpi->mt_info;
2153   for (int i = num_workers - 1; i >= 0; i--) {
2154     EncWorkerData *thread_data = &mt_info->tile_thr_data[i];
2155     ThreadData *td = thread_data->td;
2156     if (td != &cpi->td) tf_dealloc_data(&td->tf_data, is_highbitdepth);
2157   }
2158 }
2159 
2160 // Accumulate sse and sum after temporal filtering.
tf_accumulate_frame_diff(AV1_COMP * cpi,int num_workers)2161 static void tf_accumulate_frame_diff(AV1_COMP *cpi, int num_workers) {
2162   FRAME_DIFF *total_diff = &cpi->td.tf_data.diff;
2163   for (int i = num_workers - 1; i >= 0; i--) {
2164     AVxWorker *const worker = &cpi->mt_info.workers[i];
2165     EncWorkerData *const thread_data = (EncWorkerData *)worker->data1;
2166     ThreadData *td = thread_data->td;
2167     FRAME_DIFF *diff = &td->tf_data.diff;
2168     if (td != &cpi->td) {
2169       total_diff->sse += diff->sse;
2170       total_diff->sum += diff->sum;
2171     }
2172   }
2173 }
2174 
2175 // Implements multi-threading for temporal filter.
av1_tf_do_filtering_mt(AV1_COMP * cpi)2176 void av1_tf_do_filtering_mt(AV1_COMP *cpi) {
2177   AV1_COMMON *cm = &cpi->common;
2178   MultiThreadInfo *mt_info = &cpi->mt_info;
2179   const int is_highbitdepth = cpi->tf_ctx.is_highbitdepth;
2180 
2181   int num_workers =
2182       AOMMIN(mt_info->num_mod_workers[MOD_TF], mt_info->num_workers);
2183 
2184   prepare_tf_workers(cpi, tf_worker_hook, num_workers, is_highbitdepth);
2185   launch_workers(mt_info, num_workers);
2186   sync_enc_workers(mt_info, cm, num_workers);
2187   tf_accumulate_frame_diff(cpi, num_workers);
2188   tf_dealloc_thread_data(cpi, num_workers, is_highbitdepth);
2189 }
2190 
2191 // Checks if a job is available in the current direction. If a job is available,
2192 // frame_idx will be populated and returns 1, else returns 0.
get_next_gm_job(AV1_COMP * cpi,int * frame_idx,int cur_dir)2193 static AOM_INLINE int get_next_gm_job(AV1_COMP *cpi, int *frame_idx,
2194                                       int cur_dir) {
2195   GlobalMotionInfo *gm_info = &cpi->gm_info;
2196   JobInfo *job_info = &cpi->mt_info.gm_sync.job_info;
2197 
2198   int total_refs = gm_info->num_ref_frames[cur_dir];
2199   int8_t cur_frame_to_process = job_info->next_frame_to_process[cur_dir];
2200 
2201   if (cur_frame_to_process < total_refs && !job_info->early_exit[cur_dir]) {
2202     *frame_idx = gm_info->reference_frames[cur_dir][cur_frame_to_process].frame;
2203     job_info->next_frame_to_process[cur_dir] += 1;
2204     return 1;
2205   }
2206   return 0;
2207 }
2208 
2209 // Switches the current direction and calls the function get_next_gm_job() if
2210 // the speed feature 'prune_ref_frame_for_gm_search' is not set.
switch_direction(AV1_COMP * cpi,int * frame_idx,int * cur_dir)2211 static AOM_INLINE void switch_direction(AV1_COMP *cpi, int *frame_idx,
2212                                         int *cur_dir) {
2213   if (cpi->sf.gm_sf.prune_ref_frame_for_gm_search) return;
2214   // Switch the direction and get next job
2215   *cur_dir = !(*cur_dir);
2216   get_next_gm_job(cpi, frame_idx, *(cur_dir));
2217 }
2218 
2219 // Initializes inliers, num_inliers and segment_map.
init_gm_thread_data(const GlobalMotionInfo * gm_info,GlobalMotionThreadData * thread_data)2220 static AOM_INLINE void init_gm_thread_data(
2221     const GlobalMotionInfo *gm_info, GlobalMotionThreadData *thread_data) {
2222   for (int m = 0; m < RANSAC_NUM_MOTIONS; m++) {
2223     MotionModel motion_params = thread_data->params_by_motion[m];
2224     av1_zero(motion_params.params);
2225     motion_params.num_inliers = 0;
2226   }
2227 
2228   av1_zero_array(thread_data->segment_map,
2229                  gm_info->segment_map_w * gm_info->segment_map_h);
2230 }
2231 
2232 // Hook function for each thread in global motion multi-threading.
gm_mt_worker_hook(void * arg1,void * unused)2233 static int gm_mt_worker_hook(void *arg1, void *unused) {
2234   (void)unused;
2235 
2236   EncWorkerData *thread_data = (EncWorkerData *)arg1;
2237   AV1_COMP *cpi = thread_data->cpi;
2238   GlobalMotionInfo *gm_info = &cpi->gm_info;
2239   MultiThreadInfo *mt_info = &cpi->mt_info;
2240   JobInfo *job_info = &mt_info->gm_sync.job_info;
2241   int thread_id = thread_data->thread_id;
2242   GlobalMotionThreadData *gm_thread_data =
2243       &mt_info->gm_sync.thread_data[thread_id];
2244   int cur_dir = job_info->thread_id_to_dir[thread_id];
2245 #if CONFIG_MULTITHREAD
2246   pthread_mutex_t *gm_mt_mutex_ = mt_info->gm_sync.mutex_;
2247 #endif
2248 
2249   while (1) {
2250     int ref_buf_idx = -1;
2251     int ref_frame_idx = -1;
2252 
2253 #if CONFIG_MULTITHREAD
2254     pthread_mutex_lock(gm_mt_mutex_);
2255 #endif
2256 
2257     // Populates ref_buf_idx(the reference frame type) for which global motion
2258     // estimation will be done.
2259     if (!get_next_gm_job(cpi, &ref_buf_idx, cur_dir)) {
2260       // No jobs are available for the current direction. Switch
2261       // to other direction and get the next job, if available.
2262       switch_direction(cpi, &ref_buf_idx, &cur_dir);
2263     }
2264 
2265     // 'ref_frame_idx' holds the index of the current reference frame type in
2266     // gm_info->reference_frames. job_info->next_frame_to_process will be
2267     // incremented in get_next_gm_job() and hence subtracting by 1.
2268     ref_frame_idx = job_info->next_frame_to_process[cur_dir] - 1;
2269 
2270 #if CONFIG_MULTITHREAD
2271     pthread_mutex_unlock(gm_mt_mutex_);
2272 #endif
2273 
2274     if (ref_buf_idx == -1) break;
2275 
2276     init_gm_thread_data(gm_info, gm_thread_data);
2277 
2278     // Compute global motion for the given ref_buf_idx.
2279     av1_compute_gm_for_valid_ref_frames(
2280         cpi, gm_info->ref_buf, ref_buf_idx, gm_info->num_src_corners,
2281         gm_info->src_corners, gm_info->src_buffer,
2282         gm_thread_data->params_by_motion, gm_thread_data->segment_map,
2283         gm_info->segment_map_w, gm_info->segment_map_h);
2284 
2285 #if CONFIG_MULTITHREAD
2286     pthread_mutex_lock(gm_mt_mutex_);
2287 #endif
2288     assert(ref_frame_idx != -1);
2289     // If global motion w.r.t. current ref frame is
2290     // INVALID/TRANSLATION/IDENTITY, skip the evaluation of global motion w.r.t
2291     // the remaining ref frames in that direction. The below exit is disabled
2292     // when ref frame distance w.r.t. current frame is zero. E.g.:
2293     // source_alt_ref_frame w.r.t. ARF frames.
2294     if (cpi->sf.gm_sf.prune_ref_frame_for_gm_search &&
2295         gm_info->reference_frames[cur_dir][ref_frame_idx].distance != 0 &&
2296         cpi->common.global_motion[ref_buf_idx].wmtype != ROTZOOM)
2297       job_info->early_exit[cur_dir] = 1;
2298 
2299 #if CONFIG_MULTITHREAD
2300     pthread_mutex_unlock(gm_mt_mutex_);
2301 #endif
2302   }
2303   return 1;
2304 }
2305 
2306 // Assigns global motion hook function and thread data to each worker.
prepare_gm_workers(AV1_COMP * cpi,AVxWorkerHook hook,int num_workers)2307 static AOM_INLINE void prepare_gm_workers(AV1_COMP *cpi, AVxWorkerHook hook,
2308                                           int num_workers) {
2309   MultiThreadInfo *mt_info = &cpi->mt_info;
2310   for (int i = num_workers - 1; i >= 0; i--) {
2311     AVxWorker *worker = &mt_info->workers[i];
2312     EncWorkerData *thread_data = &mt_info->tile_thr_data[i];
2313 
2314     worker->hook = hook;
2315     worker->data1 = thread_data;
2316     worker->data2 = NULL;
2317 
2318     thread_data->thread_id = i;
2319     // Set the starting tile for each thread.
2320     thread_data->start = i;
2321 
2322     thread_data->cpi = cpi;
2323     if (i == 0) {
2324       thread_data->td = &cpi->td;
2325     } else {
2326       thread_data->td = thread_data->original_td;
2327     }
2328   }
2329 }
2330 
2331 // Assigns available threads to past/future direction.
assign_thread_to_dir(int8_t * thread_id_to_dir,int num_workers)2332 static AOM_INLINE void assign_thread_to_dir(int8_t *thread_id_to_dir,
2333                                             int num_workers) {
2334   int8_t frame_dir_idx = 0;
2335 
2336   for (int i = 0; i < num_workers; i++) {
2337     thread_id_to_dir[i] = frame_dir_idx++;
2338     if (frame_dir_idx == MAX_DIRECTIONS) frame_dir_idx = 0;
2339   }
2340 }
2341 
2342 // Computes number of workers for global motion multi-threading.
compute_gm_workers(const AV1_COMP * cpi)2343 static AOM_INLINE int compute_gm_workers(const AV1_COMP *cpi) {
2344   int total_refs =
2345       cpi->gm_info.num_ref_frames[0] + cpi->gm_info.num_ref_frames[1];
2346   int num_gm_workers = cpi->sf.gm_sf.prune_ref_frame_for_gm_search
2347                            ? AOMMIN(MAX_DIRECTIONS, total_refs)
2348                            : total_refs;
2349   num_gm_workers = AOMMIN(num_gm_workers, cpi->mt_info.num_workers);
2350   return (num_gm_workers);
2351 }
2352 
2353 // Frees the memory allocated for each worker in global motion multi-threading.
av1_gm_dealloc(AV1GlobalMotionSync * gm_sync_data)2354 void av1_gm_dealloc(AV1GlobalMotionSync *gm_sync_data) {
2355   if (gm_sync_data->thread_data != NULL) {
2356     for (int j = 0; j < gm_sync_data->allocated_workers; j++) {
2357       GlobalMotionThreadData *thread_data = &gm_sync_data->thread_data[j];
2358       aom_free(thread_data->segment_map);
2359 
2360       for (int m = 0; m < RANSAC_NUM_MOTIONS; m++)
2361         aom_free(thread_data->params_by_motion[m].inliers);
2362     }
2363     aom_free(gm_sync_data->thread_data);
2364   }
2365 }
2366 
2367 // Allocates memory for inliers and segment_map for each worker in global motion
2368 // multi-threading.
gm_alloc(AV1_COMP * cpi,int num_workers)2369 static AOM_INLINE void gm_alloc(AV1_COMP *cpi, int num_workers) {
2370   AV1_COMMON *cm = &cpi->common;
2371   AV1GlobalMotionSync *gm_sync = &cpi->mt_info.gm_sync;
2372   GlobalMotionInfo *gm_info = &cpi->gm_info;
2373 
2374   gm_sync->allocated_workers = num_workers;
2375   gm_sync->allocated_width = cpi->source->y_width;
2376   gm_sync->allocated_height = cpi->source->y_height;
2377 
2378   CHECK_MEM_ERROR(cm, gm_sync->thread_data,
2379                   aom_malloc(sizeof(*gm_sync->thread_data) * num_workers));
2380 
2381   for (int i = 0; i < num_workers; i++) {
2382     GlobalMotionThreadData *thread_data = &gm_sync->thread_data[i];
2383     CHECK_MEM_ERROR(
2384         cm, thread_data->segment_map,
2385         aom_malloc(sizeof(*thread_data->segment_map) * gm_info->segment_map_w *
2386                    gm_info->segment_map_h));
2387 
2388     for (int m = 0; m < RANSAC_NUM_MOTIONS; m++) {
2389       CHECK_MEM_ERROR(
2390           cm, thread_data->params_by_motion[m].inliers,
2391           aom_malloc(sizeof(*thread_data->params_by_motion[m].inliers) * 2 *
2392                      MAX_CORNERS));
2393     }
2394   }
2395 }
2396 
2397 // Implements multi-threading for global motion.
av1_global_motion_estimation_mt(AV1_COMP * cpi)2398 void av1_global_motion_estimation_mt(AV1_COMP *cpi) {
2399   AV1GlobalMotionSync *gm_sync = &cpi->mt_info.gm_sync;
2400   JobInfo *job_info = &gm_sync->job_info;
2401 
2402   av1_zero(*job_info);
2403 
2404   int num_workers = compute_gm_workers(cpi);
2405 
2406   if (num_workers > gm_sync->allocated_workers ||
2407       cpi->source->y_width != gm_sync->allocated_width ||
2408       cpi->source->y_height != gm_sync->allocated_height) {
2409     av1_gm_dealloc(gm_sync);
2410     gm_alloc(cpi, num_workers);
2411   }
2412 
2413   assign_thread_to_dir(job_info->thread_id_to_dir, num_workers);
2414   prepare_gm_workers(cpi, gm_mt_worker_hook, num_workers);
2415   launch_workers(&cpi->mt_info, num_workers);
2416   sync_enc_workers(&cpi->mt_info, &cpi->common, num_workers);
2417 }
2418 #endif  // !CONFIG_REALTIME_ONLY
2419 
2420 // Allocate memory for row synchronization
wiener_var_sync_mem_alloc(AV1EncRowMultiThreadSync * const row_mt_sync,AV1_COMMON * const cm,const int rows)2421 static void wiener_var_sync_mem_alloc(
2422     AV1EncRowMultiThreadSync *const row_mt_sync, AV1_COMMON *const cm,
2423     const int rows) {
2424 #if CONFIG_MULTITHREAD
2425   int i;
2426 
2427   CHECK_MEM_ERROR(cm, row_mt_sync->mutex_,
2428                   aom_malloc(sizeof(*row_mt_sync->mutex_) * rows));
2429   if (row_mt_sync->mutex_) {
2430     for (i = 0; i < rows; ++i) {
2431       pthread_mutex_init(&row_mt_sync->mutex_[i], NULL);
2432     }
2433   }
2434 
2435   CHECK_MEM_ERROR(cm, row_mt_sync->cond_,
2436                   aom_malloc(sizeof(*row_mt_sync->cond_) * rows));
2437   if (row_mt_sync->cond_) {
2438     for (i = 0; i < rows; ++i) {
2439       pthread_cond_init(&row_mt_sync->cond_[i], NULL);
2440     }
2441   }
2442 #endif  // CONFIG_MULTITHREAD
2443 
2444   CHECK_MEM_ERROR(cm, row_mt_sync->num_finished_cols,
2445                   aom_malloc(sizeof(*row_mt_sync->num_finished_cols) * rows));
2446 
2447   row_mt_sync->rows = rows;
2448   // Set up nsync.
2449   row_mt_sync->sync_range = 1;
2450 }
2451 
2452 // Deallocate row based multi-threading synchronization related mutex and data
wiener_var_sync_mem_dealloc(AV1EncRowMultiThreadSync * row_mt_sync)2453 static void wiener_var_sync_mem_dealloc(AV1EncRowMultiThreadSync *row_mt_sync) {
2454   if (row_mt_sync != NULL) {
2455 #if CONFIG_MULTITHREAD
2456     int i;
2457 
2458     if (row_mt_sync->mutex_ != NULL) {
2459       for (i = 0; i < row_mt_sync->rows; ++i) {
2460         pthread_mutex_destroy(&row_mt_sync->mutex_[i]);
2461       }
2462       aom_free(row_mt_sync->mutex_);
2463     }
2464     if (row_mt_sync->cond_ != NULL) {
2465       for (i = 0; i < row_mt_sync->rows; ++i) {
2466         pthread_cond_destroy(&row_mt_sync->cond_[i]);
2467       }
2468       aom_free(row_mt_sync->cond_);
2469     }
2470 #endif  // CONFIG_MULTITHREAD
2471     aom_free(row_mt_sync->num_finished_cols);
2472 
2473     // clear the structure as the source of this call may be dynamic change
2474     // in tiles in which case this call will be followed by an _alloc()
2475     // which may fail.
2476     av1_zero(*row_mt_sync);
2477   }
2478 }
2479 
prepare_wiener_var_workers(AV1_COMP * const cpi,AVxWorkerHook hook,const int num_workers)2480 static AOM_INLINE void prepare_wiener_var_workers(AV1_COMP *const cpi,
2481                                                   AVxWorkerHook hook,
2482                                                   const int num_workers) {
2483   MultiThreadInfo *const mt_info = &cpi->mt_info;
2484   for (int i = num_workers - 1; i >= 0; i--) {
2485     AVxWorker *const worker = &mt_info->workers[i];
2486     EncWorkerData *const thread_data = &mt_info->tile_thr_data[i];
2487 
2488     worker->hook = hook;
2489     worker->data1 = thread_data;
2490     worker->data2 = NULL;
2491 
2492     thread_data->thread_id = i;
2493     // Set the starting tile for each thread, in this case the preprocessing
2494     // stage does not need tiles. So we set it to 0.
2495     thread_data->start = 0;
2496 
2497     thread_data->cpi = cpi;
2498     if (i == 0) {
2499       thread_data->td = &cpi->td;
2500     } else {
2501       thread_data->td = thread_data->original_td;
2502     }
2503 
2504     if (thread_data->td != &cpi->td) {
2505       thread_data->td->mb = cpi->td.mb;
2506     }
2507   }
2508 }
2509 
cal_mb_wiener_var_hook(void * arg1,void * unused)2510 static int cal_mb_wiener_var_hook(void *arg1, void *unused) {
2511   (void)unused;
2512   EncWorkerData *const thread_data = (EncWorkerData *)arg1;
2513   AV1_COMP *const cpi = thread_data->cpi;
2514   MACROBLOCK *x = &thread_data->td->mb;
2515   MACROBLOCKD *xd = &x->e_mbd;
2516   const BLOCK_SIZE bsize = cpi->weber_bsize;
2517   const int mb_step = mi_size_wide[bsize];
2518   AV1EncRowMultiThreadSync *const row_mt_sync = &cpi->tile_data[0].row_mt_sync;
2519   AV1EncRowMultiThreadInfo *const enc_row_mt = &cpi->mt_info.enc_row_mt;
2520   (void)enc_row_mt;
2521 #if CONFIG_MULTITHREAD
2522   pthread_mutex_t *enc_row_mt_mutex_ = enc_row_mt->mutex_;
2523 #endif
2524   DECLARE_ALIGNED(32, int16_t, src_diff[32 * 32]);
2525   DECLARE_ALIGNED(32, tran_low_t, coeff[32 * 32]);
2526   DECLARE_ALIGNED(32, tran_low_t, qcoeff[32 * 32]);
2527   DECLARE_ALIGNED(32, tran_low_t, dqcoeff[32 * 32]);
2528   double sum_rec_distortion = 0;
2529   double sum_est_rate = 0;
2530   int has_jobs = 1;
2531   while (has_jobs) {
2532     int current_mi_row = -1;
2533 #if CONFIG_MULTITHREAD
2534     pthread_mutex_lock(enc_row_mt_mutex_);
2535 #endif
2536     has_jobs = get_next_job(&cpi->tile_data[0], &current_mi_row, mb_step);
2537 #if CONFIG_MULTITHREAD
2538     pthread_mutex_unlock(enc_row_mt_mutex_);
2539 #endif
2540     if (!has_jobs) break;
2541     // TODO(chengchen): properly accumulate the distortion and rate.
2542     av1_calc_mb_wiener_var_row(cpi, x, xd, current_mi_row, src_diff, coeff,
2543                                qcoeff, dqcoeff, &sum_rec_distortion,
2544                                &sum_est_rate);
2545 #if CONFIG_MULTITHREAD
2546     pthread_mutex_lock(enc_row_mt_mutex_);
2547 #endif
2548     row_mt_sync->num_threads_working--;
2549 #if CONFIG_MULTITHREAD
2550     pthread_mutex_unlock(enc_row_mt_mutex_);
2551 #endif
2552   }
2553   return 1;
2554 }
2555 
2556 // This function is the multi-threading version of computing the wiener
2557 // variance.
2558 // Note that the wiener variance is used for allintra mode (1 pass) and its
2559 // computation is before the frame encoding, so we don't need to consider
2560 // the number of tiles, instead we allocate all available threads to
2561 // the computation.
av1_calc_mb_wiener_var_mt(AV1_COMP * cpi,int num_workers,double * sum_rec_distortion,double * sum_est_rate)2562 void av1_calc_mb_wiener_var_mt(AV1_COMP *cpi, int num_workers,
2563                                double *sum_rec_distortion,
2564                                double *sum_est_rate) {
2565   (void)sum_rec_distortion;
2566   (void)sum_est_rate;
2567   AV1_COMMON *const cm = &cpi->common;
2568   MultiThreadInfo *const mt_info = &cpi->mt_info;
2569   const int tile_cols = 1;
2570   const int tile_rows = 1;
2571   if (cpi->tile_data != NULL) aom_free(cpi->tile_data);
2572   CHECK_MEM_ERROR(
2573       cm, cpi->tile_data,
2574       aom_memalign(32, tile_cols * tile_rows * sizeof(*cpi->tile_data)));
2575   cpi->allocated_tiles = tile_cols * tile_rows;
2576   cpi->tile_data->tile_info.mi_row_end = cm->mi_params.mi_rows;
2577   AV1EncRowMultiThreadSync *const row_mt_sync = &cpi->tile_data[0].row_mt_sync;
2578 
2579   // TODO(chengchen): the memory usage could be improved.
2580   const int mi_rows = cm->mi_params.mi_rows;
2581   wiener_var_sync_mem_alloc(row_mt_sync, cm, mi_rows);
2582 
2583   row_mt_sync->intrabc_extra_top_right_sb_delay = 0;
2584   row_mt_sync->num_threads_working = num_workers;
2585   row_mt_sync->next_mi_row = 0;
2586   memset(row_mt_sync->num_finished_cols, -1,
2587          sizeof(*row_mt_sync->num_finished_cols) * num_workers);
2588 
2589   prepare_wiener_var_workers(cpi, cal_mb_wiener_var_hook, num_workers);
2590   launch_workers(mt_info, num_workers);
2591   sync_enc_workers(mt_info, cm, num_workers);
2592 
2593   wiener_var_sync_mem_dealloc(row_mt_sync);
2594 }
2595 
2596 // Compare and order tiles based on absolute sum of tx coeffs.
compare_tile_order(const void * a,const void * b)2597 static int compare_tile_order(const void *a, const void *b) {
2598   const PackBSTileOrder *const tile_a = (const PackBSTileOrder *)a;
2599   const PackBSTileOrder *const tile_b = (const PackBSTileOrder *)b;
2600 
2601   if (tile_a->abs_sum_level > tile_b->abs_sum_level)
2602     return -1;
2603   else if (tile_a->abs_sum_level == tile_b->abs_sum_level)
2604     return (tile_a->tile_idx > tile_b->tile_idx ? 1 : -1);
2605   else
2606     return 1;
2607 }
2608 
2609 // Get next tile index to be processed for pack bitstream
get_next_pack_bs_tile_idx(AV1EncPackBSSync * const pack_bs_sync,const int num_tiles)2610 static AOM_INLINE int get_next_pack_bs_tile_idx(
2611     AV1EncPackBSSync *const pack_bs_sync, const int num_tiles) {
2612   assert(pack_bs_sync->next_job_idx <= num_tiles);
2613   if (pack_bs_sync->next_job_idx == num_tiles) return -1;
2614 
2615   return pack_bs_sync->pack_bs_tile_order[pack_bs_sync->next_job_idx++]
2616       .tile_idx;
2617 }
2618 
2619 // Calculates bitstream chunk size based on total buffer size and tile or tile
2620 // group size.
get_bs_chunk_size(int tg_or_tile_size,const int frame_or_tg_size,size_t * remain_buf_size,size_t max_buf_size,int is_last_chunk)2621 static AOM_INLINE size_t get_bs_chunk_size(int tg_or_tile_size,
2622                                            const int frame_or_tg_size,
2623                                            size_t *remain_buf_size,
2624                                            size_t max_buf_size,
2625                                            int is_last_chunk) {
2626   size_t this_chunk_size;
2627   assert(*remain_buf_size > 0);
2628   if (is_last_chunk) {
2629     this_chunk_size = *remain_buf_size;
2630     *remain_buf_size = 0;
2631   } else {
2632     const uint64_t size_scale = (uint64_t)max_buf_size * tg_or_tile_size;
2633     this_chunk_size = (size_t)(size_scale / frame_or_tg_size);
2634     *remain_buf_size -= this_chunk_size;
2635     assert(*remain_buf_size > 0);
2636   }
2637   assert(this_chunk_size > 0);
2638   return this_chunk_size;
2639 }
2640 
2641 // Initializes params required for pack bitstream tile.
init_tile_pack_bs_params(AV1_COMP * const cpi,uint8_t * const dst,struct aom_write_bit_buffer * saved_wb,PackBSParams * const pack_bs_params_arr,uint8_t obu_extn_header)2642 static void init_tile_pack_bs_params(AV1_COMP *const cpi, uint8_t *const dst,
2643                                      struct aom_write_bit_buffer *saved_wb,
2644                                      PackBSParams *const pack_bs_params_arr,
2645                                      uint8_t obu_extn_header) {
2646   MACROBLOCKD *const xd = &cpi->td.mb.e_mbd;
2647   AV1_COMMON *const cm = &cpi->common;
2648   const CommonTileParams *const tiles = &cm->tiles;
2649   const int num_tiles = tiles->cols * tiles->rows;
2650   // Fixed size tile groups for the moment
2651   const int num_tg_hdrs = cpi->num_tg;
2652   // Tile group size in terms of number of tiles.
2653   const int tg_size_in_tiles = (num_tiles + num_tg_hdrs - 1) / num_tg_hdrs;
2654   uint8_t *tile_dst = dst;
2655   uint8_t *tile_data_curr = dst;
2656   // Max tile group count can not be more than MAX_TILES.
2657   int tg_size_mi[MAX_TILES] = { 0 };  // Size of tile group in mi units
2658   int tile_idx;
2659   int tg_idx = 0;
2660   int tile_count_in_tg = 0;
2661   int new_tg = 1;
2662 
2663   // Populate pack bitstream params of all tiles.
2664   for (tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
2665     const TileInfo *const tile_info = &cpi->tile_data[tile_idx].tile_info;
2666     PackBSParams *const pack_bs_params = &pack_bs_params_arr[tile_idx];
2667     // Calculate tile size in mi units.
2668     const int tile_size_mi = (tile_info->mi_col_end - tile_info->mi_col_start) *
2669                              (tile_info->mi_row_end - tile_info->mi_row_start);
2670     int is_last_tile_in_tg = 0;
2671     tile_count_in_tg++;
2672     if (tile_count_in_tg == tg_size_in_tiles || tile_idx == (num_tiles - 1))
2673       is_last_tile_in_tg = 1;
2674 
2675     // Populate pack bitstream params of this tile.
2676     pack_bs_params->curr_tg_hdr_size = 0;
2677     pack_bs_params->obu_extn_header = obu_extn_header;
2678     pack_bs_params->saved_wb = saved_wb;
2679     pack_bs_params->obu_header_size = 0;
2680     pack_bs_params->is_last_tile_in_tg = is_last_tile_in_tg;
2681     pack_bs_params->new_tg = new_tg;
2682     pack_bs_params->tile_col = tile_info->tile_col;
2683     pack_bs_params->tile_row = tile_info->tile_row;
2684     pack_bs_params->tile_size_mi = tile_size_mi;
2685     tg_size_mi[tg_idx] += tile_size_mi;
2686 
2687     if (new_tg) new_tg = 0;
2688     if (is_last_tile_in_tg) {
2689       tile_count_in_tg = 0;
2690       new_tg = 1;
2691       tg_idx++;
2692     }
2693   }
2694 
2695   assert(cpi->available_bs_size > 0);
2696   size_t tg_buf_size[MAX_TILES] = { 0 };
2697   size_t max_buf_size = cpi->available_bs_size;
2698   size_t remain_buf_size = max_buf_size;
2699   const int frame_size_mi = cm->mi_params.mi_rows * cm->mi_params.mi_cols;
2700 
2701   tile_idx = 0;
2702   // Prepare obu, tile group and frame header of each tile group.
2703   for (tg_idx = 0; tg_idx < cpi->num_tg; tg_idx++) {
2704     PackBSParams *const pack_bs_params = &pack_bs_params_arr[tile_idx];
2705     int is_last_tg = tg_idx == cpi->num_tg - 1;
2706     // Prorate bitstream buffer size based on tile group size and available
2707     // buffer size. This buffer will be used to store headers and tile data.
2708     tg_buf_size[tg_idx] =
2709         get_bs_chunk_size(tg_size_mi[tg_idx], frame_size_mi, &remain_buf_size,
2710                           max_buf_size, is_last_tg);
2711 
2712     pack_bs_params->dst = tile_dst;
2713     pack_bs_params->tile_data_curr = tile_dst;
2714 
2715     // Write obu, tile group and frame header at first tile in the tile
2716     // group.
2717     av1_write_obu_tg_tile_headers(cpi, xd, pack_bs_params, tile_idx);
2718     tile_dst += tg_buf_size[tg_idx];
2719 
2720     // Exclude headers from tile group buffer size.
2721     tg_buf_size[tg_idx] -= pack_bs_params->curr_tg_hdr_size;
2722     tile_idx += tg_size_in_tiles;
2723   }
2724 
2725   tg_idx = 0;
2726   // Calculate bitstream buffer size of each tile in the tile group.
2727   for (tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
2728     PackBSParams *const pack_bs_params = &pack_bs_params_arr[tile_idx];
2729 
2730     if (pack_bs_params->new_tg) {
2731       max_buf_size = tg_buf_size[tg_idx];
2732       remain_buf_size = max_buf_size;
2733     }
2734 
2735     // Prorate bitstream buffer size of this tile based on tile size and
2736     // available buffer size. For this proration, header size is not accounted.
2737     const size_t tile_buf_size = get_bs_chunk_size(
2738         pack_bs_params->tile_size_mi, tg_size_mi[tg_idx], &remain_buf_size,
2739         max_buf_size, pack_bs_params->is_last_tile_in_tg);
2740     pack_bs_params->tile_buf_size = tile_buf_size;
2741 
2742     // Update base address of bitstream buffer for tile and tile group.
2743     if (pack_bs_params->new_tg) {
2744       tile_dst = pack_bs_params->dst;
2745       tile_data_curr = pack_bs_params->tile_data_curr;
2746       // Account header size in first tile of a tile group.
2747       pack_bs_params->tile_buf_size += pack_bs_params->curr_tg_hdr_size;
2748     } else {
2749       pack_bs_params->dst = tile_dst;
2750       pack_bs_params->tile_data_curr = tile_data_curr;
2751     }
2752 
2753     if (pack_bs_params->is_last_tile_in_tg) tg_idx++;
2754     tile_dst += pack_bs_params->tile_buf_size;
2755   }
2756 }
2757 
2758 // Worker hook function of pack bitsteam multithreading.
pack_bs_worker_hook(void * arg1,void * arg2)2759 static int pack_bs_worker_hook(void *arg1, void *arg2) {
2760   EncWorkerData *const thread_data = (EncWorkerData *)arg1;
2761   PackBSParams *const pack_bs_params = (PackBSParams *)arg2;
2762   AV1_COMP *const cpi = thread_data->cpi;
2763   AV1_COMMON *const cm = &cpi->common;
2764   AV1EncPackBSSync *const pack_bs_sync = &cpi->mt_info.pack_bs_sync;
2765   const CommonTileParams *const tiles = &cm->tiles;
2766   const int num_tiles = tiles->cols * tiles->rows;
2767 
2768   while (1) {
2769 #if CONFIG_MULTITHREAD
2770     pthread_mutex_lock(pack_bs_sync->mutex_);
2771 #endif
2772     const int tile_idx = get_next_pack_bs_tile_idx(pack_bs_sync, num_tiles);
2773 #if CONFIG_MULTITHREAD
2774     pthread_mutex_unlock(pack_bs_sync->mutex_);
2775 #endif
2776     if (tile_idx == -1) break;
2777     TileDataEnc *this_tile = &cpi->tile_data[tile_idx];
2778     thread_data->td->mb.e_mbd.tile_ctx = &this_tile->tctx;
2779 
2780     av1_pack_tile_info(cpi, thread_data->td, &pack_bs_params[tile_idx]);
2781   }
2782 
2783   return 1;
2784 }
2785 
2786 // Prepares thread data and workers of pack bitsteam multithreading.
prepare_pack_bs_workers(AV1_COMP * const cpi,PackBSParams * const pack_bs_params,AVxWorkerHook hook,const int num_workers)2787 static void prepare_pack_bs_workers(AV1_COMP *const cpi,
2788                                     PackBSParams *const pack_bs_params,
2789                                     AVxWorkerHook hook, const int num_workers) {
2790   MultiThreadInfo *const mt_info = &cpi->mt_info;
2791   for (int i = num_workers - 1; i >= 0; i--) {
2792     AVxWorker *worker = &mt_info->workers[i];
2793     EncWorkerData *const thread_data = &mt_info->tile_thr_data[i];
2794     if (i == 0) {
2795       thread_data->td = &cpi->td;
2796     } else {
2797       thread_data->td = thread_data->original_td;
2798     }
2799 
2800     if (thread_data->td != &cpi->td) thread_data->td->mb = cpi->td.mb;
2801 
2802     thread_data->cpi = cpi;
2803     thread_data->start = i;
2804     thread_data->thread_id = i;
2805     av1_reset_pack_bs_thread_data(thread_data->td);
2806 
2807     worker->hook = hook;
2808     worker->data1 = thread_data;
2809     worker->data2 = pack_bs_params;
2810   }
2811 
2812   AV1_COMMON *const cm = &cpi->common;
2813   AV1EncPackBSSync *const pack_bs_sync = &mt_info->pack_bs_sync;
2814   const uint16_t num_tiles = cm->tiles.rows * cm->tiles.cols;
2815   pack_bs_sync->next_job_idx = 0;
2816 
2817   PackBSTileOrder *const pack_bs_tile_order = pack_bs_sync->pack_bs_tile_order;
2818   // Reset tile order data of pack bitstream
2819   av1_zero_array(pack_bs_tile_order, num_tiles);
2820 
2821   // Populate pack bitstream tile order structure
2822   for (uint16_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) {
2823     pack_bs_tile_order[tile_idx].abs_sum_level =
2824         cpi->tile_data[tile_idx].abs_sum_level;
2825     pack_bs_tile_order[tile_idx].tile_idx = tile_idx;
2826   }
2827 
2828   // Sort tiles in descending order based on tile area.
2829   qsort(pack_bs_tile_order, num_tiles, sizeof(*pack_bs_tile_order),
2830         compare_tile_order);
2831 }
2832 
2833 // Accumulates data after pack bitsteam processing.
accumulate_pack_bs_data(AV1_COMP * const cpi,const PackBSParams * const pack_bs_params_arr,uint8_t * const dst,uint32_t * total_size,const FrameHeaderInfo * fh_info,int * const largest_tile_id,unsigned int * max_tile_size,uint32_t * const obu_header_size,uint8_t ** tile_data_start,const int num_workers)2834 static void accumulate_pack_bs_data(
2835     AV1_COMP *const cpi, const PackBSParams *const pack_bs_params_arr,
2836     uint8_t *const dst, uint32_t *total_size, const FrameHeaderInfo *fh_info,
2837     int *const largest_tile_id, unsigned int *max_tile_size,
2838     uint32_t *const obu_header_size, uint8_t **tile_data_start,
2839     const int num_workers) {
2840   const AV1_COMMON *const cm = &cpi->common;
2841   const CommonTileParams *const tiles = &cm->tiles;
2842   const int tile_count = tiles->cols * tiles->rows;
2843   // Fixed size tile groups for the moment
2844   size_t curr_tg_data_size = 0;
2845   int is_first_tg = 1;
2846   uint8_t *curr_tg_start = dst;
2847   size_t src_offset = 0;
2848   size_t dst_offset = 0;
2849 
2850   for (int tile_idx = 0; tile_idx < tile_count; tile_idx++) {
2851     // PackBSParams stores all parameters required to pack tile and header
2852     // info.
2853     const PackBSParams *const pack_bs_params = &pack_bs_params_arr[tile_idx];
2854     uint32_t tile_size = 0;
2855 
2856     if (pack_bs_params->new_tg) {
2857       curr_tg_start = dst + *total_size;
2858       curr_tg_data_size = pack_bs_params->curr_tg_hdr_size;
2859       *tile_data_start += pack_bs_params->curr_tg_hdr_size;
2860       *obu_header_size = pack_bs_params->obu_header_size;
2861     }
2862     curr_tg_data_size +=
2863         pack_bs_params->buf.size + (pack_bs_params->is_last_tile_in_tg ? 0 : 4);
2864 
2865     if (pack_bs_params->buf.size > *max_tile_size) {
2866       *largest_tile_id = tile_idx;
2867       *max_tile_size = (unsigned int)pack_bs_params->buf.size;
2868     }
2869     tile_size +=
2870         (uint32_t)pack_bs_params->buf.size + *pack_bs_params->total_size;
2871 
2872     // Pack all the chunks of tile bitstreams together
2873     if (tile_idx != 0) memmove(dst + dst_offset, dst + src_offset, tile_size);
2874 
2875     if (pack_bs_params->is_last_tile_in_tg)
2876       av1_write_last_tile_info(
2877           cpi, fh_info, pack_bs_params->saved_wb, &curr_tg_data_size,
2878           curr_tg_start, &tile_size, tile_data_start, largest_tile_id,
2879           &is_first_tg, *obu_header_size, pack_bs_params->obu_extn_header);
2880     src_offset += pack_bs_params->tile_buf_size;
2881     dst_offset += tile_size;
2882     *total_size += tile_size;
2883   }
2884 
2885   // Accumulate thread data
2886   MultiThreadInfo *const mt_info = &cpi->mt_info;
2887   for (int idx = num_workers - 1; idx >= 0; idx--) {
2888     ThreadData const *td = mt_info->tile_thr_data[idx].td;
2889     av1_accumulate_pack_bs_thread_data(cpi, td);
2890   }
2891 }
2892 
av1_write_tile_obu_mt(AV1_COMP * const cpi,uint8_t * const dst,uint32_t * total_size,struct aom_write_bit_buffer * saved_wb,uint8_t obu_extn_header,const FrameHeaderInfo * fh_info,int * const largest_tile_id,unsigned int * max_tile_size,uint32_t * const obu_header_size,uint8_t ** tile_data_start,const int num_workers)2893 void av1_write_tile_obu_mt(
2894     AV1_COMP *const cpi, uint8_t *const dst, uint32_t *total_size,
2895     struct aom_write_bit_buffer *saved_wb, uint8_t obu_extn_header,
2896     const FrameHeaderInfo *fh_info, int *const largest_tile_id,
2897     unsigned int *max_tile_size, uint32_t *const obu_header_size,
2898     uint8_t **tile_data_start, const int num_workers) {
2899   MultiThreadInfo *const mt_info = &cpi->mt_info;
2900 
2901   PackBSParams pack_bs_params[MAX_TILES];
2902   uint32_t tile_size[MAX_TILES] = { 0 };
2903 
2904   for (int tile_idx = 0; tile_idx < MAX_TILES; tile_idx++)
2905     pack_bs_params[tile_idx].total_size = &tile_size[tile_idx];
2906 
2907   init_tile_pack_bs_params(cpi, dst, saved_wb, pack_bs_params, obu_extn_header);
2908   prepare_pack_bs_workers(cpi, pack_bs_params, pack_bs_worker_hook,
2909                           num_workers);
2910   launch_workers(mt_info, num_workers);
2911   sync_enc_workers(mt_info, &cpi->common, num_workers);
2912   accumulate_pack_bs_data(cpi, pack_bs_params, dst, total_size, fh_info,
2913                           largest_tile_id, max_tile_size, obu_header_size,
2914                           tile_data_start, num_workers);
2915 }
2916 
2917 // Deallocate memory for CDEF search multi-thread synchronization.
av1_cdef_mt_dealloc(AV1CdefSync * cdef_sync)2918 void av1_cdef_mt_dealloc(AV1CdefSync *cdef_sync) {
2919   (void)cdef_sync;
2920   assert(cdef_sync != NULL);
2921 #if CONFIG_MULTITHREAD
2922   if (cdef_sync->mutex_ != NULL) {
2923     pthread_mutex_destroy(cdef_sync->mutex_);
2924     aom_free(cdef_sync->mutex_);
2925   }
2926 #endif  // CONFIG_MULTITHREAD
2927 }
2928 
2929 // Updates the row and column indices of the next job to be processed.
2930 // Also updates end_of_frame flag when the processing of all blocks is complete.
update_next_job_info(AV1CdefSync * cdef_sync,int nvfb,int nhfb)2931 static void update_next_job_info(AV1CdefSync *cdef_sync, int nvfb, int nhfb) {
2932   cdef_sync->fbc++;
2933   if (cdef_sync->fbc == nhfb) {
2934     cdef_sync->fbr++;
2935     if (cdef_sync->fbr == nvfb) {
2936       cdef_sync->end_of_frame = 1;
2937     } else {
2938       cdef_sync->fbc = 0;
2939     }
2940   }
2941 }
2942 
2943 // Initializes cdef_sync parameters.
cdef_reset_job_info(AV1CdefSync * cdef_sync)2944 static AOM_INLINE void cdef_reset_job_info(AV1CdefSync *cdef_sync) {
2945 #if CONFIG_MULTITHREAD
2946   if (cdef_sync->mutex_) pthread_mutex_init(cdef_sync->mutex_, NULL);
2947 #endif  // CONFIG_MULTITHREAD
2948   cdef_sync->end_of_frame = 0;
2949   cdef_sync->fbr = 0;
2950   cdef_sync->fbc = 0;
2951 }
2952 
2953 // Checks if a job is available. If job is available,
2954 // populates next job information and returns 1, else returns 0.
cdef_get_next_job(AV1CdefSync * cdef_sync,CdefSearchCtx * cdef_search_ctx,int * cur_fbr,int * cur_fbc,int * sb_count)2955 static AOM_INLINE int cdef_get_next_job(AV1CdefSync *cdef_sync,
2956                                         CdefSearchCtx *cdef_search_ctx,
2957                                         int *cur_fbr, int *cur_fbc,
2958                                         int *sb_count) {
2959 #if CONFIG_MULTITHREAD
2960   pthread_mutex_lock(cdef_sync->mutex_);
2961 #endif  // CONFIG_MULTITHREAD
2962   int do_next_block = 0;
2963   const int nvfb = cdef_search_ctx->nvfb;
2964   const int nhfb = cdef_search_ctx->nhfb;
2965 
2966   // If a block is skip, do not process the block and
2967   // check the skip condition for the next block.
2968   while ((!cdef_sync->end_of_frame) &&
2969          (cdef_sb_skip(cdef_search_ctx->mi_params, cdef_sync->fbr,
2970                        cdef_sync->fbc))) {
2971     update_next_job_info(cdef_sync, nvfb, nhfb);
2972   }
2973 
2974   // Populates information needed for current job and update the row,
2975   // column indices of the next block to be processed.
2976   if (cdef_sync->end_of_frame == 0) {
2977     do_next_block = 1;
2978     *cur_fbr = cdef_sync->fbr;
2979     *cur_fbc = cdef_sync->fbc;
2980     *sb_count = cdef_search_ctx->sb_count;
2981     cdef_search_ctx->sb_count++;
2982     update_next_job_info(cdef_sync, nvfb, nhfb);
2983   }
2984 #if CONFIG_MULTITHREAD
2985   pthread_mutex_unlock(cdef_sync->mutex_);
2986 #endif  // CONFIG_MULTITHREAD
2987   return do_next_block;
2988 }
2989 
2990 // Hook function for each thread in CDEF search multi-threading.
cdef_filter_block_worker_hook(void * arg1,void * arg2)2991 static int cdef_filter_block_worker_hook(void *arg1, void *arg2) {
2992   AV1CdefSync *const cdef_sync = (AV1CdefSync *)arg1;
2993   CdefSearchCtx *cdef_search_ctx = (CdefSearchCtx *)arg2;
2994   int cur_fbr, cur_fbc, sb_count;
2995   while (cdef_get_next_job(cdef_sync, cdef_search_ctx, &cur_fbr, &cur_fbc,
2996                            &sb_count)) {
2997     av1_cdef_mse_calc_block(cdef_search_ctx, cur_fbr, cur_fbc, sb_count);
2998   }
2999   return 1;
3000 }
3001 
3002 // Assigns CDEF search hook function and thread data to each worker.
prepare_cdef_workers(MultiThreadInfo * mt_info,CdefSearchCtx * cdef_search_ctx,AVxWorkerHook hook,int num_workers)3003 static void prepare_cdef_workers(MultiThreadInfo *mt_info,
3004                                  CdefSearchCtx *cdef_search_ctx,
3005                                  AVxWorkerHook hook, int num_workers) {
3006   for (int i = num_workers - 1; i >= 0; i--) {
3007     AVxWorker *worker = &mt_info->workers[i];
3008     worker->hook = hook;
3009     worker->data1 = &mt_info->cdef_sync;
3010     worker->data2 = cdef_search_ctx;
3011   }
3012 }
3013 
3014 // Implements multi-threading for CDEF search.
av1_cdef_mse_calc_frame_mt(AV1_COMMON * cm,MultiThreadInfo * mt_info,CdefSearchCtx * cdef_search_ctx)3015 void av1_cdef_mse_calc_frame_mt(AV1_COMMON *cm, MultiThreadInfo *mt_info,
3016                                 CdefSearchCtx *cdef_search_ctx) {
3017   AV1CdefSync *cdef_sync = &mt_info->cdef_sync;
3018   const int num_workers = mt_info->num_mod_workers[MOD_CDEF_SEARCH];
3019 
3020   cdef_reset_job_info(cdef_sync);
3021   prepare_cdef_workers(mt_info, cdef_search_ctx, cdef_filter_block_worker_hook,
3022                        num_workers);
3023   launch_workers(mt_info, num_workers);
3024   sync_enc_workers(mt_info, cm, num_workers);
3025 }
3026 
3027 // Computes num_workers for temporal filter multi-threading.
compute_num_tf_workers(AV1_COMP * cpi)3028 static AOM_INLINE int compute_num_tf_workers(AV1_COMP *cpi) {
3029   // For single-pass encode, using no. of workers as per tf block size was not
3030   // found to improve speed. Hence the thread assignment for single-pass encode
3031   // is kept based on compute_num_enc_workers().
3032   if (cpi->oxcf.pass < AOM_RC_SECOND_PASS)
3033     return (av1_compute_num_enc_workers(cpi, cpi->oxcf.max_threads));
3034 
3035   if (cpi->oxcf.max_threads <= 1) return 1;
3036 
3037   const int frame_height = cpi->common.height;
3038   const BLOCK_SIZE block_size = TF_BLOCK_SIZE;
3039   const int mb_height = block_size_high[block_size];
3040   const int mb_rows = get_num_blocks(frame_height, mb_height);
3041   return AOMMIN(cpi->oxcf.max_threads, mb_rows);
3042 }
3043 
3044 // Computes num_workers for tpl multi-threading.
compute_num_tpl_workers(AV1_COMP * cpi)3045 static AOM_INLINE int compute_num_tpl_workers(AV1_COMP *cpi) {
3046   return av1_compute_num_enc_workers(cpi, cpi->oxcf.max_threads);
3047 }
3048 
3049 // Computes num_workers for loop filter multi-threading.
compute_num_lf_workers(AV1_COMP * cpi)3050 static AOM_INLINE int compute_num_lf_workers(AV1_COMP *cpi) {
3051   return av1_compute_num_enc_workers(cpi, cpi->oxcf.max_threads);
3052 }
3053 
3054 // Computes num_workers for cdef multi-threading.
compute_num_cdef_workers(AV1_COMP * cpi)3055 static AOM_INLINE int compute_num_cdef_workers(AV1_COMP *cpi) {
3056   return av1_compute_num_enc_workers(cpi, cpi->oxcf.max_threads);
3057 }
3058 
3059 // Computes num_workers for loop-restoration multi-threading.
compute_num_lr_workers(AV1_COMP * cpi)3060 static AOM_INLINE int compute_num_lr_workers(AV1_COMP *cpi) {
3061   return av1_compute_num_enc_workers(cpi, cpi->oxcf.max_threads);
3062 }
3063 
3064 // Computes num_workers for pack bitstream multi-threading.
compute_num_pack_bs_workers(AV1_COMP * cpi)3065 static AOM_INLINE int compute_num_pack_bs_workers(AV1_COMP *cpi) {
3066   if (cpi->oxcf.max_threads <= 1) return 1;
3067   return compute_num_enc_tile_mt_workers(&cpi->common, cpi->oxcf.max_threads);
3068 }
3069 
3070 // Computes num_workers for all intra multi-threading.
compute_num_ai_workers(AV1_COMP * cpi)3071 static AOM_INLINE int compute_num_ai_workers(AV1_COMP *cpi) {
3072   if (cpi->oxcf.max_threads <= 1) return 1;
3073   cpi->weber_bsize = BLOCK_8X8;
3074   const BLOCK_SIZE bsize = cpi->weber_bsize;
3075   const int mb_step = mi_size_wide[bsize];
3076   const int num_mb_rows = cpi->common.mi_params.mi_rows / mb_step;
3077   return AOMMIN(num_mb_rows, cpi->oxcf.max_threads);
3078 }
3079 
compute_num_mod_workers(AV1_COMP * cpi,MULTI_THREADED_MODULES mod_name)3080 int compute_num_mod_workers(AV1_COMP *cpi, MULTI_THREADED_MODULES mod_name) {
3081   int num_mod_workers = 0;
3082   switch (mod_name) {
3083     case MOD_FP:
3084       if (cpi->oxcf.pass >= AOM_RC_SECOND_PASS)
3085         num_mod_workers = 0;
3086       else
3087         num_mod_workers =
3088             av1_compute_num_enc_workers(cpi, cpi->oxcf.max_threads);
3089       break;
3090     case MOD_TF: num_mod_workers = compute_num_tf_workers(cpi); break;
3091     case MOD_TPL: num_mod_workers = compute_num_tpl_workers(cpi); break;
3092     case MOD_GME: num_mod_workers = 1; break;
3093     case MOD_ENC:
3094       num_mod_workers = av1_compute_num_enc_workers(cpi, cpi->oxcf.max_threads);
3095       break;
3096     case MOD_LPF: num_mod_workers = compute_num_lf_workers(cpi); break;
3097     case MOD_CDEF_SEARCH:
3098       num_mod_workers = compute_num_cdef_workers(cpi);
3099       break;
3100     case MOD_CDEF: num_mod_workers = compute_num_cdef_workers(cpi); break;
3101     case MOD_LR: num_mod_workers = compute_num_lr_workers(cpi); break;
3102     case MOD_PACK_BS: num_mod_workers = compute_num_pack_bs_workers(cpi); break;
3103     case MOD_FRAME_ENC:
3104       num_mod_workers = cpi->ppi->p_mt_info.num_mod_workers[MOD_FRAME_ENC];
3105       break;
3106     case MOD_AI:
3107       if (cpi->oxcf.pass == AOM_RC_ONE_PASS) {
3108         num_mod_workers = compute_num_ai_workers(cpi);
3109         break;
3110       } else {
3111         num_mod_workers = 0;
3112         break;
3113       }
3114     default: assert(0); break;
3115   }
3116   return (num_mod_workers);
3117 }
3118 // Computes the number of workers for each MT modules in the encoder
av1_compute_num_workers_for_mt(AV1_COMP * cpi)3119 void av1_compute_num_workers_for_mt(AV1_COMP *cpi) {
3120   for (int i = MOD_FP; i < NUM_MT_MODULES; i++)
3121     cpi->ppi->p_mt_info.num_mod_workers[i] =
3122         compute_num_mod_workers(cpi, (MULTI_THREADED_MODULES)i);
3123 }
3124