Debian Codegraph @

src/videofilters/h26x/videotoolbox-decoder.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 "videotoolbox-utils.h"
22
23 #include "videotoolbox-decoder.h"
24
25 #define vt_dec_log(level, fmt, ...) ms_##level("VideoToolboxDecoder: " fmt, ##__VA_ARGS__)
26 #define vt_dec_message(fmt, ...) vt_dec_log(message, fmt, ##__VA_ARGS__)
27 #define vt_dec_warning(fmt, ...) vt_dec_log(warning, fmt, ##__VA_ARGS__)
28 #define vt_dec_error(fmt, ...) vt_dec_log(error, fmt, ##__VA_ARGS__)
29 #define vt_dec_debug(fmt, ...) vt_dec_log(debug, fmt, ##__VA_ARGS__)
30
31 using namespace std;
32
33 namespace mediastreamer {
34
35 VideoToolboxDecoder::VideoToolboxDecoder(const string &mime) : H26xDecoder(mime) {
36 _pixbufAllocator = ms_yuv_buf_allocator_new();
37 const H26xToolFactory &factory = H26xToolFactory::get(mime);
38 _psStore.reset(factory.createParameterSetsStore());
39 _naluHeader.reset(factory.createNaluHeader());
40 }
41
42 VideoToolboxDecoder::~VideoToolboxDecoder() {
43 if (_session) destroyDecoder();
44 ms_yuv_buf_allocator_free(_pixbufAllocator);
45 }
46
47 bool VideoToolboxDecoder::feed(MSQueue *encodedFrame, uint64_t timestamp) {
48 try {
49 _psStore->extractAllPs(encodedFrame);
50 if (_psStore->hasNewParameters()) {
51 _psStore->acknowlege();
52 if (_session) destroyDecoder();
53 }
54 if (ms_queue_empty(encodedFrame)) return true;
55 if (!_psStore->psGatheringCompleted()) throw runtime_error("need more parameter sets");
56 if (_session == nullptr) createDecoder();
57 if (_freeze) {
58 for (const mblk_t *nalu = ms_queue_peek_first(encodedFrame); !ms_queue_end(encodedFrame, nalu);
59 nalu = ms_queue_next(encodedFrame, nalu)) {
60 _naluHeader->parse(nalu->b_rptr);
61 if (_naluHeader->getAbsType().isKeyFramePart()) {
62 _freeze = false;
63 break;
64 }
65 }
66 }
67 if (!_freeze) {
68 decodeFrame(encodedFrame, timestamp);
69 return true;
70 }
71 return false; /* We can't decode without a new key rame, returning false will trigger the sending of a PLI */
72 } catch (const runtime_error &e) {
73 ms_error("VideoToolboxDecoder: %s", e.what());
74 ms_error("VideoToolboxDecoder: feeding failed");
75 if (typeid(e) == typeid(InvalidSessionError)) {
76 destroyDecoder();
77 }
78 return false;
79 }
80 }
81
82 VideoDecoder::Status VideoToolboxDecoder::fetch(mblk_t *&frame) {
83 std::lock_guard<std::mutex> lck(_mutex);
84 if (_queue.empty()) {
85 frame = nullptr;
86 return NoFrameAvailable;
87 } else {
88 frame = _queue.front().getData();
89 _queue.pop_front();
90 return frame ? NoError : DecodingFailure;
91 }
92 }
93
94 void VideoToolboxDecoder::createDecoder() {
95 OSStatus status;
96 VTDecompressionOutputCallbackRecord dec_cb = {outputCb, this};
97
98 vt_dec_message("creating a decoding session");
99
100 /*
101 * Since the decoder might be destroyed and recreated during the lifetime of the filter (for example
102 * when SPS/PPS change because of video size changed by remote encoder), we must reset the _destroying flag.
103 */
104 _mutex.lock();
105 if (_destroying) _destroying = false;
106 _mutex.unlock();
107 formatDescFromSpsPps();
108
109 CFMutableDictionaryRef decoder_params = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, NULL, NULL);
110 #if !TARGET_OS_IPHONE
111 CFDictionarySetValue(decoder_params, kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder,
112 kCFBooleanTrue);
113 #endif
114
115 CFMutableDictionaryRef pixel_parameters =
116 CFDictionaryCreateMutable(kCFAllocatorDefault, 1, NULL, &kCFTypeDictionaryValueCallBacks);
117 int32_t format = kCVPixelFormatType_420YpCbCr8Planar;
118 CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &format);
119 CFDictionarySetValue(pixel_parameters, kCVPixelBufferPixelFormatTypeKey, value);
120 CFRelease(value);
121
122 status = VTDecompressionSessionCreate(kCFAllocatorDefault, _formatDesc, decoder_params, pixel_parameters, &dec_cb,
123 &_session);
124 CFRelease(pixel_parameters);
125 CFRelease(decoder_params);
126 if (status != noErr) {
127 throw runtime_error("could not create the decoding context: " + toString(status));
128 } else {
129 #if !TARGET_OS_IPHONE
130 CFBooleanRef hardware_acceleration;
131 status = VTSessionCopyProperty(_session, kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder,
132 kCFAllocatorDefault, &hardware_acceleration);
133 if (status != noErr) {
134 vt_dec_error("could not read kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder property: %s",
135 toString(status).c_str());
136 } else {
137 if (hardware_acceleration != NULL && CFBooleanGetValue(hardware_acceleration)) {
138 vt_dec_message("hardware acceleration enabled");
139 } else {
140 vt_dec_warning("hardware acceleration not enabled");
141 }
142 }
143 if (hardware_acceleration != NULL) CFRelease(hardware_acceleration);
144 #endif
145
146 #if TARGET_OS_IPHONE // kVTDecompressionPropertyKey_RealTime is only available on MacOSX after 10.10 version
147 status = VTSessionSetProperty(_session, kVTDecompressionPropertyKey_RealTime, kCFBooleanTrue);
148 if (status != noErr) {
149 vt_dec_warning("could not be able to switch to real-time mode: %s", toString(status).c_str());
150 }
151 #endif
152 }
153 }
154
155 void VideoToolboxDecoder::destroyDecoder() {
156 vt_dec_message("destroying decoder");
157
158 // Notify the output callback that the decoder
159 // is in an instable state from now. This is necessary
160 // as the output callback may be called until the
161 // decoding session is completely destroyed.
162 _mutex.lock();
163 _destroying = true;
164 _mutex.unlock();
165
166 VTDecompressionSessionWaitForAsynchronousFrames(_session);
167 VTDecompressionSessionInvalidate(_session);
168 CFRelease(_session);
169 CFRelease(_formatDesc);
170 _session = nullptr;
171 _formatDesc = nullptr;
172 _destroying = false;
173 }
174
175 void VideoToolboxDecoder::decodeFrame(MSQueue *encodedFrame, uint64_t timestamp) {
176 CMBlockBufferRef stream = nullptr;
177 OSStatus status = CMBlockBufferCreateEmpty(kCFAllocatorDefault, 0, kCMBlockBufferAssureMemoryNowFlag, &stream);
178 if (status != kCMBlockBufferNoErr) {
179 throw runtime_error("failure while creating input buffer for decoder");
180 }
181 while (mblk_t *nalu = ms_queue_get(encodedFrame)) {
182 CMBlockBufferRef nalu_block;
183 size_t nalu_block_size = msgdsize(nalu) + _naluSizeLength;
184 uint32_t nalu_size = htonl(msgdsize(nalu));
185
186 CMBlockBufferCreateWithMemoryBlock(NULL, NULL, nalu_block_size, NULL, NULL, 0, nalu_block_size,
187 kCMBlockBufferAssureMemoryNowFlag, &nalu_block);
188 CMBlockBufferReplaceDataBytes(&nalu_size, nalu_block, 0, _naluSizeLength);
189 CMBlockBufferReplaceDataBytes(nalu->b_rptr, nalu_block, _naluSizeLength, msgdsize(nalu));
190 CMBlockBufferAppendBufferReference(stream, nalu_block, 0, nalu_block_size, 0);
191 CFRelease(nalu_block);
192 freemsg(nalu);
193 }
194 if (!CMBlockBufferIsEmpty(stream)) {
195 CMSampleBufferRef sample = NULL;
196 CMSampleTimingInfo timing_info;
197 timing_info.duration = kCMTimeInvalid;
198 timing_info.presentationTimeStamp = CMTimeMake(timestamp, 1000);
199 timing_info.decodeTimeStamp = CMTimeMake(timestamp, 1000);
200 CMSampleBufferCreate(kCFAllocatorDefault, stream, TRUE, NULL, NULL, _formatDesc, 1, 1, &timing_info, 0, NULL,
201 &sample);
202 status = VTDecompressionSessionDecodeFrame(
203 _session, sample, kVTDecodeFrame_EnableAsynchronousDecompression | kVTDecodeFrame_1xRealTimePlayback, NULL,
204 NULL);
205 CFRelease(sample);
206 if (status != noErr) {
207 CFRelease(stream);
208 if (status == kVTInvalidSessionErr) {
209 throw InvalidSessionError();
210 } else {
211 throw runtime_error("error while passing encoded frames to the decoder: " + toString(status));
212 }
213 }
214 }
215 CFRelease(stream);
216 }
217
218 void VideoToolboxDecoder::formatDescFromSpsPps() {
219 try {
220 unique_ptr<VideoToolboxUtilities> utils(VideoToolboxUtilities::create(_mime));
221 CMFormatDescriptionRef format_desc = utils->createFormatDescription(*_psStore);
222 CMVideoDimensions vsize = CMVideoFormatDescriptionGetDimensions(format_desc);
223 vt_dec_message("new video format %dx%d", int(vsize.width), int(vsize.height));
224 if (_formatDesc) CFRelease(_formatDesc);
225 _formatDesc = format_desc;
226 } catch (const AppleOSError &e) {
227 throw runtime_error(string("cannot create format description: ") + e.what());
228 }
229 }
230
231 void VideoToolboxDecoder::outputCb(void *decompressionOutputRefCon,
232 BCTBX_UNUSED(void *sourceFrameRefCon),
233 OSStatus status,
234 BCTBX_UNUSED(VTDecodeInfoFlags infoFlags),
235 CVImageBufferRef imageBuffer,
236 BCTBX_UNUSED(CMTime presentationTimeStamp),
237 BCTBX_UNUSED(CMTime presentationDuration)) {
238 auto ctx = static_cast<VideoToolboxDecoder *>(decompressionOutputRefCon);
239
240 std::lock_guard<std::mutex> lck(ctx->_mutex);
241
242 if (ctx->_destroying) {
243 return;
244 }
245
246 if (status != noErr || imageBuffer == nullptr) {
247 vt_dec_error("fail to decode one frame: %s", toString(status).c_str());
248 ctx->_queue.push_back(Frame());
249 return;
250 }
251
252 MSPicture pixbuf_desc;
253 CGSize vsize = CVImageBufferGetEncodedSize(imageBuffer);
254 mblk_t *pixbuf = ms_yuv_buf_allocator_get(ctx->_pixbufAllocator, &pixbuf_desc, int(vsize.width), int(vsize.height));
255
256 if (!pixbuf) {
257 ms_error("VideoToolboxDecoder: no more output frames.");
258 return;
259 }
260
261 uint8_t *src_planes[4] = {0};
262 int src_strides[4] = {0};
263 CVPixelBufferLockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly);
264 for (size_t i = 0; i < 3; i++) {
265 src_planes[i] = static_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(imageBuffer, i));
266 src_strides[i] = (int)CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, i);
267 }
268 ms_yuv_buf_copy(src_planes, src_strides, pixbuf_desc.planes, pixbuf_desc.strides,
269 {int(vsize.width), int(vsize.height)});
270 CVPixelBufferUnlockBaseAddress(imageBuffer, kCVPixelBufferLock_ReadOnly);
271
272 ctx->_queue.push_back(Frame(pixbuf));
273 }
274
275 } // namespace mediastreamer