Line data Source code
1 : /*
2 : * Copyright (C) 2004-2026 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_io_handle.h"
23 : #include "audio/ringbufferpool.h"
24 : #include "decoder_finder.h"
25 : #include "manager.h"
26 :
27 : #ifdef ENABLE_HWACCEL
28 : #include "video/accel.h"
29 : #endif
30 :
31 : #include "string_utils.h"
32 : #include "logger.h"
33 : #include "client/jami_signal.h"
34 :
35 : #include <unistd.h>
36 : #include <cstddef>
37 : #include <thread> // hardware_concurrency
38 : #include <chrono>
39 : #include <algorithm>
40 : #include <asio/steady_timer.hpp>
41 :
42 : namespace jami {
43 :
44 : // maximum number of packets the jitter buffer can queue
45 : const unsigned jitterBufferMaxSize_ {1500};
46 : // maximum time a packet can be queued
47 : const constexpr auto jitterBufferMaxDelay_ = std::chrono::milliseconds(50);
48 :
49 155 : MediaDemuxer::MediaDemuxer()
50 155 : : inputCtx_(avformat_alloc_context())
51 310 : , startTime_(AV_NOPTS_VALUE)
52 155 : {}
53 :
54 155 : MediaDemuxer::~MediaDemuxer()
55 : {
56 155 : if (streamInfoTimer_) {
57 0 : streamInfoTimer_->cancel();
58 0 : streamInfoTimer_.reset();
59 : }
60 155 : if (inputCtx_)
61 123 : avformat_close_input(&inputCtx_);
62 155 : av_dict_free(&options_);
63 155 : }
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 155 : MediaDemuxer::openInput(const DeviceParams& params)
88 : {
89 155 : inputParams_ = params;
90 155 : const auto* iformat = av_find_input_format(params.format.c_str());
91 :
92 155 : if (!iformat && !params.format.empty())
93 1 : JAMI_WARN("Unable to find format \"%s\"", params.format.c_str());
94 :
95 155 : std::string input;
96 :
97 155 : 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 155 : 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 155 : 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 155 : 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 155 : if (params.channel)
144 0 : av_dict_set(&options_, "channel", std::to_string(params.channel).c_str(), 0);
145 155 : av_dict_set(&options_, "loop", params.loop.c_str(), 0);
146 155 : av_dict_set(&options_, "sdp_flags", params.sdp_flags.c_str(), 0);
147 :
148 : // Set jitter buffer options
149 155 : av_dict_set(&options_, "reorder_queue_size", std::to_string(jitterBufferMaxSize_).c_str(), 0);
150 155 : auto us = std::chrono::duration_cast<std::chrono::microseconds>(jitterBufferMaxDelay_).count();
151 155 : av_dict_set(&options_, "max_delay", std::to_string(us).c_str(), 0);
152 :
153 155 : if (!params.pixel_format.empty()) {
154 0 : av_dict_set(&options_, "pixel_format", params.pixel_format.c_str(), 0);
155 : }
156 155 : if (!params.window_id.empty()) {
157 0 : av_dict_set(&options_, "window_id", params.window_id.c_str(), 0);
158 : }
159 155 : av_dict_set(&options_, "draw_mouse", "1", 0);
160 155 : av_dict_set(&options_, "is_area", std::to_string(params.is_area).c_str(), 0);
161 :
162 155 : input = params.input;
163 :
164 620 : JAMI_LOG("Attempting to open input {} with format {}, pixel format {}, size {}x{}, rate {}",
165 : input,
166 : params.format,
167 : params.pixel_format,
168 : params.width,
169 : params.height,
170 : params.framerate.real());
171 : }
172 :
173 : // Ask FFmpeg to open the input using the options set above
174 155 : if (params.disable_dts_probe_delay && params.format == "sdp") {
175 44 : av_opt_set_int(inputCtx_, "max_ts_probe", 0, AV_OPT_SEARCH_CHILDREN);
176 44 : av_opt_set_int(inputCtx_, "fpsprobesize", 0, AV_OPT_SEARCH_CHILDREN);
177 : } else {
178 : // Don't waste time fetching framerate when finding stream info
179 111 : av_opt_set_int(inputCtx_, "fpsprobesize", 1, AV_OPT_SEARCH_CHILDREN);
180 : }
181 :
182 155 : int ret = avformat_open_input(&inputCtx_, input.c_str(), iformat, options_ ? &options_ : NULL);
183 :
184 155 : if (ret) {
185 128 : JAMI_ERROR("avformat_open_input failed: {}", libav_utils::getError(ret));
186 123 : } else if (inputCtx_->nb_streams > 0 && inputCtx_->streams[0]->codecpar) {
187 123 : baseWidth_ = inputCtx_->streams[0]->codecpar->width;
188 123 : baseHeight_ = inputCtx_->streams[0]->codecpar->height;
189 492 : JAMI_LOG("Opened input using format {:s} and resolution {:d}x{:d}", params.format, baseWidth_, baseHeight_);
190 : }
191 :
192 155 : return ret;
193 155 : }
194 :
195 : int64_t
196 5 : MediaDemuxer::getDuration() const
197 : {
198 5 : return inputCtx_->duration;
199 : }
200 :
201 : bool
202 9 : MediaDemuxer::seekFrame(int, int64_t timestamp)
203 : {
204 9 : std::lock_guard lk(inputCtxMutex_);
205 9 : if (av_seek_frame(inputCtx_, -1, timestamp, AVSEEK_FLAG_BACKWARD) >= 0) {
206 9 : clearFrames();
207 9 : return true;
208 : }
209 0 : return false;
210 9 : }
211 :
212 : void
213 123 : MediaDemuxer::findStreamInfo(bool videoStream)
214 : {
215 123 : if (not streamInfoFound_) {
216 123 : inputCtx_->max_analyze_duration = 30l * AV_TIME_BASE;
217 123 : if (videoStream && keyFrameRequestCb_) {
218 44 : if (!streamInfoTimer_)
219 44 : streamInfoTimer_ = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext());
220 44 : streamInfoTimer_->expires_after(std::chrono::milliseconds(1500));
221 44 : streamInfoTimer_->async_wait([weak = weak_from_this()](const std::error_code& ec) {
222 44 : if (ec)
223 4 : return;
224 40 : if (auto self = weak.lock()) {
225 40 : if (!self->streamInfoFound_) {
226 160 : JAMI_LOG("findStreamInfo: 1500ms elapsed, requesting keyframe to aid probing");
227 40 : if (self->keyFrameRequestCb_)
228 40 : self->keyFrameRequestCb_();
229 : }
230 40 : }
231 : });
232 : }
233 :
234 123 : int err = avformat_find_stream_info(inputCtx_, nullptr);
235 123 : if (err < 0) {
236 0 : JAMI_ERROR("Unable to find stream info: {}", libav_utils::getError(err));
237 : }
238 123 : streamInfoFound_ = true;
239 123 : if (streamInfoTimer_) {
240 44 : streamInfoTimer_->cancel();
241 44 : streamInfoTimer_.reset();
242 : }
243 : }
244 123 : }
245 :
246 : int
247 129 : MediaDemuxer::selectStream(AVMediaType type)
248 : {
249 129 : auto sti = av_find_best_stream(inputCtx_, type, -1, -1, nullptr, 0);
250 129 : if (type == AVMEDIA_TYPE_VIDEO && sti >= 0) {
251 50 : auto* st = inputCtx_->streams[sti];
252 50 : auto disposition = st->disposition;
253 50 : if (disposition & AV_DISPOSITION_ATTACHED_PIC) {
254 1 : JAMI_DBG("Skipping attached picture stream");
255 1 : sti = -1;
256 : }
257 : }
258 129 : return sti;
259 : }
260 :
261 : void
262 126 : MediaDemuxer::setInterruptCallback(int (*cb)(void*), void* opaque)
263 : {
264 126 : if (cb) {
265 126 : inputCtx_->interrupt_callback.callback = cb;
266 126 : inputCtx_->interrupt_callback.opaque = opaque;
267 : } else {
268 0 : inputCtx_->interrupt_callback.callback = 0;
269 : }
270 126 : }
271 : void
272 6 : MediaDemuxer::setNeedFrameCb(std::function<void()> cb)
273 : {
274 6 : needFrameCb_ = std::move(cb);
275 6 : }
276 :
277 : void
278 6 : MediaDemuxer::setFileFinishedCb(std::function<void(bool)> cb)
279 : {
280 6 : fileFinishedCb_ = std::move(cb);
281 6 : }
282 :
283 : void
284 44 : MediaDemuxer::setKeyFrameRequestCb(std::function<void()> cb)
285 : {
286 44 : keyFrameRequestCb_ = std::move(cb);
287 44 : }
288 :
289 : void
290 9 : MediaDemuxer::clearFrames()
291 : {
292 : {
293 9 : std::lock_guard lk {videoBufferMutex_};
294 9 : while (!videoBuffer_.empty()) {
295 0 : videoBuffer_.pop();
296 : }
297 9 : }
298 : {
299 9 : std::lock_guard lk {audioBufferMutex_};
300 9 : while (!audioBuffer_.empty()) {
301 0 : audioBuffer_.pop();
302 : }
303 9 : }
304 9 : }
305 :
306 : bool
307 0 : MediaDemuxer::emitFrame(bool isAudio)
308 : {
309 0 : if (isAudio) {
310 0 : return pushFrameFrom(audioBuffer_, isAudio, audioBufferMutex_);
311 : } else {
312 0 : return pushFrameFrom(videoBuffer_, isAudio, videoBufferMutex_);
313 : }
314 : }
315 :
316 : bool
317 0 : MediaDemuxer::pushFrameFrom(std::queue<std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>>& buffer,
318 : bool isAudio,
319 : std::mutex& mutex)
320 : {
321 0 : std::unique_lock lock(mutex);
322 0 : if (buffer.empty()) {
323 0 : if (currentState_ == MediaDemuxer::CurrentState::Finished) {
324 0 : fileFinishedCb_(isAudio);
325 : } else {
326 0 : needFrameCb_();
327 : }
328 0 : return false;
329 : }
330 0 : auto packet = std::move(buffer.front());
331 0 : if (!packet) {
332 0 : return false;
333 : }
334 0 : auto streamIndex = packet->stream_index;
335 0 : if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) {
336 0 : return false;
337 : }
338 0 : if (auto& cb = streams_[streamIndex]) {
339 0 : buffer.pop();
340 0 : lock.unlock();
341 0 : cb(*packet.get());
342 : }
343 0 : return true;
344 0 : }
345 :
346 : MediaDemuxer::Status
347 0 : MediaDemuxer::demuxe()
348 : {
349 0 : auto packet = std::unique_ptr<AVPacket, std::function<void(AVPacket*)>>(av_packet_alloc(), [](AVPacket* p) {
350 0 : if (p)
351 0 : av_packet_free(&p);
352 0 : });
353 :
354 : bool isVideo;
355 : {
356 0 : std::lock_guard lk(inputCtxMutex_);
357 0 : int ret = av_read_frame(inputCtx_, packet.get());
358 0 : if (ret == AVERROR(EAGAIN)) {
359 0 : return Status::Success;
360 0 : } else if (ret == AVERROR_EOF) {
361 0 : return Status::EndOfFile;
362 0 : } else if (ret < 0) {
363 0 : JAMI_ERR("Unable to read frame: %s\n", libav_utils::getError(ret).c_str());
364 0 : return Status::ReadError;
365 : }
366 :
367 0 : auto streamIndex = packet->stream_index;
368 0 : if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) {
369 0 : return Status::Success;
370 : }
371 :
372 0 : isVideo = inputCtx_->streams[streamIndex]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
373 0 : }
374 :
375 0 : if (isVideo) {
376 0 : std::lock_guard lk {videoBufferMutex_};
377 0 : videoBuffer_.push(std::move(packet));
378 0 : if (videoBuffer_.size() >= 90) {
379 0 : return Status::ReadBufferOverflow;
380 : }
381 0 : } else {
382 0 : std::lock_guard lk {audioBufferMutex_};
383 0 : audioBuffer_.push(std::move(packet));
384 0 : if (audioBuffer_.size() >= 300) {
385 0 : return Status::ReadBufferOverflow;
386 : }
387 0 : }
388 0 : return Status::Success;
389 0 : }
390 :
391 : void
392 232 : MediaDemuxer::setIOContext(MediaIOHandle* ioctx)
393 : {
394 232 : inputCtx_->pb = ioctx->getContext();
395 232 : }
396 :
397 : MediaDemuxer::Status
398 52 : MediaDemuxer::decode()
399 : {
400 52 : if (inputParams_.format == "x11grab" || inputParams_.format == "dxgigrab") {
401 0 : auto ret = inputCtx_->iformat->read_header(inputCtx_);
402 0 : if (ret == AVERROR_EXTERNAL) {
403 0 : JAMI_ERR("Unable to read frame: %s\n", libav_utils::getError(ret).c_str());
404 0 : return Status::ReadError;
405 : }
406 0 : auto* codecpar = inputCtx_->streams[0]->codecpar;
407 0 : if (baseHeight_ != codecpar->height || baseWidth_ != codecpar->width) {
408 0 : baseHeight_ = codecpar->height;
409 0 : baseWidth_ = codecpar->width;
410 0 : inputParams_.height = ((baseHeight_ >> 3) << 3);
411 0 : inputParams_.width = ((baseWidth_ >> 3) << 3);
412 0 : return Status::RestartRequired;
413 : }
414 : }
415 :
416 52 : libjami::PacketBuffer packet(av_packet_alloc());
417 52 : int ret = av_read_frame(inputCtx_, packet.get());
418 52 : if (ret == AVERROR(EAGAIN)) {
419 : /*no data available. Calculate time until next frame.
420 : We do not use the emulated frame mechanism from the decoder because it will affect all
421 : platforms. With the current implementation, the demuxer will be waiting just in case when
422 : av_read_frame returns EAGAIN. For some platforms, av_read_frame is blocking and it will
423 : never happen.
424 : */
425 0 : if (inputParams_.framerate.numerator() == 0)
426 0 : return Status::Success;
427 0 : rational<double> frameTime = 1e6 / inputParams_.framerate;
428 0 : int64_t timeToSleep = lastReadPacketTime_ - av_gettime_relative() + frameTime.real<int64_t>();
429 0 : if (timeToSleep <= 0) {
430 0 : return Status::Success;
431 : }
432 0 : std::this_thread::sleep_for(std::chrono::microseconds(timeToSleep));
433 0 : return Status::Success;
434 52 : } else if (ret == AVERROR_EOF) {
435 44 : return Status::EndOfFile;
436 8 : } else if (ret == AVERROR(EACCES)) {
437 0 : return Status::RestartRequired;
438 8 : } else if (ret < 0) {
439 0 : auto media = inputCtx_->streams[0]->codecpar->codec_type;
440 0 : const auto* const type = media == AVMediaType::AVMEDIA_TYPE_AUDIO
441 0 : ? "AUDIO"
442 0 : : (media == AVMediaType::AVMEDIA_TYPE_VIDEO ? "VIDEO" : "UNSUPPORTED");
443 0 : JAMI_ERR("Unable to read [%s] frame: %s\n", type, libav_utils::getError(ret).c_str());
444 0 : return Status::ReadError;
445 : }
446 :
447 8 : auto streamIndex = packet->stream_index;
448 8 : if (static_cast<unsigned>(streamIndex) >= streams_.size() || streamIndex < 0) {
449 0 : return Status::Success;
450 : }
451 :
452 8 : lastReadPacketTime_ = av_gettime_relative();
453 :
454 8 : auto& cb = streams_[streamIndex];
455 8 : if (cb) {
456 8 : DecodeStatus ret = cb(*packet.get());
457 8 : if (ret == DecodeStatus::FallBack)
458 0 : return Status::FallBack;
459 : }
460 8 : return Status::Success;
461 52 : }
462 :
463 0 : MediaDecoder::MediaDecoder(const std::shared_ptr<MediaDemuxer>& demuxer, int index)
464 0 : : demuxer_(demuxer)
465 0 : , avStream_(demuxer->getStream(index))
466 : {
467 0 : demuxer->setStreamCallback(index, [this](AVPacket& packet) { return decode(packet); });
468 0 : setupStream();
469 0 : }
470 :
471 10 : MediaDecoder::MediaDecoder(const std::shared_ptr<MediaDemuxer>& demuxer, int index, MediaObserver observer)
472 10 : : demuxer_(demuxer)
473 10 : , avStream_(demuxer->getStream(index))
474 20 : , callback_(std::move(observer))
475 : {
476 10 : demuxer->setStreamCallback(index, [this](AVPacket& packet) { return decode(packet); });
477 10 : setupStream();
478 10 : }
479 :
480 : bool
481 0 : MediaDecoder::emitFrame(bool isAudio)
482 : {
483 0 : return demuxer_->emitFrame(isAudio);
484 : }
485 :
486 0 : MediaDecoder::MediaDecoder()
487 0 : : demuxer_(new MediaDemuxer)
488 0 : {}
489 :
490 149 : MediaDecoder::MediaDecoder(MediaObserver o)
491 149 : : demuxer_(new MediaDemuxer)
492 149 : , callback_(std::move(o))
493 149 : {}
494 :
495 159 : MediaDecoder::~MediaDecoder()
496 : {
497 : #ifdef ENABLE_HWACCEL
498 159 : if (decoderCtx_ && decoderCtx_->hw_device_ctx)
499 0 : av_buffer_unref(&decoderCtx_->hw_device_ctx);
500 : #endif
501 159 : if (decoderCtx_)
502 127 : avcodec_free_context(&decoderCtx_);
503 159 : }
504 :
505 : void
506 18 : MediaDecoder::flushBuffers()
507 : {
508 18 : avcodec_flush_buffers(decoderCtx_);
509 18 : }
510 :
511 : int
512 149 : MediaDecoder::openInput(const DeviceParams& p)
513 : {
514 149 : return demuxer_->openInput(p);
515 : }
516 :
517 : void
518 126 : MediaDecoder::setInterruptCallback(int (*cb)(void*), void* opaque)
519 : {
520 126 : demuxer_->setInterruptCallback(cb, opaque);
521 126 : }
522 :
523 : void
524 232 : MediaDecoder::setIOContext(MediaIOHandle* ioctx)
525 : {
526 232 : demuxer_->setIOContext(ioctx);
527 232 : }
528 :
529 : void
530 44 : MediaDecoder::setKeyFrameRequestCb(std::function<void()> cb)
531 : {
532 44 : demuxer_->setKeyFrameRequestCb(std::move(cb));
533 44 : }
534 :
535 : int
536 117 : MediaDecoder::setup(AVMediaType type)
537 : {
538 117 : demuxer_->findStreamInfo(type == AVMEDIA_TYPE_VIDEO);
539 117 : auto stream = demuxer_->selectStream(type);
540 117 : if (stream < 0) {
541 0 : JAMI_ERR("No stream found for type %i", static_cast<int>(type));
542 0 : return -1;
543 : }
544 117 : avStream_ = demuxer_->getStream(stream);
545 117 : if (avStream_ == nullptr) {
546 0 : JAMI_ERR("No stream found at index %i", stream);
547 0 : return -1;
548 : }
549 125 : demuxer_->setStreamCallback(stream, [this](AVPacket& packet) { return decode(packet); });
550 117 : return setupStream();
551 : }
552 :
553 : int
554 126 : MediaDecoder::setupStream()
555 : {
556 126 : int ret = 0;
557 126 : avcodec_free_context(&decoderCtx_);
558 :
559 127 : if (prepareDecoderContext() < 0)
560 0 : return -1; // failed
561 :
562 : #ifdef ENABLE_HWACCEL
563 : // if there was a fallback to software decoding, do not enable accel
564 : // it has been disabled already by the video_receive_thread/video_input
565 127 : enableAccel_ &= Manager::instance().videoPreferences.getDecodingAccelerated();
566 :
567 127 : if (enableAccel_ and not fallback_) {
568 127 : auto APIs = video::HardwareAccel::getCompatibleAccel(decoderCtx_->codec_id,
569 127 : decoderCtx_->width,
570 127 : decoderCtx_->height,
571 127 : CODEC_DECODER);
572 264 : for (const auto& it : APIs) {
573 137 : accel_ = std::make_unique<video::HardwareAccel>(it); // save accel
574 137 : auto ret = accel_->initAPI(false, nullptr);
575 137 : if (ret < 0) {
576 137 : accel_.reset();
577 137 : continue;
578 : }
579 0 : if (prepareDecoderContext() < 0)
580 0 : return -1; // failed
581 0 : accel_->setDetails(decoderCtx_);
582 0 : decoderCtx_->opaque = accel_.get();
583 0 : decoderCtx_->pix_fmt = accel_->getFormat();
584 0 : if (avcodec_open2(decoderCtx_, inputDecoder_, &options_) < 0) {
585 : // Failed to open codec
586 0 : JAMI_WARN("Fail to open hardware decoder for %s with %s",
587 : avcodec_get_name(decoderCtx_->codec_id),
588 : it.getName().c_str());
589 0 : avcodec_free_context(&decoderCtx_);
590 0 : decoderCtx_ = nullptr;
591 0 : accel_.reset();
592 0 : continue;
593 : } else {
594 : // Codec opened successfully.
595 0 : JAMI_WARN("Using hardware decoding for %s with %s",
596 : avcodec_get_name(decoderCtx_->codec_id),
597 : it.getName().c_str());
598 0 : break;
599 : }
600 : }
601 127 : }
602 : #endif
603 :
604 508 : JAMI_LOG("Using {} ({}) decoder for {}",
605 : inputDecoder_->long_name,
606 : inputDecoder_->name,
607 : av_get_media_type_string(avStream_->codecpar->codec_type));
608 127 : decoderCtx_->thread_count = std::max(1, std::min(8, static_cast<int>(std::thread::hardware_concurrency()) / 2));
609 127 : if (emulateRate_)
610 0 : JAMI_DBG() << "Using framerate emulation";
611 127 : startTime_ = av_gettime(); // Used to set pts after decoding, and for rate emulation
612 :
613 : #ifdef ENABLE_HWACCEL
614 127 : if (!accel_) {
615 127 : JAMI_WARN("Not using hardware decoding for %s", avcodec_get_name(decoderCtx_->codec_id));
616 127 : ret = avcodec_open2(decoderCtx_, inputDecoder_, nullptr);
617 : }
618 : #else
619 : ret = avcodec_open2(decoderCtx_, inputDecoder_, nullptr);
620 : #endif
621 127 : if (ret < 0) {
622 0 : JAMI_ERR() << "Unable to open codec: " << libav_utils::getError(ret);
623 0 : return -1;
624 : }
625 :
626 127 : return 0;
627 : }
628 :
629 : int
630 127 : MediaDecoder::prepareDecoderContext()
631 : {
632 127 : inputDecoder_ = findDecoder(avStream_->codecpar->codec_id);
633 127 : if (!inputDecoder_) {
634 0 : JAMI_ERROR("Unsupported codec");
635 0 : return -1;
636 : }
637 :
638 127 : decoderCtx_ = avcodec_alloc_context3(inputDecoder_);
639 127 : if (!decoderCtx_) {
640 0 : JAMI_ERROR("Failed to create decoder context");
641 0 : return -1;
642 : }
643 127 : avcodec_parameters_to_context(decoderCtx_, avStream_->codecpar);
644 127 : decoderCtx_->pkt_timebase = avStream_->time_base;
645 127 : width_ = decoderCtx_->width;
646 127 : height_ = decoderCtx_->height;
647 127 : decoderCtx_->framerate = avStream_->avg_frame_rate;
648 127 : if (avStream_->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
649 49 : if (decoderCtx_->framerate.num == 0 || decoderCtx_->framerate.den == 0)
650 44 : decoderCtx_->framerate = inputParams_.framerate;
651 49 : if (decoderCtx_->framerate.num == 0 || decoderCtx_->framerate.den == 0)
652 44 : decoderCtx_->framerate = {30, 1};
653 78 : } else if (avStream_->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
654 78 : if (decoderCtx_->codec_id == AV_CODEC_ID_OPUS) {
655 76 : av_opt_set_int(decoderCtx_, "decode_fec", fecEnabled_ ? 1 : 0, AV_OPT_SEARCH_CHILDREN);
656 : }
657 78 : auto format = libav_utils::choose_sample_fmt_default(
658 78 : inputDecoder_, Manager::instance().getRingBufferPool().getInternalAudioFormat().sampleFormat);
659 78 : decoderCtx_->sample_fmt = format;
660 78 : decoderCtx_->request_sample_fmt = format;
661 : }
662 127 : return 0;
663 : }
664 :
665 : void
666 52 : MediaDecoder::updateStartTime(int64_t startTime)
667 : {
668 52 : startTime_ = startTime;
669 52 : }
670 :
671 : DecodeStatus
672 8 : MediaDecoder::decode(AVPacket& packet)
673 : {
674 8 : int frameFinished = 0;
675 8 : auto ret = avcodec_send_packet(decoderCtx_, &packet);
676 : // TODO: Investigate avcodec_send_packet returning AVERROR_INVALIDDATA.
677 : // * Bug Windows documented here: git.jami.net/savoirfairelinux/jami-daemon/-/issues/1116
678 : // where avcodec_send_packet returns AVERROR_INVALIDDATA when the size information in the
679 : // packet is incorrect. Falling back onto sw decoding in this causes a segfault.
680 : // * A second problem occurs on some Windows devices with intel CPUs in which hardware
681 : // decoding fails with AVERROR_INVALIDDATA when using H.264. However, in this scenario,
682 : // falling back to software decoding works fine.
683 : // We need to figure out why this behavior occurs and how to discriminate between the two.
684 8 : if (ret < 0 && ret != AVERROR(EAGAIN)) {
685 : #ifdef ENABLE_HWACCEL
686 0 : if (accel_) {
687 0 : JAMI_WARN("Decoding error falling back to software");
688 0 : fallback_ = true;
689 0 : accel_.reset();
690 0 : avcodec_flush_buffers(decoderCtx_);
691 0 : setupStream();
692 0 : return DecodeStatus::FallBack;
693 : }
694 : #endif
695 0 : avcodec_flush_buffers(decoderCtx_);
696 0 : return ret == AVERROR_EOF ? DecodeStatus::Success : DecodeStatus::DecodeError;
697 : }
698 :
699 : #ifdef ENABLE_VIDEO
700 8 : auto f = (inputDecoder_->type == AVMEDIA_TYPE_VIDEO)
701 4 : ? std::static_pointer_cast<MediaFrame>(std::make_shared<VideoFrame>())
702 16 : : std::static_pointer_cast<MediaFrame>(std::make_shared<AudioFrame>());
703 : #else
704 : auto f = std::static_pointer_cast<MediaFrame>(std::make_shared<AudioFrame>());
705 : #endif
706 8 : auto* frame = f->pointer();
707 8 : ret = avcodec_receive_frame(decoderCtx_, frame);
708 : // time_base is not set in AVCodecContext for decoding
709 : // fail to set it causes pts to be incorrectly computed down in the function
710 8 : if (inputDecoder_->type == AVMEDIA_TYPE_VIDEO) {
711 4 : decoderCtx_->time_base.num = decoderCtx_->framerate.den;
712 4 : decoderCtx_->time_base.den = decoderCtx_->framerate.num;
713 : } else {
714 4 : decoderCtx_->time_base.num = 1;
715 4 : decoderCtx_->time_base.den = decoderCtx_->sample_rate;
716 : }
717 8 : frame->time_base = decoderCtx_->time_base;
718 8 : if (resolutionChangedCallback_) {
719 4 : if (decoderCtx_->width != width_ or decoderCtx_->height != height_) {
720 0 : JAMI_DBG("Resolution changed from %dx%d to %dx%d", width_, height_, decoderCtx_->width, decoderCtx_->height);
721 0 : width_ = decoderCtx_->width;
722 0 : height_ = decoderCtx_->height;
723 0 : resolutionChangedCallback_(width_, height_);
724 : }
725 : }
726 8 : if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
727 0 : return DecodeStatus::DecodeError;
728 : }
729 8 : if (ret >= 0)
730 4 : frameFinished = 1;
731 :
732 8 : if (frameFinished) {
733 4 : if (inputDecoder_->type == AVMEDIA_TYPE_VIDEO) {
734 0 : frame->format = (AVPixelFormat) correctPixFmt(frame->format);
735 : } else {
736 : // It's possible (albeit rare) for avcodec_receive_frame to return a frame with
737 : // unspecified channel order. This can cause issues later on in the resampler
738 : // because swr_convert_frame expects the ch_layout of the input frame to match
739 : // the in_ch_layout of the SwrContext, but swr_init sets in_ch_layout to a default
740 : // value based on the number of channels if the channel order of the input frame
741 : // is unspecified.
742 4 : if (frame->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC) {
743 4 : av_channel_layout_default(&frame->ch_layout, frame->ch_layout.nb_channels);
744 : }
745 : }
746 4 : auto packetTimestamp = frame->pts; // in stream time base
747 4 : frame->pts = av_rescale_q_rnd(av_gettime() - startTime_,
748 : {1, AV_TIME_BASE},
749 4 : decoderCtx_->time_base,
750 : static_cast<AVRounding>(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
751 4 : lastTimestamp_ = frame->pts;
752 4 : if (emulateRate_ and packetTimestamp != AV_NOPTS_VALUE) {
753 0 : auto startTime = avStream_->start_time == AV_NOPTS_VALUE ? 0 : avStream_->start_time;
754 0 : rational<double> frame_time = rational<double>(getTimeBase())
755 0 : * rational<double>(static_cast<double>(packetTimestamp - startTime));
756 0 : auto target_relative = static_cast<std::int64_t>(frame_time.real() * 1e6);
757 0 : auto target_absolute = startTime_ + target_relative;
758 0 : if (target_relative < seekTime_) {
759 0 : return DecodeStatus::Success;
760 : }
761 : // required frame found. Reset seek time
762 0 : if (target_relative >= seekTime_) {
763 0 : resetSeekTime();
764 : }
765 0 : auto now = av_gettime();
766 0 : if (target_absolute > now) {
767 0 : std::this_thread::sleep_for(std::chrono::microseconds(target_absolute - now));
768 : }
769 : }
770 :
771 4 : if (callback_)
772 4 : callback_(std::move(f));
773 :
774 4 : if (contextCallback_ && firstDecode_.load()) {
775 0 : firstDecode_.exchange(false);
776 0 : contextCallback_();
777 : }
778 4 : return DecodeStatus::FrameFinished;
779 : }
780 4 : return DecodeStatus::Success;
781 8 : }
782 :
783 : void
784 18 : MediaDecoder::setSeekTime(int64_t time)
785 : {
786 18 : seekTime_ = time;
787 18 : }
788 :
789 : MediaDemuxer::Status
790 52 : MediaDecoder::decode()
791 : {
792 52 : auto ret = demuxer_->decode();
793 52 : if (ret == MediaDemuxer::Status::RestartRequired) {
794 0 : avcodec_flush_buffers(decoderCtx_);
795 0 : setupStream();
796 0 : ret = MediaDemuxer::Status::EndOfFile;
797 : }
798 52 : return ret;
799 : }
800 :
801 : #ifdef ENABLE_VIDEO
802 : #ifdef ENABLE_HWACCEL
803 : void
804 0 : MediaDecoder::enableAccel(bool enableAccel)
805 : {
806 0 : enableAccel_ = enableAccel;
807 0 : emitSignal<libjami::ConfigurationSignal::HardwareDecodingChanged>(enableAccel_);
808 0 : if (!enableAccel) {
809 0 : accel_.reset();
810 0 : if (decoderCtx_)
811 0 : decoderCtx_->opaque = nullptr;
812 : }
813 0 : }
814 : #endif
815 :
816 : DecodeStatus
817 0 : MediaDecoder::flush()
818 : {
819 : AVPacket inpacket;
820 0 : av_init_packet(&inpacket);
821 :
822 0 : int frameFinished = 0;
823 0 : int ret = 0;
824 0 : ret = avcodec_send_packet(decoderCtx_, &inpacket);
825 0 : if (ret < 0 && ret != AVERROR(EAGAIN))
826 0 : return ret == AVERROR_EOF ? DecodeStatus::Success : DecodeStatus::DecodeError;
827 :
828 0 : auto result = std::make_shared<MediaFrame>();
829 0 : ret = avcodec_receive_frame(decoderCtx_, result->pointer());
830 0 : if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
831 0 : return DecodeStatus::DecodeError;
832 0 : if (ret >= 0)
833 0 : frameFinished = 1;
834 :
835 0 : if (frameFinished) {
836 0 : av_packet_unref(&inpacket);
837 0 : if (callback_)
838 0 : callback_(std::move(result));
839 0 : return DecodeStatus::FrameFinished;
840 : }
841 :
842 0 : return DecodeStatus::Success;
843 0 : }
844 : #endif // ENABLE_VIDEO
845 :
846 : int
847 54 : MediaDecoder::getWidth() const
848 : {
849 54 : return decoderCtx_ ? decoderCtx_->width : 0;
850 : }
851 :
852 : int
853 54 : MediaDecoder::getHeight() const
854 : {
855 54 : return decoderCtx_ ? decoderCtx_->height : 0;
856 : }
857 :
858 : std::string
859 0 : MediaDecoder::getDecoderName() const
860 : {
861 0 : return decoderCtx_ ? decoderCtx_->codec->name : "";
862 : }
863 :
864 : rational<double>
865 5 : MediaDecoder::getFps() const
866 : {
867 5 : return {(double) avStream_->avg_frame_rate.num, (double) avStream_->avg_frame_rate.den};
868 : }
869 :
870 : rational<unsigned>
871 0 : MediaDecoder::getTimeBase() const
872 : {
873 0 : return {(unsigned) avStream_->time_base.num, (unsigned) avStream_->time_base.den};
874 : }
875 :
876 : AVPixelFormat
877 5 : MediaDecoder::getPixelFormat() const
878 : {
879 5 : return decoderCtx_->pix_fmt;
880 : }
881 :
882 : int
883 0 : MediaDecoder::correctPixFmt(int input_pix_fmt)
884 : {
885 : // https://ffmpeg.org/pipermail/ffmpeg-user/2014-February/020152.html
886 : int pix_fmt;
887 0 : switch (input_pix_fmt) {
888 0 : case AV_PIX_FMT_YUVJ420P:
889 0 : pix_fmt = AV_PIX_FMT_YUV420P;
890 0 : break;
891 0 : case AV_PIX_FMT_YUVJ422P:
892 0 : pix_fmt = AV_PIX_FMT_YUV422P;
893 0 : break;
894 0 : case AV_PIX_FMT_YUVJ444P:
895 0 : pix_fmt = AV_PIX_FMT_YUV444P;
896 0 : break;
897 0 : case AV_PIX_FMT_YUVJ440P:
898 0 : pix_fmt = AV_PIX_FMT_YUV440P;
899 0 : break;
900 0 : default:
901 0 : pix_fmt = input_pix_fmt;
902 0 : break;
903 : }
904 0 : return pix_fmt;
905 : }
906 :
907 : MediaStream
908 55 : MediaDecoder::getStream(const std::string& name) const
909 : {
910 55 : if (!decoderCtx_) {
911 40 : JAMI_WARN("No decoder context");
912 40 : return {};
913 : }
914 15 : auto ms = MediaStream(name, decoderCtx_, lastTimestamp_);
915 : #ifdef ENABLE_HWACCEL
916 : // accel_ is null if not using accelerated codecs
917 15 : if (accel_)
918 5 : ms.format = accel_->getSoftwareFormat();
919 : #endif
920 15 : return ms;
921 15 : }
922 :
923 : } // namespace jami
|