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