1 #include "ffmpeg_capture.h"
13 #include <libavcodec/avcodec.h>
14 #include <libavformat/avformat.h>
15 #include <libavutil/avutil.h>
16 #include <libavutil/error.h>
17 #include <libavutil/frame.h>
18 #include <libavutil/imgutils.h>
19 #include <libavutil/mem.h>
20 #include <libavutil/pixfmt.h>
21 #include <libavutil/opt.h>
22 #include <libswscale/swscale.h>
29 #include <unordered_set>
33 #include <movit/colorspace_conversion_effect.h>
35 #include "bmusb/bmusb.h"
36 #include "shared/ffmpeg_raii.h"
37 #include "ffmpeg_util.h"
39 #include "image_input.h"
40 #include "ref_counted_frame.h"
41 #include "shared/timebase.h"
48 using namespace std::chrono;
49 using namespace bmusb;
50 using namespace movit;
51 using namespace Eigen;
53 // Avoid deprecation warnings, but we don't want to drop FFmpeg 5.1 support just yet.
54 #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(57, 30, 100)
55 #define pkt_duration duration
60 steady_clock::time_point compute_frame_start(int64_t frame_pts, int64_t pts_origin, const AVRational &video_timebase, const steady_clock::time_point &origin, double rate)
62 const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
63 return origin + duration_cast<steady_clock::duration>(pts / rate);
66 bool changed_since(const std::string &pathname, const timespec &ts)
72 if (stat(pathname.c_str(), &buf) != 0) {
73 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
76 return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
79 bool is_full_range(const AVPixFmtDescriptor *desc)
81 // This is horrible, but there's no better way that I know of.
82 return (strchr(desc->name, 'j') != nullptr);
85 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
87 if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
88 return AV_PIX_FMT_BGRA;
90 if (dst_format_type == FFmpegCapture::PixelFormat_NV12) {
91 return AV_PIX_FMT_NV12;
94 assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
96 // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
97 // and be done with it. It's too strange to spend a lot of time on.
98 // (Let's hope there's no alpha.)
99 const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
100 if (src_desc == nullptr ||
101 src_desc->nb_components != 3 ||
102 (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
103 return AV_PIX_FMT_YUV444P;
106 // The best for us would be Cb and Cr together if possible,
107 // but FFmpeg doesn't support that except in the special case of
108 // NV12, so we need to go to planar even for the case of NV12.
109 // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
110 // that matches in color range. (This will also include the case of
111 // the source format already being acceptable.)
112 bool src_full_range = is_full_range(src_desc);
113 const char *best_format = "yuv444p";
114 unsigned best_score = numeric_limits<unsigned>::max();
115 for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
117 desc = av_pix_fmt_desc_next(desc)) {
118 // Find planar Y'CbCr formats only.
119 if (desc->nb_components != 3) continue;
120 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
121 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
122 if (desc->comp[0].plane != 0 ||
123 desc->comp[1].plane != 1 ||
124 desc->comp[2].plane != 2) continue;
126 // 8-bit formats only.
127 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
128 if (desc->comp[0].depth != 8) continue;
130 // Same or better chroma resolution only.
131 int chroma_w_diff = src_desc->log2_chroma_w - desc->log2_chroma_w;
132 int chroma_h_diff = src_desc->log2_chroma_h - desc->log2_chroma_h;
133 if (chroma_w_diff < 0 || chroma_h_diff < 0)
136 // Matching full/limited range only.
137 if (is_full_range(desc) != src_full_range)
140 // Pick something with as little excess chroma resolution as possible.
141 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
142 if (score < best_score) {
144 best_format = desc->name;
147 return av_get_pix_fmt(best_format);
150 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame, bool is_mjpeg, AVColorSpace *last_colorspace, AVChromaLocation *last_chroma_location)
153 AVColorSpace colorspace = frame->colorspace;
154 switch (colorspace) {
155 case AVCOL_SPC_BT709:
156 format.luma_coefficients = YCBCR_REC_709;
158 case AVCOL_SPC_BT470BG:
159 case AVCOL_SPC_SMPTE170M:
160 case AVCOL_SPC_SMPTE240M:
161 format.luma_coefficients = YCBCR_REC_601;
163 case AVCOL_SPC_BT2020_NCL:
164 format.luma_coefficients = YCBCR_REC_2020;
166 case AVCOL_SPC_UNSPECIFIED:
167 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
170 if (colorspace != *last_colorspace) {
171 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
174 format.luma_coefficients = YCBCR_REC_709;
177 *last_colorspace = colorspace;
179 format.full_range = is_full_range(desc);
180 format.num_levels = 1 << desc->comp[0].depth;
181 format.chroma_subsampling_x = 1 << desc->log2_chroma_w;
182 format.chroma_subsampling_y = 1 << desc->log2_chroma_h;
184 switch (frame->chroma_location) {
185 case AVCHROMA_LOC_LEFT:
186 format.cb_x_position = 0.0;
187 format.cb_y_position = 0.5;
189 case AVCHROMA_LOC_CENTER:
190 format.cb_x_position = 0.5;
191 format.cb_y_position = 0.5;
193 case AVCHROMA_LOC_TOPLEFT:
194 format.cb_x_position = 0.0;
195 format.cb_y_position = 0.0;
197 case AVCHROMA_LOC_TOP:
198 format.cb_x_position = 0.5;
199 format.cb_y_position = 0.0;
201 case AVCHROMA_LOC_BOTTOMLEFT:
202 format.cb_x_position = 0.0;
203 format.cb_y_position = 1.0;
205 case AVCHROMA_LOC_BOTTOM:
206 format.cb_x_position = 0.5;
207 format.cb_y_position = 1.0;
210 if (frame->chroma_location != *last_chroma_location) {
211 fprintf(stderr, "Unknown chroma location coefficient enum %d from FFmpeg; choosing center.\n",
212 frame->chroma_location);
214 format.cb_x_position = 0.5;
215 format.cb_y_position = 0.5;
218 *last_chroma_location = frame->chroma_location;
220 if (is_mjpeg && !format.full_range) {
221 // Limited-range MJPEG is only detected by FFmpeg whenever a special
222 // JPEG comment is set, which means that in practice, the stream is
223 // almost certainly generated by Futatabi. Override FFmpeg's forced
224 // MJPEG defaults (it disregards the values set in the mux) with what
226 format.luma_coefficients = YCBCR_REC_709;
227 format.cb_x_position = 0.0;
228 format.cb_y_position = 0.5;
231 format.cr_x_position = format.cb_x_position;
232 format.cr_y_position = format.cb_y_position;
236 RGBTriplet get_neutral_color(AVDictionary *metadata)
238 if (metadata == nullptr) {
239 return RGBTriplet(1.0f, 1.0f, 1.0f);
241 AVDictionaryEntry *entry = av_dict_get(metadata, "WhitePoint", nullptr, 0);
242 if (entry == nullptr) {
243 return RGBTriplet(1.0f, 1.0f, 1.0f);
246 unsigned x_nom, x_den, y_nom, y_den;
247 if (sscanf(entry->value, " %u:%u , %u:%u", &x_nom, &x_den, &y_nom, &y_den) != 4) {
248 fprintf(stderr, "WARNING: Unable to parse white point '%s', using default white point\n", entry->value);
249 return RGBTriplet(1.0f, 1.0f, 1.0f);
252 double x = double(x_nom) / x_den;
253 double y = double(y_nom) / y_den;
254 double z = 1.0 - x - y;
256 Matrix3d rgb_to_xyz_matrix = movit::ColorspaceConversionEffect::get_xyz_matrix(COLORSPACE_sRGB);
257 Vector3d rgb = rgb_to_xyz_matrix.inverse() * Vector3d(x, y, z);
259 return RGBTriplet(rgb[0], rgb[1], rgb[2]);
264 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
265 : filename(filename), width(width), height(height), video_timebase{1, 1}
267 description = "Video: " + filename;
269 last_frame = steady_clock::now();
271 avformat_network_init(); // In case someone wants this.
275 FFmpegCapture::FFmpegCapture(int srt_sock, const string &stream_id)
276 : srt_sock(srt_sock),
277 width(0), // Don't resize; SRT streams typically have stable resolution, and should behave much like regular cards in general.
279 pixel_format(bmusb::PixelFormat_8BitYCbCrPlanar),
282 if (stream_id.empty()) {
283 description = "SRT stream";
285 description = stream_id;
287 play_as_fast_as_possible = true;
289 last_frame = steady_clock::now();
293 FFmpegCapture::~FFmpegCapture()
295 if (has_dequeue_callbacks) {
296 dequeue_cleanup_callback();
298 swr_free(&resampler);
300 if (srt_sock != -1) {
306 void FFmpegCapture::configure_card()
308 if (video_frame_allocator == nullptr) {
309 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
310 set_video_frame_allocator(owned_video_frame_allocator.get());
312 if (audio_frame_allocator == nullptr) {
313 // Audio can come out in pretty large chunks, so increase from the default 1 MB.
314 owned_audio_frame_allocator.reset(new MallocFrameAllocator(1 << 20, NUM_QUEUED_AUDIO_FRAMES));
315 set_audio_frame_allocator(owned_audio_frame_allocator.get());
319 void FFmpegCapture::start_bm_capture()
325 producer_thread_should_quit.unquit();
326 producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
329 void FFmpegCapture::stop_dequeue_thread()
335 producer_thread_should_quit.quit();
336 producer_thread.join();
339 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
341 // Note: This will never really be shown in the UI.
345 snprintf(buf, sizeof(buf), "%ux%u", sws_last_width, sws_last_height);
348 mode.autodetect = false;
349 mode.width = sws_last_width;
350 mode.height = sws_last_height;
351 mode.frame_rate_num = 60;
352 mode.frame_rate_den = 1;
353 mode.interlaced = false;
355 return {{ 0, mode }};
358 void FFmpegCapture::producer_thread_func()
360 char thread_name[16];
361 snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
362 pthread_setname_np(pthread_self(), thread_name);
364 while (!producer_thread_should_quit.should_quit()) {
365 string filename_copy;
367 lock_guard<mutex> lock(filename_mu);
368 filename_copy = filename;
372 if (srt_sock == -1) {
373 pathname = search_for_file(filename_copy);
375 pathname = description;
377 if (pathname.empty()) {
378 send_disconnected_frame();
382 producer_thread_should_quit.sleep_for(seconds(1));
383 fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename_copy.c_str());
386 should_interrupt = false;
387 if (!play_video(pathname)) {
389 send_disconnected_frame();
393 fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
394 producer_thread_should_quit.sleep_for(seconds(1));
399 send_disconnected_frame();
403 // Probably just EOF, will exit the loop above on next test.
406 if (has_dequeue_callbacks) {
407 dequeue_cleanup_callback();
408 has_dequeue_callbacks = false;
412 void FFmpegCapture::send_disconnected_frame()
414 // Send an empty frame to signal that we have no signal anymore.
415 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
416 size_t frame_width = width == 0 ? global_flags.width : width;
417 size_t frame_height = height == 0 ? global_flags.height : height;
418 if (video_frame.data) {
419 VideoFormat video_format;
420 video_format.width = frame_width;
421 video_format.height = frame_height;
422 video_format.frame_rate_nom = 60;
423 video_format.frame_rate_den = 1;
424 video_format.is_connected = false;
425 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
426 video_format.stride = frame_width * 4;
427 video_frame.len = frame_width * frame_height * 4;
428 memset(video_frame.data, 0, video_frame.len);
430 video_format.stride = frame_width;
431 current_frame_ycbcr_format.luma_coefficients = YCBCR_REC_709;
432 current_frame_ycbcr_format.full_range = true;
433 current_frame_ycbcr_format.num_levels = 256;
434 current_frame_ycbcr_format.chroma_subsampling_x = 2;
435 current_frame_ycbcr_format.chroma_subsampling_y = 2;
436 current_frame_ycbcr_format.cb_x_position = 0.0f;
437 current_frame_ycbcr_format.cb_y_position = 0.0f;
438 current_frame_ycbcr_format.cr_x_position = 0.0f;
439 current_frame_ycbcr_format.cr_y_position = 0.0f;
440 video_frame.len = frame_width * frame_height * 2;
441 memset(video_frame.data, 0, frame_width * frame_height);
442 memset(video_frame.data + frame_width * frame_height, 128, frame_width * frame_height); // Valid for both NV12 and planar.
445 if (frame_callback != nullptr) {
446 frame_callback(-1, AVRational{1, TIMEBASE}, -1, AVRational{1, TIMEBASE}, timecode++,
447 video_frame, /*video_offset=*/0, video_format,
448 FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
450 last_frame_was_connected = false;
455 if (card_disconnected_callback != nullptr) {
456 card_disconnected_callback();
461 template<AVHWDeviceType type>
462 AVPixelFormat get_hw_format(AVCodecContext *ctx, const AVPixelFormat *fmt)
464 bool found_config_of_right_type = false;
465 for (int i = 0;; ++i) { // Termination condition inside loop.
466 const AVCodecHWConfig *config = avcodec_get_hw_config(ctx->codec, i);
467 if (config == nullptr) { // End of list.
470 if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) ||
471 config->device_type != type) {
472 // Not interesting for us.
476 // We have a config of the right type, but does it actually support
477 // the pixel format we want? (Seemingly, FFmpeg's way of signaling errors
478 // is to just replace the pixel format with a software-decoded one,
480 found_config_of_right_type = true;
481 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
482 if (config->pix_fmt == *fmt_ptr) {
483 fprintf(stderr, "Initialized '%s' hardware decoding for codec '%s'.\n",
484 av_hwdevice_get_type_name(type), ctx->codec->name);
485 if (ctx->profile == FF_PROFILE_H264_BASELINE) {
486 fprintf(stderr, "WARNING: Stream claims to be H.264 Baseline, which is generally poorly supported in hardware decoders.\n");
487 fprintf(stderr, " Consider encoding it as Constrained Baseline, Main or High instead.\n");
488 fprintf(stderr, " Decoding might fail and fall back to software.\n");
490 return config->pix_fmt;
493 fprintf(stderr, "Decoder '%s' supports only these pixel formats:", ctx->codec->name);
494 unordered_set<AVPixelFormat> seen;
495 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
496 if (!seen.count(*fmt_ptr)) {
497 fprintf(stderr, " %s", av_get_pix_fmt_name(*fmt_ptr));
498 seen.insert(*fmt_ptr);
501 fprintf(stderr, " (wanted %s for hardware acceleration)\n", av_get_pix_fmt_name(config->pix_fmt));
505 if (!found_config_of_right_type) {
506 fprintf(stderr, "Decoder '%s' does not support device type '%s'.\n", ctx->codec->name, av_hwdevice_get_type_name(type));
509 // We found no VA-API formats, so take the first software format.
510 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
511 if ((av_pix_fmt_desc_get(*fmt_ptr)->flags & AV_PIX_FMT_FLAG_HWACCEL) == 0) {
512 fprintf(stderr, "Falling back to software format %s.\n", av_get_pix_fmt_name(*fmt_ptr));
517 // Fallback: Just return anything. (Should never really happen.)
521 bool FFmpegCapture::play_video(const string &pathname)
523 // Note: Call before open, not after; otherwise, there's a race.
524 // (There is now, too, but it tips the correct way. We could use fstat()
525 // if we had the file descriptor.)
526 timespec last_modified;
528 if (stat(pathname.c_str(), &buf) != 0) {
529 // Probably some sort of protocol, so can't stat.
530 last_modified.tv_sec = -1;
532 last_modified = buf.st_mtim;
534 last_colorspace = static_cast<AVColorSpace>(-1);
535 last_chroma_location = static_cast<AVChromaLocation>(-1);
537 AVFormatContextWithCloser format_ctx;
538 if (srt_sock == -1) {
539 // Regular file (or stream).
540 frame_timeout_started = steady_clock::now();
541 frame_timeout_valid = true;
542 format_ctx = avformat_open_input_unique(pathname.c_str(), /*fmt=*/nullptr,
544 AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
545 frame_timeout_valid = false;
548 // SRT socket, already opened.
549 const AVInputFormat *mpegts_fmt = av_find_input_format("mpegts");
550 format_ctx = avformat_open_input_unique(&FFmpegCapture::read_srt_thunk, this,
551 mpegts_fmt, /*options=*/nullptr,
552 AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
557 if (format_ctx == nullptr) {
558 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
562 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
563 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
567 int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
568 if (video_stream_index == -1) {
569 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
573 int audio_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_AUDIO);
574 int subtitle_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_SUBTITLE);
575 has_last_subtitle = false;
577 // Open video decoder.
578 const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
579 const AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
581 video_timebase = format_ctx->streams[video_stream_index]->time_base;
582 AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
583 if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
584 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
587 if (video_codec == nullptr) {
588 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
592 // Seemingly, it's not too easy to make something that just initializes
593 // “whatever goes”, so we don't get CUDA or VULKAN or whatever here
594 // without enumerating through several different types.
595 // VA-API and VDPAU will do for now. We prioritize VDPAU for the
596 // simple reason that there's a VA-API-via-VDPAU emulation for NVidia
597 // cards that seems to work, but just hangs when trying to transfer the frame.
599 // Note that we don't actually check codec support beforehand,
600 // so if you have a low-end VDPAU device but a high-end VA-API device,
601 // you lose out on the extra codec support from the latter.
602 AVBufferRef *hw_device_ctx = nullptr;
603 if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VDPAU, nullptr, nullptr, 0) >= 0) {
604 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
605 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VDPAU>;
606 } else if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, nullptr, nullptr, 0) >= 0) {
607 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
608 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VAAPI>;
610 fprintf(stderr, "Failed to initialize VA-API or VDPAU for FFmpeg acceleration. Decoding video in software.\n");
613 if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
614 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
617 unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
618 video_codec_ctx.get(), avcodec_close);
620 // Used in decode_ycbcr_format().
621 is_mjpeg = video_codecpar->codec_id == AV_CODEC_ID_MJPEG;
623 // Open audio decoder, if we have audio.
624 AVCodecContextWithDeleter audio_codec_ctx;
625 if (audio_stream_index != -1) {
626 audio_codec_ctx = avcodec_alloc_context3_unique(nullptr);
627 const AVCodecParameters *audio_codecpar = format_ctx->streams[audio_stream_index]->codecpar;
628 audio_timebase = format_ctx->streams[audio_stream_index]->time_base;
629 if (avcodec_parameters_to_context(audio_codec_ctx.get(), audio_codecpar) < 0) {
630 fprintf(stderr, "%s: Cannot fill audio codec parameters\n", pathname.c_str());
633 const AVCodec *audio_codec = avcodec_find_decoder(audio_codecpar->codec_id);
634 if (audio_codec == nullptr) {
635 fprintf(stderr, "%s: Cannot find audio decoder\n", pathname.c_str());
638 if (avcodec_open2(audio_codec_ctx.get(), audio_codec, nullptr) < 0) {
639 fprintf(stderr, "%s: Cannot open audio decoder\n", pathname.c_str());
643 unique_ptr<AVCodecContext, decltype(avcodec_close)*> audio_codec_ctx_cleanup(
644 audio_codec_ctx.get(), avcodec_close);
649 bool first_frame = true;
650 int consecutive_errors = 0;
651 while (!producer_thread_should_quit.should_quit()) {
652 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
655 if (should_interrupt.load()) {
656 // Check as a failsafe, so that we don't need to rely on avio if we don't have to.
659 UniqueFrame audio_frame = audio_frame_allocator->alloc_frame();
660 AudioFormat audio_format;
664 frame_timeout_started = steady_clock::now();
665 frame_timeout_valid = true;
666 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(), audio_codec_ctx.get(),
667 pathname, video_stream_index, audio_stream_index, subtitle_stream_index, audio_frame.get(), &audio_format, &audio_pts, &error);
668 frame_timeout_valid = false;
669 if (should_interrupt.load()) {
670 // Abort no matter whether we got a frame or not.
674 if (++consecutive_errors >= 100) {
675 fprintf(stderr, "More than 100 consecutive error video frames, aborting playback.\n");
681 consecutive_errors = 0;
683 if (frame == nullptr) {
684 // EOF. Loop back to the start if we can.
685 if (format_ctx->pb != nullptr && format_ctx->pb->seekable == 0) {
686 // Not seekable (but seemingly, sometimes av_seek_frame() would return 0 anyway,
690 if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
691 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
694 if (video_codec_ctx != nullptr) {
695 avcodec_flush_buffers(video_codec_ctx.get());
697 if (audio_codec_ctx != nullptr) {
698 avcodec_flush_buffers(audio_codec_ctx.get());
700 // If the file has changed since last time, return to get it reloaded.
701 // Note that depending on how you move the file into place, you might
702 // end up corrupting the one you're already playing, so this path
703 // might not trigger.
704 if (changed_since(pathname, last_modified)) {
711 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
712 if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
713 // Invalid frame rate; try constructing it from the previous frame length.
714 // (This is especially important if we are the master card, for SRT,
715 // since it affects audio. Not all senders have good timebases
716 // (e.g., Larix rounds first to timebase 1000 and then multiplies by
717 // 90 from there, it seems), but it's much better to have an oscillating
718 // value than just locking at 60.
719 if (last_pts != 0 && frame->pts > last_pts) {
720 int64_t pts_diff = frame->pts - last_pts;
721 video_format.frame_rate_nom = video_timebase.den;
722 video_format.frame_rate_den = video_timebase.num * pts_diff;
724 video_format.frame_rate_nom = 60;
725 video_format.frame_rate_den = 1;
728 UniqueFrame video_frame = make_video_frame(frame.get(), pathname, &error);
734 if (last_pts == 0 && pts_origin == 0) {
735 pts_origin = frame->pts;
737 steady_clock::time_point now = steady_clock::now();
738 if (play_as_fast_as_possible) {
739 video_frame->received_timestamp = now;
740 audio_frame->received_timestamp = now;
741 next_frame_start = now;
743 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
744 if (first_frame && last_frame_was_connected) {
745 // If reconnect took more than one second, this is probably a live feed,
746 // and we should reset the resampler. (Or the rate is really, really low,
747 // in which case a reset on the first frame is fine anyway.)
748 if (duration<double>(next_frame_start - last_frame).count() >= 1.0) {
749 last_frame_was_connected = false;
752 video_frame->received_timestamp = next_frame_start;
754 // The easiest way to get all the rate conversions etc. right is to move the
755 // audio PTS into the video PTS timebase and go from there. (We'll get some
756 // rounding issues, but they should not be a big problem.)
757 int64_t audio_pts_as_video_pts = av_rescale_q(audio_pts, audio_timebase, video_timebase);
758 audio_frame->received_timestamp = compute_frame_start(audio_pts_as_video_pts, pts_origin, video_timebase, start, rate);
760 if (audio_frame->len != 0) {
761 // The received timestamps in Nageru are measured after we've just received the frame.
762 // However, pts (especially audio pts) is at the _beginning_ of the frame.
763 // If we have locked audio, the distinction doesn't really matter, as pts is
764 // on a relative scale and a fixed offset is fine. But if we don't, we will have
765 // a different number of samples each time, which will cause huge audio jitter
766 // and throw off the resampler.
768 // In a sense, we should have compensated by adding the frame and audio lengths
769 // to video_frame->received_timestamp and audio_frame->received_timestamp respectively,
770 // but that would mean extra waiting in sleep_until(). All we need is that they
771 // are correct relative to each other, though (and to the other frames we send),
772 // so just align the end of the audio frame, and we're fine.
773 size_t num_samples = (audio_frame->len * 8) / audio_format.bits_per_sample / audio_format.num_channels;
774 double offset = double(num_samples) / OUTPUT_FREQUENCY -
775 double(video_format.frame_rate_den) / video_format.frame_rate_nom;
776 audio_frame->received_timestamp += duration_cast<steady_clock::duration>(duration<double>(offset));
779 if (duration<double>(now - next_frame_start).count() >= 0.1) {
780 // If we don't have enough CPU to keep up, or if we have a live stream
781 // where the initial origin was somehow wrong, we could be behind indefinitely.
782 // In particular, this will give the audio resampler problems as it tries
783 // to speed up to reduce the delay, hitting the low end of the buffer every time.
784 fprintf(stderr, "%s: Playback %.0f ms behind, resetting time scale\n",
786 1e3 * duration<double>(now - next_frame_start).count());
787 pts_origin = frame->pts;
788 start = next_frame_start = now;
789 timecode += TYPICAL_FPS * 2 + 1;
792 bool finished_wakeup;
793 if (play_as_fast_as_possible) {
794 finished_wakeup = !producer_thread_should_quit.should_quit();
796 finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
798 if (finished_wakeup) {
799 if (audio_frame->len > 0) {
800 assert(audio_pts != -1);
802 if (!last_frame_was_connected) {
803 // We're recovering from an error (or really slow load, see above).
804 // Make sure to get the audio resampler reset. (This is a hack;
805 // ideally, the frame callback should just accept a way to signal
806 // audio discontinuity.)
807 timecode += TYPICAL_FPS * 2 + 1;
809 last_neutral_color = get_neutral_color(frame->metadata);
810 if (frame_callback != nullptr) {
811 frame_callback(frame->pts, video_timebase, audio_pts, audio_timebase, timecode++,
812 video_frame.get_and_release(), 0, video_format,
813 audio_frame.get_and_release(), 0, audio_format);
816 last_frame = steady_clock::now();
817 last_frame_was_connected = true;
820 if (producer_thread_should_quit.should_quit()) break;
822 bool rewound = false;
823 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
826 // If we just rewound, drop this frame on the floor and be done.
830 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
831 // but if it's now in the past, we'll reset the origin, so that we don't
832 // generate a huge backlog of frames that we need to run through quickly.
833 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
834 steady_clock::time_point now = steady_clock::now();
835 if (next_frame_start < now) {
836 pts_origin = frame->pts;
837 start = next_frame_start = now;
841 last_pts = frame->pts;
846 void FFmpegCapture::internal_rewind()
848 pts_origin = last_pts = 0;
849 start = next_frame_start = steady_clock::now();
852 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
854 // Process any queued commands from other threads.
855 vector<QueuedCommand> commands;
857 lock_guard<mutex> lock(queue_mu);
858 swap(commands, command_queue);
860 for (const QueuedCommand &cmd : commands) {
861 switch (cmd.command) {
862 case QueuedCommand::REWIND:
863 if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
864 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
866 // If the file has changed since last time, return to get it reloaded.
867 // Note that depending on how you move the file into place, you might
868 // end up corrupting the one you're already playing, so this path
869 // might not trigger.
870 if (changed_since(pathname, last_modified)) {
874 if (rewound != nullptr) {
879 case QueuedCommand::CHANGE_RATE:
880 // Change the origin to the last played frame.
881 start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
882 pts_origin = last_pts;
884 play_as_fast_as_possible = (rate >= 10.0);
895 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
896 const std::string &pathname, int video_stream_index, int audio_stream_index, int subtitle_stream_index,
897 FrameAllocator::Frame *audio_frame, AudioFormat *audio_format, int64_t *audio_pts, bool *error)
901 // Read packets until we have a frame or there are none left.
902 bool frame_finished = false;
903 AVFrameWithDeleter audio_avframe = av_frame_alloc_unique();
904 AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
907 bool has_audio = false;
909 AVPacketWithDeleter pkt = av_packet_alloc_unique();
912 if (av_read_frame(format_ctx, pkt.get()) == 0) {
913 if (pkt->stream_index == audio_stream_index && audio_callback != nullptr) {
914 audio_callback(pkt.get(), format_ctx->streams[audio_stream_index]->time_base);
916 if (pkt->stream_index == video_stream_index && video_callback != nullptr) {
917 video_callback(pkt.get(), format_ctx->streams[video_stream_index]->time_base);
919 if (pkt->stream_index == video_stream_index && global_flags.transcode_video) {
920 if (avcodec_send_packet(video_codec_ctx, pkt.get()) < 0) {
921 fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
923 return AVFrameWithDeleter(nullptr);
925 } else if (pkt->stream_index == audio_stream_index && global_flags.transcode_audio) {
927 if (avcodec_send_packet(audio_codec_ctx, pkt.get()) < 0) {
928 fprintf(stderr, "%s: Cannot send packet to audio codec.\n", pathname.c_str());
930 return AVFrameWithDeleter(nullptr);
932 } else if (pkt->stream_index == subtitle_stream_index) {
933 last_subtitle = string(reinterpret_cast<const char *>(pkt->data), pkt->size);
934 has_last_subtitle = true;
937 eof = true; // Or error, but ignore that for the time being.
940 // Decode audio, if any.
943 int err = avcodec_receive_frame(audio_codec_ctx, audio_avframe.get());
945 if (*audio_pts == -1) {
946 *audio_pts = audio_avframe->pts;
948 convert_audio(audio_avframe.get(), audio_frame, audio_format);
949 } else if (err == AVERROR(EAGAIN)) {
952 fprintf(stderr, "%s: Cannot receive frame from audio codec.\n", pathname.c_str());
954 return AVFrameWithDeleter(nullptr);
959 // Decode video, if we have a frame.
960 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
962 if (video_avframe->format == AV_PIX_FMT_VAAPI ||
963 video_avframe->format == AV_PIX_FMT_VDPAU) {
964 // Get the frame down to the CPU. (TODO: See if we can keep it
965 // on the GPU all the way, since it will be going up again later.
966 // However, this only works if the OpenGL GPU is the same one.)
967 AVFrameWithDeleter sw_frame = av_frame_alloc_unique();
968 int err = av_hwframe_transfer_data(sw_frame.get(), video_avframe.get(), 0);
970 fprintf(stderr, "%s: Cannot transfer hardware video frame to software.\n", pathname.c_str());
972 return AVFrameWithDeleter(nullptr);
974 sw_frame->pts = video_avframe->pts;
975 sw_frame->pkt_duration = video_avframe->pkt_duration;
976 video_avframe = move(sw_frame);
978 frame_finished = true;
980 } else if (err != AVERROR(EAGAIN)) {
981 fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
983 return AVFrameWithDeleter(nullptr);
988 return video_avframe;
990 return AVFrameWithDeleter(nullptr);
993 void FFmpegCapture::convert_audio(const AVFrame *audio_avframe, FrameAllocator::Frame *audio_frame, AudioFormat *audio_format)
995 // Decide on a format. If there already is one in this audio frame,
996 // we're pretty much forced to use it. If not, we try to find an exact match.
997 // If that still doesn't work, we default to 32-bit signed chunked
998 // (float would be nice, but there's really no way to signal that yet).
999 AVSampleFormat dst_format;
1000 if (audio_format->bits_per_sample == 0) {
1001 switch (audio_avframe->format) {
1002 case AV_SAMPLE_FMT_S16:
1003 case AV_SAMPLE_FMT_S16P:
1004 audio_format->bits_per_sample = 16;
1005 dst_format = AV_SAMPLE_FMT_S16;
1007 case AV_SAMPLE_FMT_S32:
1008 case AV_SAMPLE_FMT_S32P:
1010 audio_format->bits_per_sample = 32;
1011 dst_format = AV_SAMPLE_FMT_S32;
1014 } else if (audio_format->bits_per_sample == 16) {
1015 dst_format = AV_SAMPLE_FMT_S16;
1016 } else if (audio_format->bits_per_sample == 32) {
1017 dst_format = AV_SAMPLE_FMT_S32;
1021 audio_format->num_channels = 2;
1023 AVChannelLayout channel_layout = audio_avframe->ch_layout;
1024 if (!av_channel_layout_check(&channel_layout) ||
1025 channel_layout.order == AV_CHANNEL_ORDER_UNSPEC) {
1026 av_channel_layout_default(&channel_layout, audio_avframe->ch_layout.nb_channels);
1029 if (resampler == nullptr ||
1030 audio_avframe->format != last_src_format ||
1031 dst_format != last_dst_format ||
1032 av_channel_layout_compare(&channel_layout, &last_channel_layout) != 0||
1033 audio_avframe->sample_rate != last_sample_rate) {
1034 // TODO: When we get C++20, use AV_CHANNEL_LAYOUT_STEREO_DOWNMIX.
1035 AVChannelLayout stereo_downmix;
1036 stereo_downmix.order = AV_CHANNEL_ORDER_NATIVE;
1037 stereo_downmix.nb_channels = 2;
1038 stereo_downmix.u.mask = AV_CH_LAYOUT_STEREO_DOWNMIX;
1040 swr_free(&resampler);
1041 resampler = nullptr;
1042 int err = swr_alloc_set_opts2(&resampler,
1043 /*out_ch_layout=*/&stereo_downmix,
1044 /*out_sample_fmt=*/dst_format,
1045 /*out_sample_rate=*/OUTPUT_FREQUENCY,
1046 /*in_ch_layout=*/&channel_layout,
1047 /*in_sample_fmt=*/AVSampleFormat(audio_avframe->format),
1048 /*in_sample_rate=*/audio_avframe->sample_rate,
1050 /*log_ctx=*/nullptr);
1052 if (err != 0 || resampler == nullptr) {
1053 fprintf(stderr, "Allocating resampler failed.\n");
1057 if (swr_init(resampler) < 0) {
1058 fprintf(stderr, "Could not open resample context.\n");
1062 last_src_format = AVSampleFormat(audio_avframe->format);
1063 last_dst_format = dst_format;
1064 last_channel_layout = channel_layout;
1065 last_sample_rate = audio_avframe->sample_rate;
1068 size_t bytes_per_sample = (audio_format->bits_per_sample / 8) * 2;
1069 size_t num_samples_room = (audio_frame->size - audio_frame->len) / bytes_per_sample;
1071 uint8_t *data = audio_frame->data + audio_frame->len;
1072 int out_samples = swr_convert(resampler, &data, num_samples_room,
1073 const_cast<const uint8_t **>(audio_avframe->data), audio_avframe->nb_samples);
1074 if (out_samples < 0) {
1075 fprintf(stderr, "Audio conversion failed.\n");
1079 audio_frame->len += out_samples * bytes_per_sample;
1082 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
1084 VideoFormat video_format;
1085 video_format.width = frame_width(frame);
1086 video_format.height = frame_height(frame);
1087 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1088 video_format.stride = frame_width(frame) * 4;
1089 } else if (pixel_format == FFmpegCapture::PixelFormat_NV12) {
1090 video_format.stride = frame_width(frame);
1092 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1093 video_format.stride = frame_width(frame);
1095 video_format.frame_rate_nom = video_timebase.den;
1096 video_format.frame_rate_den = frame->pkt_duration * video_timebase.num;
1097 video_format.has_signal = true;
1098 video_format.is_connected = true;
1099 return video_format;
1102 UniqueFrame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
1106 UniqueFrame video_frame(video_frame_allocator->alloc_frame());
1107 if (video_frame->data == nullptr) {
1111 if (sws_ctx == nullptr ||
1112 sws_last_width != frame->width ||
1113 sws_last_height != frame->height ||
1114 sws_last_src_format != frame->format) {
1115 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
1117 sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
1118 frame_width(frame), frame_height(frame), sws_dst_format,
1119 SWS_BICUBIC, nullptr, nullptr, nullptr));
1120 sws_last_width = frame->width;
1121 sws_last_height = frame->height;
1122 sws_last_src_format = frame->format;
1124 if (sws_ctx == nullptr) {
1125 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
1130 uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
1131 int linesizes[4] = { 0, 0, 0, 0 };
1132 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1133 pic_data[0] = video_frame->data;
1134 linesizes[0] = frame_width(frame) * 4;
1135 video_frame->len = (frame_width(frame) * 4) * frame_height(frame);
1136 } else if (pixel_format == PixelFormat_NV12) {
1137 pic_data[0] = video_frame->data;
1138 linesizes[0] = frame_width(frame);
1140 pic_data[1] = pic_data[0] + frame_width(frame) * frame_height(frame);
1141 linesizes[1] = frame_width(frame);
1143 video_frame->len = (frame_width(frame) * 2) * frame_height(frame);
1145 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
1146 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame, is_mjpeg, &last_colorspace, &last_chroma_location);
1148 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1149 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
1151 int chroma_width = AV_CEIL_RSHIFT(int(frame_width(frame)), desc->log2_chroma_w);
1152 int chroma_height = AV_CEIL_RSHIFT(int(frame_height(frame)), desc->log2_chroma_h);
1154 pic_data[0] = video_frame->data;
1155 linesizes[0] = frame_width(frame);
1157 pic_data[1] = pic_data[0] + frame_width(frame) * frame_height(frame);
1158 linesizes[1] = chroma_width;
1160 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
1161 linesizes[2] = chroma_width;
1163 video_frame->len = frame_width(frame) * frame_height(frame) + 2 * chroma_width * chroma_height;
1165 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame, is_mjpeg, &last_colorspace, &last_chroma_location);
1168 // FIXME: Currently, if the video is too high-res for one of the allocated
1169 // frames, we simply refuse to scale it here to avoid crashes. It would be better
1170 // if we could somehow signal getting larger frames, especially as 4K is a thing now.
1171 if (video_frame->len > FRAME_SIZE) {
1172 fprintf(stderr, "%s: Decoded frame would be larger than supported FRAME_SIZE (%zu > %u), not decoding.\n", pathname.c_str(), video_frame->len, FRAME_SIZE);
1177 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
1182 int FFmpegCapture::interrupt_cb_thunk(void *opaque)
1184 return reinterpret_cast<FFmpegCapture *>(opaque)->interrupt_cb();
1187 int FFmpegCapture::interrupt_cb()
1189 // If ten seconds is gone without anything happening, we assume that
1190 // we are in a network stream that died and FFmpeg just didn't
1191 // pick it up (or perhaps it just hung, keeping the connection open).
1192 // Called back approximately every 100 ms if something is hanging,
1193 // so we get more than enough accuracy for our purposes.
1194 if (!should_interrupt && frame_timeout_valid &&
1195 duration<double>(steady_clock::now() - frame_timeout_started).count() >= 10.0) {
1196 string filename_copy;
1198 lock_guard<mutex> lock(filename_mu);
1199 filename_copy = filename;
1201 fprintf(stderr, "%s: No frame for more than 10 seconds, restarting stream.\n", filename.c_str());
1202 should_interrupt = true;
1204 return should_interrupt.load();
1207 unsigned FFmpegCapture::frame_width(const AVFrame *frame) const
1210 return frame->width;
1216 unsigned FFmpegCapture::frame_height(const AVFrame *frame) const
1219 return frame->height;
1226 int FFmpegCapture::read_srt_thunk(void *opaque, uint8_t *buf, int buf_size)
1228 return reinterpret_cast<FFmpegCapture *>(opaque)->read_srt(buf, buf_size);
1231 int FFmpegCapture::read_srt(uint8_t *buf, int buf_size)
1233 SRT_MSGCTRL mc = srt_msgctrl_default;
1234 return srt_recvmsg2(srt_sock, reinterpret_cast<char *>(buf), buf_size, &mc);