• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The libgav1 Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/threading_strategy.h"
16 
17 #include <algorithm>
18 #include <cassert>
19 #include <memory>
20 
21 #include "src/frame_scratch_buffer.h"
22 #include "src/utils/constants.h"
23 #include "src/utils/logging.h"
24 #include "src/utils/vector.h"
25 
26 namespace libgav1 {
27 namespace {
28 
29 #if !defined(LIBGAV1_FRAME_PARALLEL_THRESHOLD_MULTIPLIER)
30 constexpr int kFrameParallelThresholdMultiplier = 4;
31 #else
32 constexpr int kFrameParallelThresholdMultiplier =
33     LIBGAV1_FRAME_PARALLEL_THRESHOLD_MULTIPLIER;
34 #endif
35 
36 // Computes the number of frame threads to be used based on the following
37 // heuristic:
38 //   * If |thread_count| == 1, return 0.
39 //   * If |thread_count| <= |tile_count| * 4, return 0.
40 //   * Otherwise, return the largest value of i which satisfies the following
41 //     condition: i + i * tile_columns <= thread_count. This ensures that there
42 //     are at least |tile_columns| worker threads for each frame thread.
43 //   * This function will never return 1 or a value > |thread_count|.
44 //
45 //  This heuristic is based empirical performance data. The in-frame threading
46 //  model (combination of tile multithreading, superblock row multithreading and
47 //  post filter multithreading) performs better than the frame parallel model
48 //  until we reach the threshold of |thread_count| > |tile_count| *
49 //  kFrameParallelThresholdMultiplier.
50 //
51 //  It is a function of |tile_count| since tile threading and superblock row
52 //  multithreading will scale only as a factor of |tile_count|. The threshold 4
53 //  is arrived at based on empirical data. The general idea is that superblock
54 //  row multithreading plateaus at 4 * |tile_count| because in most practical
55 //  cases there aren't more than that many superblock rows and columns available
56 //  to work on in parallel.
ComputeFrameThreadCount(int thread_count,int tile_count,int tile_columns)57 int ComputeFrameThreadCount(int thread_count, int tile_count,
58                             int tile_columns) {
59   assert(thread_count > 0);
60   if (thread_count == 1) return 0;
61   return (thread_count <= tile_count * kFrameParallelThresholdMultiplier)
62              ? 0
63              : std::max(2, thread_count / (1 + tile_columns));
64 }
65 
66 }  // namespace
67 
Reset(const ObuFrameHeader & frame_header,int thread_count)68 bool ThreadingStrategy::Reset(const ObuFrameHeader& frame_header,
69                               int thread_count) {
70   assert(thread_count > 0);
71   frame_parallel_ = false;
72 
73   if (thread_count == 1) {
74     thread_pool_.reset(nullptr);
75     tile_thread_count_ = 0;
76     max_tile_index_for_row_threads_ = 0;
77     return true;
78   }
79 
80   // We do work in the current thread, so it is sufficient to create
81   // |thread_count|-1 threads in the threadpool.
82   thread_count = std::min(thread_count, static_cast<int>(kMaxThreads)) - 1;
83 
84   if (thread_pool_ == nullptr || thread_pool_->num_threads() != thread_count) {
85     thread_pool_ = ThreadPool::Create("libgav1", thread_count);
86     if (thread_pool_ == nullptr) {
87       LIBGAV1_DLOG(ERROR, "Failed to create a thread pool with %d threads.",
88                    thread_count);
89       tile_thread_count_ = 0;
90       max_tile_index_for_row_threads_ = 0;
91       return false;
92     }
93   }
94 
95   // Prefer tile threads first (but only if there is more than one tile).
96   const int tile_count = frame_header.tile_info.tile_count;
97   if (tile_count > 1) {
98     // We want 1 + tile_thread_count_ <= tile_count because the current thread
99     // is also used to decode tiles. This is equivalent to
100     // tile_thread_count_ <= tile_count - 1.
101     tile_thread_count_ = std::min(thread_count, tile_count - 1);
102     thread_count -= tile_thread_count_;
103     if (thread_count == 0) {
104       max_tile_index_for_row_threads_ = 0;
105       return true;
106     }
107   } else {
108     tile_thread_count_ = 0;
109   }
110 
111 #if defined(__ANDROID__)
112   // Assign the remaining threads for each Tile. The heuristic used here is that
113   // we will assign two threads for each Tile. So for example, if |thread_count|
114   // is 2, for a stream with 2 tiles the first tile would get both the threads
115   // and the second tile would have row multi-threading turned off. This
116   // heuristic is based on the fact that row multi-threading is fast enough only
117   // when there are at least two threads to do the decoding (since one thread
118   // always does the parsing).
119   //
120   // This heuristic might stop working when SIMD optimizations make the decoding
121   // much faster and the parsing thread is only as fast as the decoding threads.
122   // So we will have to revisit this later to make sure that this is still
123   // optimal.
124   //
125   // Note that while this heuristic significantly improves performance on high
126   // end devices (like the Pixel 3), there are some performance regressions in
127   // some lower end devices (in some cases) and that needs to be revisited as we
128   // bring in more optimizations. Overall, the gains because of this heuristic
129   // seems to be much larger than the regressions.
130   for (int i = 0; i < tile_count; ++i) {
131     max_tile_index_for_row_threads_ = i + 1;
132     thread_count -= 2;
133     if (thread_count <= 0) break;
134   }
135 #else  // !defined(__ANDROID__)
136   // Assign the remaining threads to each Tile.
137   for (int i = 0; i < tile_count; ++i) {
138     const int count = thread_count / tile_count +
139                       static_cast<int>(i < thread_count % tile_count);
140     if (count == 0) {
141       // Once we see a 0 value, all subsequent values will be 0 since it is
142       // supposed to be assigned in a round-robin fashion.
143       break;
144     }
145     max_tile_index_for_row_threads_ = i + 1;
146   }
147 #endif  // defined(__ANDROID__)
148   return true;
149 }
150 
Reset(int thread_count)151 bool ThreadingStrategy::Reset(int thread_count) {
152   assert(thread_count > 0);
153   frame_parallel_ = true;
154 
155   // In frame parallel mode, we simply access the underlying |thread_pool_|
156   // directly. So ensure all the other threadpool getter functions return
157   // nullptr. Also, superblock row multithreading is always disabled in frame
158   // parallel mode.
159   tile_thread_count_ = 0;
160   max_tile_index_for_row_threads_ = 0;
161 
162   if (thread_pool_ == nullptr || thread_pool_->num_threads() != thread_count) {
163     thread_pool_ = ThreadPool::Create("libgav1-fp", thread_count);
164     if (thread_pool_ == nullptr) {
165       LIBGAV1_DLOG(ERROR, "Failed to create a thread pool with %d threads.",
166                    thread_count);
167       return false;
168     }
169   }
170   return true;
171 }
172 
InitializeThreadPoolsForFrameParallel(int thread_count,int tile_count,int tile_columns,std::unique_ptr<ThreadPool> * const frame_thread_pool,FrameScratchBufferPool * const frame_scratch_buffer_pool)173 bool InitializeThreadPoolsForFrameParallel(
174     int thread_count, int tile_count, int tile_columns,
175     std::unique_ptr<ThreadPool>* const frame_thread_pool,
176     FrameScratchBufferPool* const frame_scratch_buffer_pool) {
177   assert(*frame_thread_pool == nullptr);
178   thread_count = std::min(thread_count, static_cast<int>(kMaxThreads));
179   const int frame_threads =
180       ComputeFrameThreadCount(thread_count, tile_count, tile_columns);
181   if (frame_threads == 0) return true;
182   *frame_thread_pool = ThreadPool::Create(frame_threads);
183   if (*frame_thread_pool == nullptr) {
184     LIBGAV1_DLOG(ERROR, "Failed to create frame thread pool with %d threads.",
185                  frame_threads);
186     return false;
187   }
188   int remaining_threads = thread_count - frame_threads;
189   if (remaining_threads == 0) return true;
190   int threads_per_frame = remaining_threads / frame_threads;
191   const int extra_threads = remaining_threads % frame_threads;
192   Vector<std::unique_ptr<FrameScratchBuffer>> frame_scratch_buffers;
193   if (!frame_scratch_buffers.reserve(frame_threads)) return false;
194   // Create the tile thread pools.
195   for (int i = 0; i < frame_threads && remaining_threads > 0; ++i) {
196     std::unique_ptr<FrameScratchBuffer> frame_scratch_buffer =
197         frame_scratch_buffer_pool->Get();
198     if (frame_scratch_buffer == nullptr) {
199       return false;
200     }
201     // If the number of tile threads cannot be divided equally amongst all the
202     // frame threads, assign one extra thread to the first |extra_threads| frame
203     // threads.
204     const int current_frame_thread_count =
205         threads_per_frame + static_cast<int>(i < extra_threads);
206     if (!frame_scratch_buffer->threading_strategy.Reset(
207             current_frame_thread_count)) {
208       return false;
209     }
210     remaining_threads -= current_frame_thread_count;
211     frame_scratch_buffers.push_back_unchecked(std::move(frame_scratch_buffer));
212   }
213   // We release the frame scratch buffers in reverse order so that the extra
214   // threads are allocated to buffers in the top of the stack.
215   for (int i = static_cast<int>(frame_scratch_buffers.size()) - 1; i >= 0;
216        --i) {
217     frame_scratch_buffer_pool->Release(std::move(frame_scratch_buffers[i]));
218   }
219   return true;
220 }
221 
222 }  // namespace libgav1
223