Debian Codegraph @

src/videofilters/h26x/videotoolbox-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 "TargetConditionals.h"
22
23 #include <bctoolbox/defs.h>
24
25 #include "h26x-utils.h"
26 #include "videotoolbox-utils.h"
27
28 #include "videotoolbox-encoder.h"
29
30 #define vt_enc_log(level, fmt, ...) ms_##level("VideoToolboxEncoder: " fmt, ##__VA_ARGS__)
31 #define vt_enc_message(fmt, ...) vt_enc_log(message, fmt, ##__VA_ARGS__)
32 #define vt_enc_warning(fmt, ...) vt_enc_log(warning, fmt, ##__VA_ARGS__)
33 #define vt_enc_error(fmt, ...) vt_enc_log(error, fmt, ##__VA_ARGS__)
34
35 using namespace std;
36
37 namespace mediastreamer {
38
39 VideoToolboxEncoder::Frame::Frame(Frame &&src) {
40 ms_queue_init(&_nalus);
41 while (mblk_t *m = ms_queue_get(&src._nalus)) {
42 ms_queue_put(&_nalus, m);
43 }
44 }
45
46 void VideoToolboxEncoder::Frame::insert(MSQueue *q) {
47 mblk_t *insertionPoint = ms_queue_peek_first(&_nalus);
48 while (mblk_t *m = ms_queue_get(q)) {
49 ms_queue_insert(&_nalus, insertionPoint, m);
50 }
51 }
52
53 VideoToolboxEncoder::VideoToolboxEncoder(const string &mime, int payloadMaxSize) : H26xEncoder(mime) {
54 _payloadMaxSize = payloadMaxSize;
55 _vsize.width = 0;
56 _vsize.height = 0;
57 ms_mutex_init(&_mutex, nullptr);
58 }
59
60 void VideoToolboxEncoder::setFps(float fps) {
61 float oldFramerate = _framerate;
62 try {
63 _framerate = fps;
64 if (isRunning()) applyFramerate();
65 } catch (const runtime_error &e) {
66 _framerate = oldFramerate;
67 throw;
68 }
69 }
70
71 void VideoToolboxEncoder::setBitrate(int bitrate) {
72 int oldBitrate = _bitrate;
73 try {
74 _bitrate = bitrate;
75 if (isRunning()) applyBitrate();
76 } catch (const runtime_error &e) {
77 _bitrate = oldBitrate;
78 throw;
79 }
80 }
81
82 void VideoToolboxEncoder::start() {
83 try {
84 OSStatus err;
85 CFNumberRef value;
86
87 unique_ptr<VideoToolboxUtilities> utils(VideoToolboxUtilities::create(_mime));
88
89 CFMutableDictionaryRef pixbuf_attr =
90 CFDictionaryCreateMutable(kCFAllocatorDefault, 1, NULL, &kCFTypeDictionaryValueCallBacks);
91 int32_t pixel_type = kCVPixelFormatType_420YpCbCr8Planar;
92 value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pixel_type);
93 CFDictionarySetValue(pixbuf_attr, kCVPixelBufferPixelFormatTypeKey, value);
94 CFRelease(value);
95
96 CFMutableDictionaryRef session_props = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, NULL, NULL);
97 #if !TARGET_OS_IPHONE
98 CFDictionarySetValue(session_props, kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
99 kCFBooleanTrue);
100 #endif
101
102 err = VTCompressionSessionCreate(kCFAllocatorDefault, _vsize.width, _vsize.height, utils->getCodecType(),
103 session_props, pixbuf_attr, kCFAllocatorDefault, outputCb, this, &_session);
104 CFRelease(pixbuf_attr);
105 CFRelease(session_props);
106 if (err) throw runtime_error("could not initialize the VideoToolbox compresson session: " + toString(err));
107
108 err = VTSessionSetProperty(_session, kVTCompressionPropertyKey_ProfileLevel, utils->getDefaultProfileLevel());
109 if (err != noErr) {
110 vt_enc_error("could not set profile and level: %s", toString(err).c_str());
111 }
112
113 err = VTSessionSetProperty(_session, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
114 if (err != noErr) {
115 vt_enc_warning("could not enable real-time mode: %s", toString(err).c_str());
116 }
117 err = VTSessionSetProperty(_session, kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse);
118 if (err != noErr) {
119 vt_enc_warning("could not set kVTCompressionPropertyKey_AllowFrameReordering: %s", toString(err).c_str());
120 }
121
122 int max_frame_count = 1;
123 value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &max_frame_count);
124
125 err = VTSessionSetProperty(_session, kVTCompressionPropertyKey_MaxFrameDelayCount, value);
126 if (err != noErr) {
127 vt_enc_warning("could not set kVTCompressionPropertyKey_MaxFrameDelayCount: %s", toString(err).c_str());
128 }
129 CFRelease(value);
130
131 value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &_payloadMaxSize);
132 err = VTSessionSetProperty(_session, kVTCompressionPropertyKey_MaxH264SliceBytes, value);
133 if (err != noErr) {
134 vt_enc_warning("could not set kVTCompressionPropertyKey_MaxH264SliceBytes: %s", toString(err).c_str());
135 }
136 CFRelease(value);
137
138 applyFramerate();
139 applyBitrate();
140
141 if ((err = VTCompressionSessionPrepareToEncodeFrames(_session)) != noErr) {
142 throw runtime_error("could not prepare the VideoToolbox compression session: " + toString(err));
143 }
144
145 vt_enc_message("encoder succesfully initialized.");
146 #if !TARGET_OS_IPHONE
147 CFBooleanRef hardware_acceleration_enabled;
148 err = VTSessionCopyProperty(_session, kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder,
149 kCFAllocatorDefault, &hardware_acceleration_enabled);
150 if (err != noErr) {
151 vt_enc_error("could not read kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder property: %s",
152 toString(err).c_str());
153 } else {
154 if (hardware_acceleration_enabled != nullptr && CFBooleanGetValue(hardware_acceleration_enabled)) {
155 vt_enc_message("hardware acceleration enabled");
156 } else {
157 vt_enc_warning("hardware acceleration not enabled");
158 }
159 }
160 if (hardware_acceleration_enabled) CFRelease(hardware_acceleration_enabled);
161 #endif
162 return;
163 } catch (const runtime_error &e) {
164 vt_enc_error("VTSession not created because of error '%s'", e.what());
165 if (_session) {
166 CFRelease(_session);
167 _session = nullptr;
168 }
169 }
170 }
171
172 void VideoToolboxEncoder::stop() {
173 if (_session == nullptr) return;
174 vt_enc_message("destroying the encoding session");
175 VTCompressionSessionInvalidate(_session);
176 CFRelease(_session);
177 _session = nullptr;
178 }
179
180 void VideoToolboxEncoder::feed(mblk_t *rawData, uint64_t time, bool requestIFrame) {
181 YuvBuf src_yuv_frame, dst_yuv_frame = {0};
182 CVPixelBufferRef pixbuf = nullptr;
183 const int pixbuf_fmt = kCVPixelFormatType_420YpCbCr8Planar;
184
185 if (!_session) {
186 freemsg(rawData);
187 return;
188 }
189
190 ms_yuv_buf_init_from_mblk(&src_yuv_frame, rawData);
191
192 CFMutableDictionaryRef pixbuf_attr = CFDictionaryCreateMutable(nullptr, 0, nullptr, nullptr);
193 CFNumberRef value = CFNumberCreate(nullptr, kCFNumberIntType, &pixbuf_fmt);
194 CFDictionarySetValue(pixbuf_attr, kCVPixelBufferPixelFormatTypeKey, value);
195 CVPixelBufferCreate(nullptr, _vsize.width, _vsize.height, kCVPixelFormatType_420YpCbCr8Planar, pixbuf_attr,
196 &pixbuf);
197 CFRelease(pixbuf_attr);
198
199 CVPixelBufferLockBaseAddress(pixbuf, 0);
200 dst_yuv_frame.w = (int)CVPixelBufferGetWidth(pixbuf);
201 dst_yuv_frame.h = (int)CVPixelBufferGetHeight(pixbuf);
202 for (int i = 0; i < 3; i++) {
203 dst_yuv_frame.planes[i] = static_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(pixbuf, i));
204 dst_yuv_frame.strides[i] = (int)CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i);
205 }
206 ms_yuv_buf_copy(src_yuv_frame.planes, src_yuv_frame.strides, dst_yuv_frame.planes, dst_yuv_frame.strides,
207 (MSVideoSize){dst_yuv_frame.w, dst_yuv_frame.h});
208 CVPixelBufferUnlockBaseAddress(pixbuf, 0);
209
210 CMTime p_time = CMTimeMake(time, 1000);
211 CFMutableDictionaryRef frameProperties = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, nullptr, nullptr);
212 CFDictionarySetValue(frameProperties, kVTEncodeFrameOptionKey_ForceKeyFrame,
213 requestIFrame ? kCFBooleanTrue : kCFBooleanFalse);
214
215 OSStatus err;
216 if ((err = VTCompressionSessionEncodeFrame(_session, pixbuf, p_time, kCMTimeInvalid, frameProperties, nullptr,
217 nullptr)) != noErr) {
218 vt_enc_error("could not pass a pixbuf to the encoder: %s", toString(err).c_str());
219 if (err == kVTInvalidSessionErr) {
220 stop();
221 start();
222 }
223 }
224 CFRelease(pixbuf);
225 CFRelease(frameProperties);
226 freemsg(rawData);
227 }
228
229 bool VideoToolboxEncoder::fetch(MSQueue *encodedData) {
230 ms_mutex_lock(&_mutex);
231 if (_encodedFrames.empty()) {
232 ms_mutex_unlock(&_mutex);
233 return false;
234 }
235 Frame &frame = _encodedFrames.front();
236 while (mblk_t *m = frame.get()) {
237 ms_queue_put(encodedData, m);
238 }
239 _encodedFrames.pop_front();
240 ms_mutex_unlock(&_mutex);
241 return true;
242 }
243
244 void VideoToolboxEncoder::applyFramerate() {
245 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &_framerate);
246 OSStatus status = VTSessionSetProperty(_session, kVTCompressionPropertyKey_ExpectedFrameRate, value);
247 CFRelease(value);
248 if (status != noErr) {
249 ostringstream msg;
250 msg << "error while setting kVTCompressionPropertyKey_ExpectedFrameRate: " << toString(status);
251 throw runtime_error(msg.str());
252 }
253 }
254
255 void VideoToolboxEncoder::applyBitrate() {
256 OSStatus status;
257
258 vt_enc_message("setting output bitrate to [%i] bits/s", _bitrate);
259 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &_bitrate);
260 status = VTSessionSetProperty(_session, kVTCompressionPropertyKey_AverageBitRate, value);
261 CFRelease(value);
262 if (status != noErr) {
263 ostringstream msg;
264 msg << "error while setting kVTCompressionPropertyKey_AverageBitRate: " << toString(status);
265 vt_enc_error("%s : %i bits/s", msg.str().c_str(), _bitrate);
266 throw runtime_error(msg.str());
267 }
268
269 int bytes_per_seconds = _bitrate / 8;
270 int dur = 1;
271 CFNumberRef bytes_value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &bytes_per_seconds);
272 CFNumberRef duration_value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &dur);
273 CFMutableArrayRef data_rate_limits = CFArrayCreateMutable(kCFAllocatorDefault, 2, &kCFTypeArrayCallBacks);
274 CFArrayAppendValue(data_rate_limits, bytes_value);
275 CFArrayAppendValue(data_rate_limits, duration_value);
276 status = VTSessionSetProperty(_session, kVTCompressionPropertyKey_DataRateLimits, data_rate_limits);
277 CFRelease(bytes_value);
278 CFRelease(duration_value);
279 CFRelease(data_rate_limits);
280 if (status != noErr) {
281 ms_error("VideoToolboxEncoder::applyBitrate(): kVTCompressionPropertyKey_DataRateLimits failed: %s",
282 toString(status).c_str());
283 /* This error is not fatal unlike for averageBitRate: do not throw exception which would result in VTSession not
284 * created.*/
285 }
286 }
287
288 void VideoToolboxEncoder::outputCb(void *outputCallbackRefCon,
289 BCTBX_UNUSED(void *sourceFrameRefCon),
290 OSStatus status,
291 BCTBX_UNUSED(VTEncodeInfoFlags infoFlags),
292 CMSampleBufferRef sampleBuffer) {
293 VideoToolboxEncoder *ctx = static_cast<VideoToolboxEncoder *>(outputCallbackRefCon);
294
295 try {
296 if (sampleBuffer == nullptr) throw runtime_error("no output buffer");
297 if (status != noErr) throw AppleOSError(status);
298
299 if (ctx->_session) {
300 Frame encodedFrame;
301 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(sampleBuffer);
302 const size_t frame_size = CMBlockBufferGetDataLength(block_buffer);
303 size_t read_size = 0;
304
305 while (read_size < frame_size) {
306 char *chunk;
307 size_t chunk_size;
308 OSStatus status = CMBlockBufferGetDataPointer(block_buffer, read_size, &chunk_size, NULL, &chunk);
309 if (status != kCMBlockBufferNoErr)
310 throw runtime_error(string("chunk reading failed: ") + toString(status));
311
312 H26xUtils::naluStreamToNalus(reinterpret_cast<uint8_t *>(chunk), chunk_size, encodedFrame.getQueue());
313 read_size += chunk_size;
314 }
315
316 bool isKeyFrame = false;
317 unique_ptr<H26xNaluHeader> header(H26xToolFactory::get(ctx->_mime).createNaluHeader());
318 for (const mblk_t *nalu = ms_queue_peek_first(encodedFrame.getQueue());
319 !ms_queue_end(encodedFrame.getQueue(), nalu); nalu = ms_queue_next(encodedFrame.getQueue(), nalu)) {
320 header->parse(nalu->b_rptr);
321 if (header->getAbsType().isKeyFramePart()) {
322 isKeyFrame = true;
323 break;
324 }
325 }
326
327 if (isKeyFrame) {
328 MSQueue parameterSets;
329 ms_queue_init(&parameterSets);
330 try {
331 ms_message("VideoToolboxEncoder: I-frame created");
332 unique_ptr<VideoToolboxUtilities> vtUtils(VideoToolboxUtilities::create(ctx->_mime));
333 vtUtils->getParameterSets(CMSampleBufferGetFormatDescription(sampleBuffer), &parameterSets);
334 encodedFrame.insert(&parameterSets);
335 } catch (const AppleOSError &e) {
336 ms_error("VideoToolboxEncoder: parameter sets generation failed: %s", e.what());
337 ms_queue_flush(&parameterSets);
338 }
339 }
340
341 ms_mutex_lock(&ctx->_mutex);
342 ctx->_encodedFrames.push_back(std::move(encodedFrame));
343 ms_mutex_unlock(&ctx->_mutex);
344 }
345 } catch (const runtime_error &e) {
346 ms_error("VideoToolboxEncoder: encoding error: %s", e.what());
347 } catch (const AppleOSError &e) {
348 ms_error("VideoToolboxEncoder: encoding error: %s", e.what());
349 }
350 }
351
352 } // namespace mediastreamer