Line data Source code
1 : /*
2 : * Copyright (C) 2004-2025 Savoir-faire Linux Inc.
3 : *
4 : * This program is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 3 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * This program is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "libav_deps.h" // MUST BE INCLUDED FIRST
19 : #include "media_decoder.h"
20 : #include "media_device.h"
21 : #include "media_buffer.h"
22 : #include "media_const.h"
23 : #include "media_io_handle.h"
24 : #include "audio/ringbuffer.h"
25 : #include "audio/resampler.h"
26 : #include "audio/ringbufferpool.h"
27 : #include "decoder_finder.h"
28 : #include "manager.h"
29 :
30 : #ifdef ENABLE_HWACCEL
31 : #include "video/accel.h"
32 : #endif
33 :
34 : #include "string_utils.h"
35 : #include "logger.h"
36 : #include "client/ring_signal.h"
37 :
38 : #include <iostream>
39 : #include <unistd.h>
40 : #include <thread> // hardware_concurrency
41 : #include <chrono>
42 : #include <algorithm>
43 :
44 : namespace jami {
45 :
46 : // maximum number of packets the jitter buffer can queue
47 : const unsigned jitterBufferMaxSize_ {1500};
48 : // maximum time a packet can be queued
49 : const constexpr auto jitterBufferMaxDelay_ = std::chrono::milliseconds(50);
50 : // maximum number of times accelerated decoding can fail in a row before falling back to software
51 : const constexpr unsigned MAX_ACCEL_FAILURES {5};
52 :
53 407 : MediaDemuxer::MediaDemuxer()
54 814 : : inputCtx_(avformat_alloc_context())
55 407 : , startTime_(AV_NOPTS_VALUE)
56 407 : {}
57 :
58 407 : MediaDemuxer::~MediaDemuxer()
59 : {
60 407 : if (inputCtx_)
61 347 : avformat_close_input(&inputCtx_);
62 407 : av_dict_free(&options_);
63 407 : }
64 :
65 : const char*
66 0 : MediaDemuxer::getStatusStr(Status status)
67 : {
68 0 : switch (status) {
69 0 : case Status::Success:
70 0 : return "Success";
71 0 : case Status::EndOfFile:
72 0 : return "End of file";
73 0 : case Status::ReadBufferOverflow:
74 0 : return "Read overflow";
75 0 : case Status::ReadError:
76 0 : return "Read error";
77 0 : case Status::FallBack:
78 0 : return "Fallback";
79 0 : case Status::RestartRequired:
80 0 : return "Restart required";
81 0 : default:
82 0 : return "Undefined";
83 : }
84 : }
85 :
86 : int
87 407 : MediaDemuxer::openInput(const DeviceParams& params)
88 : {
89 407 : inputParams_ = params;
90 407 : auto iformat = av_find_input_format(params.format.c_str());
91 :
92 407 : if (!iformat && !params.format.empty())
93 1 : JAMI_WARN("Unable to find format \"%s\"", params.format.c_str());
94 :
95 407 : std::string input;
96 :
97 407 : if (params.input == "pipewiregrab") {
98 : //
99 : // We rely on pipewiregrab for screen/window sharing on Wayland.
100 : // Because pipewiregrab is a "video source filter" (part of FFmpeg's libavfilter
101 : // library), its options must all be passed as part of the `input` string.
102 : //
103 0 : input = fmt::format("pipewiregrab=draw_mouse=1:fd={}:node={}", params.fd, params.node);
104 0 : JAMI_LOG("Attempting to open input {}", input);
105 : //
106 : // In all other cases, we use the `options_` AVDictionary to pass options to FFmpeg.
107 : //
108 : // NOTE: We rely on the "lavfi" virtual input device to read pipewiregrab's output
109 : // and create a corresponding stream (cf. the getDeviceParams function in
110 : // daemon/src/media/video/v4l2/video_device_impl.cpp). The `options_` dictionary
111 : // could be used to set lavfi's parameters if that was ever needed, but it isn't at
112 : // the moment. (Doc: https://ffmpeg.org/ffmpeg-devices.html#lavfi)
113 : //
114 : } else {
115 407 : if (params.width and params.height) {
116 0 : auto sizeStr = fmt::format("{}x{}", params.width, params.height);
117 0 : av_dict_set(&options_, "video_size", sizeStr.c_str(), 0);
118 0 : }
119 :
120 407 : if (params.framerate) {
121 : #ifdef _WIN32
122 : // On windows, framerate settings don't reduce to avrational values
123 : // that correspond to valid video device formats.
124 : // e.g. A the rational<double>(10000000, 333333) or 30.000030000
125 : // will be reduced by av_reduce to 999991/33333 or 30.00003000003
126 : // which cause the device opening routine to fail.
127 : // So we treat this imprecise reduction and adjust the value,
128 : // or let dshow choose the framerate, which is, unfortunately,
129 : // NOT the highest according to our experimentations.
130 : auto framerate {params.framerate.real()};
131 : framerate = params.framerate.numerator() / (params.framerate.denominator() + 0.5);
132 : if (params.framerate.denominator() != 4999998)
133 : av_dict_set(&options_, "framerate", jami::to_string(framerate).c_str(), 0);
134 : #else
135 1 : av_dict_set(&options_, "framerate", jami::to_string(params.framerate.real()).c_str(), 0);
136 : #endif
137 : }
138 :
139 407 : if (params.offset_x || params.offset_y) {
140 0 : av_dict_set(&options_, "offset_x", std::to_string(params.offset_x).c_str(), 0);
141 0 : av_dict_set(&options_, "offset_y", std::to_string(params.offset_y).c_str(), 0);
142 : }
143 407 : if (params.channel)
144 0 : av_dict_set(&options_, "channel", std::to_string(params.channel).c_str(), 0);
145 407 : av_dict_set(&options_, "loop", params.loop.c_str(), 0);
146 407 : av_dict_set(&options_, "sdp_flags", params.sdp_flags.c_str(), 0);
147 :
148 : // Set jitter buffer options
149 407 : av_dict_set(&options_, "reorder_queue_size", std::to_string(jitterBufferMaxSize_).c_str(), 0);
150 407 : auto us = std::chrono::duration_cast<std::chrono::microseconds>(jitterBufferMaxDelay_).count();
151 407 : av_dict_set(&options_, "max_delay", std::to_string(us).c_str(), 0);
152 :
153 407 : if (!params.pixel_format.empty()) {
154 0 : av_dict_set(&options_, "pixel_format", params.pixel_format.c_str(), 0);
155 : }
156 407 : if (!params.window_id.empty()) {
157 0 : av_dict_set(&options_, "window_id", params.window_id.c_str(), 0);
158 : }
159 407 : av_dict_set(&options_, "draw_mouse", "1", 0);
160 407 : av_dict_set(&options_, "is_area", std::to_string(params.is_area).c_str(), 0);
161 :
162 : #if defined(__APPLE__) && TARGET_OS_MAC
163 : input = params.name;
164 : #else
165 407 : input = params.input;
166 : #endif
167 :
168 1221 : JAMI_LOG("Attempting to open input {} with format {}, pixel format {}, size {}x{}, rate {}",
169 : input,
170 : params.format,
171 : params.pixel_format,
172 : params.width,
173 : params.height,
174 : params.framerate.real());
175 : }
176 :
177 : // Ask FFmpeg to open the input using the options set above
178 407 : if (params.disable_dts_probe_delay && params.format == "sdp") {
179 145 : av_opt_set_int(inputCtx_, "max_ts_probe", 0, AV_OPT_SEARCH_CHILDREN);
180 145 : av_opt_set_int(inputCtx_, "fpsprobesize", 0, AV_OPT_SEARCH_CHILDREN);
181 : } else {
182 : // Don't waste time fetching framerate when finding stream info
183 262 : av_opt_set_int(inputCtx_, "fpsprobesize", 1, AV_OPT_SEARCH_CHILDREN);
184 : }
185 :
186 407 : int ret = avformat_open_input(&inputCtx_, input.c_str(), iformat, options_ ? &options_ : NULL);
187 :
188 407 : if (ret) {
189 180 : JAMI_ERROR("avformat_open_input failed: {}", libav_utils::getError(ret));
190 347 : } else if (inputCtx_->nb_streams > 0 && inputCtx_->streams[0]->codecpar) {
191 347 : baseWidth_ = inputCtx_->streams[0]->codecpar->width;
192 347 : baseHeight_ = inputCtx_->streams[0]->codecpar->height;
193 1041 : JAMI_LOG("Opened input Using format {:s} and resolution {:d}x{:d}",
194 : params.format, baseWidth_, baseHeight_);
195 : }
196 :
197 407 : return ret;
198 407 : }
199 :
200 : int64_t
201 10 : MediaDemuxer::getDuration() const
202 : {
203 10 : return inputCtx_->duration;
204 : }
205 :
206 : bool
207 9 : MediaDemuxer::seekFrame(int, int64_t timestamp)
208 : {
209 9 : if (av_seek_frame(inputCtx_, -1, timestamp, AVSEEK_FLAG_BACKWARD) >= 0) {
210 9 : clearFrames();
211 9 : return true;
212 : }
213 0 : return false;
214 : }
215 :
216 : void
217 347 : MediaDemuxer::findStreamInfo()
218 : {
219 347 : if (not streamInfoFound_) {
220 347 : inputCtx_->max_analyze_duration = 30 * AV_TIME_BASE;
221 : int err;
222 347 : if ((err = avformat_find_stream_info(inputCtx_, nullptr)) < 0) {
223 0 : JAMI_ERR() << "Unable to find stream info: " << libav_utils::getError(err);
224 : }
225 347 : streamInfoFound_ = true;
226 : }
227 347 : }
228 :
229 : int
230 358 : MediaDemuxer::selectStream(AVMediaType type)
231 : {
232 358 : auto sti = av_find_best_stream(inputCtx_, type, -1, -1, nullptr, 0);
233 358 : if (type == AVMEDIA_TYPE_VIDEO && sti >= 0) {
234 156 : auto st = inputCtx_->streams[sti];
235 156 : auto disposition = st->disposition;
236 156 : if (disposition & AV_DISPOSITION_ATTACHED_PIC) {
237 1 : JAMI_DBG("Skipping attached picture stream");
238 1 : sti = -1;
239 : }
240 : }
241 358 : return sti;
242 : }
243 :
244 : void
245 355 : MediaDemuxer::setInterruptCallback(int (*cb)(void*), void* opaque)
246 : {
247 355 : if (cb) {
248 355 : inputCtx_->interrupt_callback.callback = cb;
249 355 : inputCtx_->interrupt_callback.opaque = opaque;
250 : } else {
251 0 : inputCtx_->interrupt_callback.callback = 0;
252 : }
253 355 : }
254 : void
255 11 : MediaDemuxer::setNeedFrameCb(std::function<void()> cb)
256 : {
257 11 : needFrameCb_ = std::move(cb);
258 11 : }
259 :
260 : void
261 11 : MediaDemuxer::setFileFinishedCb(std::function<void(bool)> cb)
262 : {
263 11 : fileFinishedCb_ = std::move(cb);
264 11 : }
265 :
266 : void
267 9 : MediaDemuxer::clearFrames()
268 : {
269 : {
270 9 : std::lock_guard lk {videoBufferMutex_};
271 9 : while (!videoBuffer_.empty()) {
272 0 : videoBuffer_.pop();
273 : }
274 9 : }
275 : {
276 9 : std::lock_guard lk {audioBufferMutex_};
277 9 : while (!audioBuffer_.empty()) {
278 0 : audioBuffer_.pop();
279 : }
280 9 : }
281 9 : }
282 :
283 : bool
284 0 : MediaDemuxer::emitFrame(bool isAudio)
285 : {
286 0 : if (isAudio) {
287 0 : return pushFrameFrom(audioBuffer_, isAudio, audioBufferMutex_);
288 : } else {
289 0 : return pushFrameFrom(videoBuffer_, isAudio, videoBufferMutex_);
290 : }
291 : }
292 :
293 : bool
294 0 : MediaDemuxer::pushFrameFrom(
295 : std::queue<std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>>& buffer,
296 : bool isAudio,
297 : std::mutex& mutex)
298 : {
299 0 : std::unique_lock lock(mutex);
300 0 : if (buffer.empty()) {
301 0 : if (currentState_ == MediaDemuxer::CurrentState::Finished) {
302 0 : fileFinishedCb_(isAudio);
303 : } else {
304 0 : needFrameCb_();
305 : }
306 0 : return false;
307 : }
308 0 : auto packet = std::move(buffer.front());
309 0 : if (!packet) {
310 0 : return false;
311 : }
312 0 : auto streamIndex = packet->stream_index;
313 0 : if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) {
314 0 : return false;
315 : }
316 0 : if (auto& cb = streams_[streamIndex]) {
317 0 : buffer.pop();
318 0 : lock.unlock();
319 0 : cb(*packet.get());
320 : }
321 0 : return true;
322 0 : }
323 :
324 : MediaDemuxer::Status
325 91886983 : MediaDemuxer::demuxe()
326 : {
327 : auto packet = std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>(av_packet_alloc(),
328 91886983 : [](AVPacket* p) {
329 91886983 : if (p)
330 91886983 : av_packet_free(
331 : &p);
332 91886983 : });
333 :
334 91886983 : int ret = av_read_frame(inputCtx_, packet.get());
335 91886983 : if (ret == AVERROR(EAGAIN)) {
336 0 : return Status::Success;
337 91886983 : } else if (ret == AVERROR_EOF) {
338 91886228 : return Status::EndOfFile;
339 755 : } else if (ret < 0) {
340 0 : JAMI_ERR("Unable to read frame: %s\n", libav_utils::getError(ret).c_str());
341 0 : return Status::ReadError;
342 : }
343 :
344 755 : auto streamIndex = packet->stream_index;
345 755 : if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) {
346 0 : return Status::Success;
347 : }
348 :
349 755 : AVStream* stream = inputCtx_->streams[streamIndex];
350 755 : if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
351 250 : std::lock_guard lk {videoBufferMutex_};
352 250 : videoBuffer_.push(std::move(packet));
353 250 : if (videoBuffer_.size() >= 90) {
354 0 : return Status::ReadBufferOverflow;
355 : }
356 250 : } else {
357 505 : std::lock_guard lk {audioBufferMutex_};
358 505 : audioBuffer_.push(std::move(packet));
359 505 : if (audioBuffer_.size() >= 300) {
360 0 : return Status::ReadBufferOverflow;
361 : }
362 505 : }
363 755 : return Status::Success;
364 91886983 : }
365 :
366 : void
367 670 : MediaDemuxer::setIOContext(MediaIOHandle* ioctx)
368 : {
369 670 : inputCtx_->pb = ioctx->getContext();
370 670 : }
371 :
372 : MediaDemuxer::Status
373 5932 : MediaDemuxer::decode()
374 : {
375 5932 : if (inputParams_.format == "x11grab" || inputParams_.format == "dxgigrab") {
376 0 : auto ret = inputCtx_->iformat->read_header(inputCtx_);
377 0 : if (ret == AVERROR_EXTERNAL) {
378 0 : JAMI_ERR("Unable to read frame: %s\n", libav_utils::getError(ret).c_str());
379 0 : return Status::ReadError;
380 : }
381 0 : auto codecpar = inputCtx_->streams[0]->codecpar;
382 0 : if (baseHeight_ != codecpar->height || baseWidth_ != codecpar->width) {
383 0 : baseHeight_ = codecpar->height;
384 0 : baseWidth_ = codecpar->width;
385 0 : inputParams_.height = ((baseHeight_ >> 3) << 3);
386 0 : inputParams_.width = ((baseWidth_ >> 3) << 3);
387 0 : return Status::RestartRequired;
388 : }
389 : }
390 :
391 5932 : libjami::PacketBuffer packet(av_packet_alloc());
392 5932 : int ret = av_read_frame(inputCtx_, packet.get());
393 5932 : if (ret == AVERROR(EAGAIN)) {
394 : /*no data available. Calculate time until next frame.
395 : We do not use the emulated frame mechanism from the decoder because it will affect all
396 : platforms. With the current implementation, the demuxer will be waiting just in case when
397 : av_read_frame returns EAGAIN. For some platforms, av_read_frame is blocking and it will
398 : never happen.
399 : */
400 0 : if (inputParams_.framerate.numerator() == 0)
401 0 : return Status::Success;
402 0 : rational<double> frameTime = 1e6 / inputParams_.framerate;
403 0 : int64_t timeToSleep = lastReadPacketTime_ - av_gettime_relative()
404 0 : + frameTime.real<int64_t>();
405 0 : if (timeToSleep <= 0) {
406 0 : return Status::Success;
407 : }
408 0 : std::this_thread::sleep_for(std::chrono::microseconds(timeToSleep));
409 0 : return Status::Success;
410 5932 : } else if (ret == AVERROR_EOF) {
411 121 : return Status::EndOfFile;
412 5811 : } else if (ret == AVERROR(EACCES)) {
413 0 : return Status::RestartRequired;
414 5811 : } else if (ret < 0) {
415 0 : auto media = inputCtx_->streams[0]->codecpar->codec_type;
416 0 : const auto type = media == AVMediaType::AVMEDIA_TYPE_AUDIO
417 0 : ? "AUDIO"
418 0 : : (media == AVMediaType::AVMEDIA_TYPE_VIDEO ? "VIDEO" : "UNSUPPORTED");
419 0 : JAMI_ERR("Unable to read [%s] frame: %s\n", type, libav_utils::getError(ret).c_str());
420 0 : return Status::ReadError;
421 : }
422 :
423 5811 : auto streamIndex = packet->stream_index;
424 5811 : if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) {
425 0 : return Status::Success;
426 : }
427 :
428 5811 : lastReadPacketTime_ = av_gettime_relative();
429 :
430 5811 : auto& cb = streams_[streamIndex];
431 5811 : if (cb) {
432 5811 : DecodeStatus ret = cb(*packet.get());
433 5811 : if (ret == DecodeStatus::FallBack)
434 0 : return Status::FallBack;
435 : }
436 5811 : return Status::Success;
437 5932 : }
438 :
439 0 : MediaDecoder::MediaDecoder(const std::shared_ptr<MediaDemuxer>& demuxer, int index)
440 0 : : demuxer_(demuxer)
441 0 : , avStream_(demuxer->getStream(index))
442 : {
443 0 : demuxer->setStreamCallback(index, [this](AVPacket& packet) { return decode(packet); });
444 0 : setupStream();
445 0 : }
446 :
447 20 : MediaDecoder::MediaDecoder(const std::shared_ptr<MediaDemuxer>& demuxer,
448 : int index,
449 20 : MediaObserver observer)
450 20 : : demuxer_(demuxer)
451 20 : , avStream_(demuxer->getStream(index))
452 40 : , callback_(std::move(observer))
453 : {
454 20 : demuxer->setStreamCallback(index, [this](AVPacket& packet) { return decode(packet); });
455 20 : setupStream();
456 20 : }
457 :
458 : bool
459 0 : MediaDecoder::emitFrame(bool isAudio)
460 : {
461 0 : return demuxer_->emitFrame(isAudio);
462 : }
463 :
464 0 : MediaDecoder::MediaDecoder()
465 0 : : demuxer_(new MediaDemuxer)
466 0 : {}
467 :
468 396 : MediaDecoder::MediaDecoder(MediaObserver o)
469 396 : : demuxer_(new MediaDemuxer)
470 396 : , callback_(std::move(o))
471 396 : {}
472 :
473 416 : MediaDecoder::~MediaDecoder()
474 : {
475 : #ifdef ENABLE_HWACCEL
476 416 : if (decoderCtx_ && decoderCtx_->hw_device_ctx)
477 0 : av_buffer_unref(&decoderCtx_->hw_device_ctx);
478 : #endif
479 416 : if (decoderCtx_)
480 356 : avcodec_free_context(&decoderCtx_);
481 416 : }
482 :
483 : void
484 18 : MediaDecoder::flushBuffers()
485 : {
486 18 : avcodec_flush_buffers(decoderCtx_);
487 18 : }
488 :
489 : int
490 396 : MediaDecoder::openInput(const DeviceParams& p)
491 : {
492 396 : return demuxer_->openInput(p);
493 : }
494 :
495 : void
496 355 : MediaDecoder::setInterruptCallback(int (*cb)(void*), void* opaque)
497 : {
498 355 : demuxer_->setInterruptCallback(cb, opaque);
499 355 : }
500 :
501 : void
502 670 : MediaDecoder::setIOContext(MediaIOHandle* ioctx)
503 : {
504 670 : demuxer_->setIOContext(ioctx);
505 670 : }
506 :
507 : int
508 336 : MediaDecoder::setup(AVMediaType type)
509 : {
510 336 : demuxer_->findStreamInfo();
511 336 : auto stream = demuxer_->selectStream(type);
512 336 : if (stream < 0) {
513 0 : JAMI_ERR("No stream found for type %i", static_cast<int>(type));
514 0 : return -1;
515 : }
516 336 : avStream_ = demuxer_->getStream(stream);
517 336 : if (avStream_ == nullptr) {
518 0 : JAMI_ERR("No stream found at index %i", stream);
519 0 : return -1;
520 : }
521 6147 : demuxer_->setStreamCallback(stream, [this](AVPacket& packet) { return decode(packet); });
522 336 : return setupStream();
523 : }
524 :
525 : int
526 356 : MediaDecoder::setupStream()
527 : {
528 356 : int ret = 0;
529 356 : avcodec_free_context(&decoderCtx_);
530 :
531 356 : if (prepareDecoderContext() < 0)
532 0 : return -1; // failed
533 :
534 : #ifdef ENABLE_HWACCEL
535 : // if there was a fallback to software decoding, do not enable accel
536 : // it has been disabled already by the video_receive_thread/video_input
537 356 : enableAccel_ &= Manager::instance().videoPreferences.getDecodingAccelerated();
538 :
539 356 : if (enableAccel_ and not fallback_) {
540 356 : auto APIs = video::HardwareAccel::getCompatibleAccel(decoderCtx_->codec_id,
541 356 : decoderCtx_->width,
542 356 : decoderCtx_->height,
543 356 : CODEC_DECODER);
544 801 : for (const auto& it : APIs) {
545 445 : accel_ = std::make_unique<video::HardwareAccel>(it); // save accel
546 445 : auto ret = accel_->initAPI(false, nullptr);
547 445 : if (ret < 0) {
548 445 : accel_.reset();
549 445 : continue;
550 : }
551 0 : if (prepareDecoderContext() < 0)
552 0 : return -1; // failed
553 0 : accel_->setDetails(decoderCtx_);
554 0 : decoderCtx_->opaque = accel_.get();
555 0 : decoderCtx_->pix_fmt = accel_->getFormat();
556 0 : if (avcodec_open2(decoderCtx_, inputDecoder_, &options_) < 0) {
557 : // Failed to open codec
558 0 : JAMI_WARN("Fail to open hardware decoder for %s with %s",
559 : avcodec_get_name(decoderCtx_->codec_id),
560 : it.getName().c_str());
561 0 : avcodec_free_context(&decoderCtx_);
562 0 : decoderCtx_ = nullptr;
563 0 : accel_.reset();
564 0 : continue;
565 : } else {
566 : // Succeed to open codec
567 0 : JAMI_WARN("Using hardware decoding for %s with %s",
568 : avcodec_get_name(decoderCtx_->codec_id),
569 : it.getName().c_str());
570 0 : break;
571 : }
572 : }
573 356 : }
574 : #endif
575 :
576 1068 : JAMI_LOG("Using {} ({}) decoder for {}",
577 : inputDecoder_->long_name,
578 : inputDecoder_->name,
579 : av_get_media_type_string(avStream_->codecpar->codec_type));
580 356 : decoderCtx_->thread_count = std::max(1u, std::min(8u, std::thread::hardware_concurrency() / 2));
581 356 : if (emulateRate_)
582 0 : JAMI_DBG() << "Using framerate emulation";
583 356 : startTime_ = av_gettime(); // used to set pts after decoding, and for rate emulation
584 :
585 : #ifdef ENABLE_HWACCEL
586 356 : if (!accel_) {
587 356 : JAMI_WARN("Not using hardware decoding for %s", avcodec_get_name(decoderCtx_->codec_id));
588 356 : ret = avcodec_open2(decoderCtx_, inputDecoder_, nullptr);
589 : }
590 : #else
591 : ret = avcodec_open2(decoderCtx_, inputDecoder_, nullptr);
592 : #endif
593 356 : if (ret < 0) {
594 0 : JAMI_ERR() << "Unable to open codec: " << libav_utils::getError(ret);
595 0 : return -1;
596 : }
597 :
598 356 : return 0;
599 : }
600 :
601 : int
602 356 : MediaDecoder::prepareDecoderContext()
603 : {
604 356 : inputDecoder_ = findDecoder(avStream_->codecpar->codec_id);
605 356 : if (!inputDecoder_) {
606 0 : JAMI_ERROR("Unsupported codec");
607 0 : return -1;
608 : }
609 :
610 356 : decoderCtx_ = avcodec_alloc_context3(inputDecoder_);
611 356 : if (!decoderCtx_) {
612 0 : JAMI_ERROR("Failed to create decoder context");
613 0 : return -1;
614 : }
615 356 : avcodec_parameters_to_context(decoderCtx_, avStream_->codecpar);
616 356 : width_ = decoderCtx_->width;
617 356 : height_ = decoderCtx_->height;
618 356 : decoderCtx_->framerate = avStream_->avg_frame_rate;
619 356 : if (avStream_->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
620 155 : if (decoderCtx_->framerate.num == 0 || decoderCtx_->framerate.den == 0)
621 145 : decoderCtx_->framerate = inputParams_.framerate;
622 155 : if (decoderCtx_->framerate.num == 0 || decoderCtx_->framerate.den == 0)
623 145 : decoderCtx_->framerate = {30, 1};
624 : }
625 201 : else if (avStream_->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
626 201 : if (decoderCtx_->codec_id == AV_CODEC_ID_OPUS) {
627 199 : av_opt_set_int(decoderCtx_, "decode_fec", fecEnabled_ ? 1 : 0, AV_OPT_SEARCH_CHILDREN);
628 : }
629 201 : auto format = libav_utils::choose_sample_fmt_default(inputDecoder_, Manager::instance().getRingBufferPool().getInternalAudioFormat().sampleFormat);
630 201 : decoderCtx_->sample_fmt = format;
631 201 : decoderCtx_->request_sample_fmt = format;
632 : }
633 356 : return 0;
634 : }
635 :
636 : void
637 56 : MediaDecoder::updateStartTime(int64_t startTime)
638 : {
639 56 : startTime_ = startTime;
640 56 : }
641 :
642 : DecodeStatus
643 5811 : MediaDecoder::decode(AVPacket& packet)
644 : {
645 5811 : int frameFinished = 0;
646 5811 : auto ret = avcodec_send_packet(decoderCtx_, &packet);
647 : // TODO: Investigate avcodec_send_packet returning AVERROR_INVALIDDATA.
648 : // * Bug Windows documented here: git.jami.net/savoirfairelinux/jami-daemon/-/issues/1116
649 : // where avcodec_send_packet returns AVERROR_INVALIDDATA when the size information in the
650 : // packet is incorrect. Falling back onto sw decoding in this causes a segfault.
651 : // * A second problem occurs on some Windows devices with intel CPUs in which hardware
652 : // decoding fails with AVERROR_INVALIDDATA when using H.264. However, in this scenario,
653 : // falling back to software decoding works fine.
654 : // We need to figure out why this behavior occurs and how to discriminate between the two.
655 5811 : if (ret < 0 && ret != AVERROR(EAGAIN)) {
656 : #ifdef ENABLE_HWACCEL
657 0 : if (accel_) {
658 0 : JAMI_WARN("Decoding error falling back to software");
659 0 : fallback_ = true;
660 0 : accel_.reset();
661 0 : avcodec_flush_buffers(decoderCtx_);
662 0 : setupStream();
663 0 : return DecodeStatus::FallBack;
664 : }
665 : #endif
666 0 : avcodec_flush_buffers(decoderCtx_);
667 0 : return ret == AVERROR_EOF ? DecodeStatus::Success : DecodeStatus::DecodeError;
668 : }
669 :
670 : #ifdef ENABLE_VIDEO
671 5811 : auto f = (inputDecoder_->type == AVMEDIA_TYPE_VIDEO)
672 5807 : ? std::static_pointer_cast<MediaFrame>(std::make_shared<VideoFrame>())
673 11622 : : std::static_pointer_cast<MediaFrame>(std::make_shared<AudioFrame>());
674 : #else
675 : auto f = std::static_pointer_cast<MediaFrame>(std::make_shared<AudioFrame>());
676 : #endif
677 5811 : auto frame = f->pointer();
678 5811 : ret = avcodec_receive_frame(decoderCtx_, frame);
679 : // time_base is not set in AVCodecContext for decoding
680 : // fail to set it causes pts to be incorrectly computed down in the function
681 5811 : if (inputDecoder_->type == AVMEDIA_TYPE_VIDEO) {
682 5807 : decoderCtx_->time_base.num = decoderCtx_->framerate.den;
683 5807 : decoderCtx_->time_base.den = decoderCtx_->framerate.num;
684 : } else {
685 4 : decoderCtx_->time_base.num = 1;
686 4 : decoderCtx_->time_base.den = decoderCtx_->sample_rate;
687 : }
688 5811 : frame->time_base = decoderCtx_->time_base;
689 5811 : if (resolutionChangedCallback_) {
690 5807 : if (decoderCtx_->width != width_ or decoderCtx_->height != height_) {
691 0 : JAMI_DBG("Resolution changed from %dx%d to %dx%d",
692 : width_,
693 : height_,
694 : decoderCtx_->width,
695 : decoderCtx_->height);
696 0 : width_ = decoderCtx_->width;
697 0 : height_ = decoderCtx_->height;
698 0 : resolutionChangedCallback_(width_, height_);
699 : }
700 : }
701 5811 : if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
702 0 : return DecodeStatus::DecodeError;
703 : }
704 5811 : if (ret >= 0)
705 5546 : frameFinished = 1;
706 :
707 5811 : if (frameFinished) {
708 5546 : if (inputDecoder_->type == AVMEDIA_TYPE_VIDEO)
709 5542 : frame->format = (AVPixelFormat) correctPixFmt(frame->format);
710 5546 : auto packetTimestamp = frame->pts; // in stream time base
711 5546 : frame->pts = av_rescale_q_rnd(av_gettime() - startTime_,
712 : {1, AV_TIME_BASE},
713 5546 : decoderCtx_->time_base,
714 : static_cast<AVRounding>(AV_ROUND_NEAR_INF
715 : | AV_ROUND_PASS_MINMAX));
716 5546 : lastTimestamp_ = frame->pts;
717 5546 : if (emulateRate_ and packetTimestamp != AV_NOPTS_VALUE) {
718 0 : auto startTime = avStream_->start_time == AV_NOPTS_VALUE ? 0 : avStream_->start_time;
719 0 : rational<double> frame_time = rational<double>(getTimeBase())
720 0 : * rational<double>(packetTimestamp - startTime);
721 0 : auto target_relative = static_cast<std::int64_t>(frame_time.real() * 1e6);
722 0 : auto target_absolute = startTime_ + target_relative;
723 0 : if (target_relative < seekTime_) {
724 0 : return DecodeStatus::Success;
725 : }
726 : // required frame found. Reset seek time
727 0 : if (target_relative >= seekTime_) {
728 0 : resetSeekTime();
729 : }
730 0 : auto now = av_gettime();
731 0 : if (target_absolute > now) {
732 0 : std::this_thread::sleep_for(std::chrono::microseconds(target_absolute - now));
733 : }
734 : }
735 :
736 5546 : if (callback_)
737 5546 : callback_(std::move(f));
738 :
739 5546 : if (contextCallback_ && firstDecode_.load()) {
740 32 : firstDecode_.exchange(false);
741 32 : contextCallback_();
742 : }
743 5546 : return DecodeStatus::FrameFinished;
744 : }
745 265 : return DecodeStatus::Success;
746 5811 : }
747 :
748 : void
749 18 : MediaDecoder::setSeekTime(int64_t time)
750 : {
751 18 : seekTime_ = time;
752 18 : }
753 :
754 : MediaDemuxer::Status
755 5932 : MediaDecoder::decode()
756 : {
757 5932 : auto ret = demuxer_->decode();
758 5932 : if (ret == MediaDemuxer::Status::RestartRequired) {
759 0 : avcodec_flush_buffers(decoderCtx_);
760 0 : setupStream();
761 0 : ret = MediaDemuxer::Status::EndOfFile;
762 : }
763 5932 : return ret;
764 : }
765 :
766 : #ifdef ENABLE_VIDEO
767 : #ifdef ENABLE_HWACCEL
768 : void
769 0 : MediaDecoder::enableAccel(bool enableAccel)
770 : {
771 0 : enableAccel_ = enableAccel;
772 0 : emitSignal<libjami::ConfigurationSignal::HardwareDecodingChanged>(enableAccel_);
773 0 : if (!enableAccel) {
774 0 : accel_.reset();
775 0 : if (decoderCtx_)
776 0 : decoderCtx_->opaque = nullptr;
777 : }
778 0 : }
779 : #endif
780 :
781 : DecodeStatus
782 0 : MediaDecoder::flush()
783 : {
784 : AVPacket inpacket;
785 0 : av_init_packet(&inpacket);
786 :
787 0 : int frameFinished = 0;
788 0 : int ret = 0;
789 0 : ret = avcodec_send_packet(decoderCtx_, &inpacket);
790 0 : if (ret < 0 && ret != AVERROR(EAGAIN))
791 0 : return ret == AVERROR_EOF ? DecodeStatus::Success : DecodeStatus::DecodeError;
792 :
793 0 : auto result = std::make_shared<MediaFrame>();
794 0 : ret = avcodec_receive_frame(decoderCtx_, result->pointer());
795 0 : if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
796 0 : return DecodeStatus::DecodeError;
797 0 : if (ret >= 0)
798 0 : frameFinished = 1;
799 :
800 0 : if (frameFinished) {
801 0 : av_packet_unref(&inpacket);
802 0 : if (callback_)
803 0 : callback_(std::move(result));
804 0 : return DecodeStatus::FrameFinished;
805 : }
806 :
807 0 : return DecodeStatus::Success;
808 0 : }
809 : #endif // ENABLE_VIDEO
810 :
811 : int
812 165 : MediaDecoder::getWidth() const
813 : {
814 165 : return decoderCtx_ ? decoderCtx_->width : 0;
815 : }
816 :
817 : int
818 165 : MediaDecoder::getHeight() const
819 : {
820 165 : return decoderCtx_ ? decoderCtx_->height : 0;
821 : }
822 :
823 : std::string
824 0 : MediaDecoder::getDecoderName() const
825 : {
826 0 : return decoderCtx_ ? decoderCtx_->codec->name : "";
827 : }
828 :
829 : rational<double>
830 10 : MediaDecoder::getFps() const
831 : {
832 10 : return {(double) avStream_->avg_frame_rate.num, (double) avStream_->avg_frame_rate.den};
833 : }
834 :
835 : rational<unsigned>
836 0 : MediaDecoder::getTimeBase() const
837 : {
838 0 : return {(unsigned) avStream_->time_base.num, (unsigned) avStream_->time_base.den};
839 : }
840 :
841 : AVPixelFormat
842 10 : MediaDecoder::getPixelFormat() const
843 : {
844 10 : return decoderCtx_->pix_fmt;
845 : }
846 :
847 : int
848 5542 : MediaDecoder::correctPixFmt(int input_pix_fmt)
849 : {
850 : // https://ffmpeg.org/pipermail/ffmpeg-user/2014-February/020152.html
851 : int pix_fmt;
852 5542 : switch (input_pix_fmt) {
853 0 : case AV_PIX_FMT_YUVJ420P:
854 0 : pix_fmt = AV_PIX_FMT_YUV420P;
855 0 : break;
856 0 : case AV_PIX_FMT_YUVJ422P:
857 0 : pix_fmt = AV_PIX_FMT_YUV422P;
858 0 : break;
859 0 : case AV_PIX_FMT_YUVJ444P:
860 0 : pix_fmt = AV_PIX_FMT_YUV444P;
861 0 : break;
862 0 : case AV_PIX_FMT_YUVJ440P:
863 0 : pix_fmt = AV_PIX_FMT_YUV440P;
864 0 : break;
865 5542 : default:
866 5542 : pix_fmt = input_pix_fmt;
867 5542 : break;
868 : }
869 5542 : return pix_fmt;
870 : }
871 :
872 : MediaStream
873 192 : MediaDecoder::getStream(std::string name) const
874 : {
875 192 : if (!decoderCtx_) {
876 98 : JAMI_WARN("No decoder context");
877 98 : return {};
878 : }
879 94 : auto ms = MediaStream(name, decoderCtx_, lastTimestamp_);
880 : #ifdef ENABLE_HWACCEL
881 : // accel_ is null if not using accelerated codecs
882 94 : if (accel_)
883 3 : ms.format = accel_->getSoftwareFormat();
884 : #endif
885 94 : return ms;
886 94 : }
887 :
888 : } // namespace jami
|