Coverage Report

Created: 2026-10-27 06:32

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