Debian Codegraph @

src/videofilters/av1/encoder/av1-encoder.cpp

raw
1 /*
2 * Copyright (c) 2010-2022 Belledonne Communications SARL.
3 *
4 * This file is part of mediastreamer2
5 * (see https://gitlab.linphone.org/BC/public/mediastreamer2).
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16 *
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "av1-encoder.h"
22
23 #include <memory>
24
25 using namespace mediastreamer;
26 using namespace std;
27
28 namespace mediastreamer {
29
30 Av1Encoder::Av1Encoder(MSFactory *factory) : mFactory(factory) {
31 mEncoder = aom_codec_av1_cx();
32
33 aom_codec_err_t ret = aom_codec_enc_config_default(mEncoder, &mConfig, AOM_USAGE_REALTIME);
34 if (ret != AOM_CODEC_OK) {
35 ms_error("Av1Encoder: Cannot retrieve encoder default settings (%d).", ret);
36 }
37
38 ms_queue_init(&mToEncode);
39 ms_queue_init(&mEncodedFrames);
40 }
41
42 Av1Encoder::~Av1Encoder() {
43 if (mIsRunning) Av1Encoder::stop();
44 }
45
46 void Av1Encoder::setVideoSize(const MSVideoSize &vsize) {
47 mVsize = vsize;
48
49 mConfig.g_w = vsize.width;
50 mConfig.g_h = vsize.height;
51 }
52
53 void Av1Encoder::setFps(float fps) {
54 mFps = fps;
55
56 mConfig.g_timebase.num = 1;
57 mConfig.g_timebase.den = (int)fps;
58
59 if (mIsRunning) {
60 lock_guard<mutex> guard(mCodecMutex);
61 if (aom_codec_enc_config_set(&mCodec, &mConfig)) {
62 ms_error("Av1Encoder: Failed to set fps while encoder is running.");
63 }
64 }
65 }
66
67 void Av1Encoder::setBitrate(int bitrate) {
68 mBitrate = bitrate;
69
70 // 0.92=take into account IP/UDP/RTP overhead, in average.
71 mConfig.rc_target_bitrate = (unsigned int)(((float)mBitrate) * 0.92f / 1024.0f);
72
73 if (mIsRunning) {
74 lock_guard<mutex> guard(mCodecMutex);
75 if (aom_codec_enc_config_set(&mCodec, &mConfig)) {
76 ms_error("Av1Encoder: Failed to set bitrate while encoder is running.");
77 }
78 }
79 }
80
81 void Av1Encoder::configure(bool avpfEnabled) {
82 // This initial configuration is for now the same as VP8
83 #if TARGET_IPHONE_SIMULATOR
84 mConfig.g_threads = 1;
85 #elif TARGET_OS_OSX
86 mConfig.g_threads = std::max<int>(ms_factory_get_cpu_count(mFactory) - 2, 1);
87 #else
88 mConfig.g_threads = ms_factory_get_cpu_count(mFactory);
89 #endif
90
91 mConfig.g_error_resilient = AOM_ERROR_RESILIENT_DEFAULT;
92
93 if (avpfEnabled) {
94 mConfig.kf_mode = AOM_KF_DISABLED;
95 } else {
96 mConfig.kf_mode = AOM_KF_AUTO; // encoder automatically places keyframes
97 mConfig.kf_max_dist = 10 * mConfig.g_timebase.den; // 1 keyframe each 10s.
98 }
99 }
100
101 void Av1Encoder::start() {
102 if (mIsRunning) {
103 ms_warning("Av1Encoder: Trying to start encode while already running.");
104 return;
105 }
106
107 if (aom_codec_enc_init(&mCodec, mEncoder, &mConfig, 0)) {
108 ms_error("Av1Encoder: Failed to initialize encoder.");
109 } else {
110 aom_codec_control(&mCodec, AOME_SET_CPUUSED, 10);
111
112 mIsRunning = true;
113 mEncodeThread = std::thread(&Av1Encoder::encoderThread, this);
114 }
115 }
116
117 void Av1Encoder::stop() {
118 if (mIsRunning) {
119 mIsRunning = false;
120
121 // Ensure the encoding thread can finish
122 unique_lock<mutex> lk(mToEncodeMutex);
123 mFramesAvailable = true;
124 lk.unlock();
125 mToEncodeCondition.notify_one();
126
127 mEncodeThread.join();
128
129 flush();
130
131 if (aom_codec_destroy(&mCodec)) {
132 ms_error("Av1Encoder: Failed to destroy encoder.");
133 }
134 }
135 }
136
137 void Av1Encoder::feed(mblk_t *rawData, [[maybe_unused]] uint64_t time, bool requestIFrame) {
138 if (!mIsRunning) {
139 ms_error("Av1Encoder: encoder not running. Dropping buffer.");
140 return;
141 }
142
143 unique_lock<mutex> lk(mToEncodeMutex);
144
145 ms_queue_put(&mToEncode, rawData);
146
147 // Notify the encoding thread that frames are available
148 mFramesAvailable = true;
149
150 if (requestIFrame) mIframeRequested = true;
151
152 lk.unlock();
153 mToEncodeCondition.notify_one();
154 }
155
156 bool Av1Encoder::fetch(MSQueue *encodedData) {
157 if (!mIsRunning) return false;
158
159 lock_guard<mutex> guard(mEncodedFramesMutex);
160 if (ms_queue_empty(&mEncodedFrames)) return false;
161
162 mblk_t *out;
163 while ((out = ms_queue_get(&mEncodedFrames)) != nullptr) {
164 ms_queue_put(encodedData, out);
165 }
166
167 return true;
168 }
169
170 void Av1Encoder::encoderThread() {
171 while (mIsRunning) {
172 // Wait for available frames to pass to the encoder
173 unique_lock lk(mToEncodeMutex);
174 mToEncodeCondition.wait(lk, [this] { return this->mFramesAvailable; });
175
176 mblk_t *data = nullptr;
177 int skippedCount = 0;
178
179 mblk_t *previous = nullptr;
180 while ((data = ms_queue_get(&mToEncode)) != nullptr) {
181 if (previous) {
182 freemsg(previous);
183 skippedCount++;
184 }
185 previous = data;
186 }
187
188 if (data == nullptr) data = previous;
189
190 mFramesAvailable = false;
191 lk.unlock();
192
193 if (data == nullptr) continue;
194
195 if (skippedCount > 0) ms_warning("Av1Encoder: %i frames skipped by async encoding process", skippedCount);
196
197 MSPicture pic;
198 ms_yuv_buf_init_from_mblk(&pic, data);
199
200 aom_image_t img;
201 aom_img_wrap(&img, AOM_IMG_FMT_I420, mVsize.width, mVsize.height, 1, pic.planes[0]);
202
203 aom_enc_frame_flags_t flags = 0;
204
205 if (mFrameCount == 0) flags |= AOM_EFLAG_FORCE_KF;
206
207 lk.lock();
208 if (mIframeRequested) {
209 flags |= AOM_EFLAG_FORCE_KF;
210 mIframeRequested = false;
211 }
212 lk.unlock();
213
214 unique_lock codecLk(mCodecMutex);
215 aom_codec_err_t ret = aom_codec_encode(&mCodec, &img, mFrameCount, 1, flags);
216
217 if (ret != AOM_CODEC_OK) {
218 ms_error("Av1Encoder: encode failed: %s (%s)", aom_codec_err_to_string(ret),
219 aom_codec_error_detail(&mCodec));
220 }
221
222 const aom_codec_cx_pkt_t *pkt;
223 aom_codec_iter_t iter = nullptr;
224
225 while ((pkt = aom_codec_get_cx_data(&mCodec, &iter))) {
226 if (pkt->kind == AOM_CODEC_CX_FRAME_PKT) {
227 mblk_t *out = allocb(pkt->data.frame.sz, 0);
228 memcpy(out->b_wptr, pkt->data.frame.buf, pkt->data.frame.sz);
229 out->b_wptr += pkt->data.frame.sz;
230 mblk_set_timestamp_info(out, mblk_get_timestamp_info(data));
231
232 lock_guard<mutex> guard(mEncodedFramesMutex);
233 ms_queue_put(&mEncodedFrames, out);
234 }
235 }
236 codecLk.unlock();
237
238 mFrameCount++;
239
240 freemsg(data);
241 }
242 }
243
244 void Av1Encoder::flush() {
245 aom_codec_iter_t iter = nullptr;
246 while (aom_codec_get_cx_data(&mCodec, &iter))
247 continue;
248
249 ms_queue_flush(&mToEncode);
250 ms_queue_flush(&mEncodedFrames);
251 }
252
253 } // namespace mediastreamer