Coverage Report

Created: 2026-01-09 06:51

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