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"
47 #define FRAME_SIZE (8 << 20) // 8 MB.
50 using namespace std::chrono;
51 using namespace bmusb;
52 using namespace movit;
53 using namespace Eigen;
57 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)
59 const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
60 return origin + duration_cast<steady_clock::duration>(pts / rate);
63 bool changed_since(const std::string &pathname, const timespec &ts)
69 if (stat(pathname.c_str(), &buf) != 0) {
70 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
73 return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
76 bool is_full_range(const AVPixFmtDescriptor *desc)
78 // This is horrible, but there's no better way that I know of.
79 return (strchr(desc->name, 'j') != nullptr);
82 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
84 if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
85 return AV_PIX_FMT_BGRA;
87 if (dst_format_type == FFmpegCapture::PixelFormat_NV12) {
88 return AV_PIX_FMT_NV12;
91 assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
93 // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
94 // and be done with it. It's too strange to spend a lot of time on.
95 // (Let's hope there's no alpha.)
96 const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
97 if (src_desc == nullptr ||
98 src_desc->nb_components != 3 ||
99 (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
100 return AV_PIX_FMT_YUV444P;
103 // The best for us would be Cb and Cr together if possible,
104 // but FFmpeg doesn't support that except in the special case of
105 // NV12, so we need to go to planar even for the case of NV12.
106 // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
107 // that matches in color range. (This will also include the case of
108 // the source format already being acceptable.)
109 bool src_full_range = is_full_range(src_desc);
110 const char *best_format = "yuv444p";
111 unsigned best_score = numeric_limits<unsigned>::max();
112 for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
114 desc = av_pix_fmt_desc_next(desc)) {
115 // Find planar Y'CbCr formats only.
116 if (desc->nb_components != 3) continue;
117 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
118 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
119 if (desc->comp[0].plane != 0 ||
120 desc->comp[1].plane != 1 ||
121 desc->comp[2].plane != 2) continue;
123 // 8-bit formats only.
124 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
125 if (desc->comp[0].depth != 8) continue;
127 // Same or better chroma resolution only.
128 int chroma_w_diff = desc->log2_chroma_w - src_desc->log2_chroma_w;
129 int chroma_h_diff = desc->log2_chroma_h - src_desc->log2_chroma_h;
130 if (chroma_w_diff < 0 || chroma_h_diff < 0)
133 // Matching full/limited range only.
134 if (is_full_range(desc) != src_full_range)
137 // Pick something with as little excess chroma resolution as possible.
138 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
139 if (score < best_score) {
141 best_format = desc->name;
144 return av_get_pix_fmt(best_format);
147 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame, bool is_mjpeg, AVColorSpace *last_colorspace, AVChromaLocation *last_chroma_location)
150 AVColorSpace colorspace = frame->colorspace;
151 switch (colorspace) {
152 case AVCOL_SPC_BT709:
153 format.luma_coefficients = YCBCR_REC_709;
155 case AVCOL_SPC_BT470BG:
156 case AVCOL_SPC_SMPTE170M:
157 case AVCOL_SPC_SMPTE240M:
158 format.luma_coefficients = YCBCR_REC_601;
160 case AVCOL_SPC_BT2020_NCL:
161 format.luma_coefficients = YCBCR_REC_2020;
163 case AVCOL_SPC_UNSPECIFIED:
164 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
167 if (colorspace != *last_colorspace) {
168 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
171 format.luma_coefficients = YCBCR_REC_709;
174 *last_colorspace = colorspace;
176 format.full_range = is_full_range(desc);
177 format.num_levels = 1 << desc->comp[0].depth;
178 format.chroma_subsampling_x = 1 << desc->log2_chroma_w;
179 format.chroma_subsampling_y = 1 << desc->log2_chroma_h;
181 switch (frame->chroma_location) {
182 case AVCHROMA_LOC_LEFT:
183 format.cb_x_position = 0.0;
184 format.cb_y_position = 0.5;
186 case AVCHROMA_LOC_CENTER:
187 format.cb_x_position = 0.5;
188 format.cb_y_position = 0.5;
190 case AVCHROMA_LOC_TOPLEFT:
191 format.cb_x_position = 0.0;
192 format.cb_y_position = 0.0;
194 case AVCHROMA_LOC_TOP:
195 format.cb_x_position = 0.5;
196 format.cb_y_position = 0.0;
198 case AVCHROMA_LOC_BOTTOMLEFT:
199 format.cb_x_position = 0.0;
200 format.cb_y_position = 1.0;
202 case AVCHROMA_LOC_BOTTOM:
203 format.cb_x_position = 0.5;
204 format.cb_y_position = 1.0;
207 if (frame->chroma_location != *last_chroma_location) {
208 fprintf(stderr, "Unknown chroma location coefficient enum %d from FFmpeg; choosing center.\n",
209 frame->chroma_location);
211 format.cb_x_position = 0.5;
212 format.cb_y_position = 0.5;
215 *last_chroma_location = frame->chroma_location;
217 if (is_mjpeg && !format.full_range) {
218 // Limited-range MJPEG is only detected by FFmpeg whenever a special
219 // JPEG comment is set, which means that in practice, the stream is
220 // almost certainly generated by Futatabi. Override FFmpeg's forced
221 // MJPEG defaults (it disregards the values set in the mux) with what
223 format.luma_coefficients = YCBCR_REC_709;
224 format.cb_x_position = 0.0;
225 format.cb_y_position = 0.5;
228 format.cr_x_position = format.cb_x_position;
229 format.cr_y_position = format.cb_y_position;
233 RGBTriplet get_neutral_color(AVDictionary *metadata)
235 if (metadata == nullptr) {
236 return RGBTriplet(1.0f, 1.0f, 1.0f);
238 AVDictionaryEntry *entry = av_dict_get(metadata, "WhitePoint", nullptr, 0);
239 if (entry == nullptr) {
240 return RGBTriplet(1.0f, 1.0f, 1.0f);
243 unsigned x_nom, x_den, y_nom, y_den;
244 if (sscanf(entry->value, " %u:%u , %u:%u", &x_nom, &x_den, &y_nom, &y_den) != 4) {
245 fprintf(stderr, "WARNING: Unable to parse white point '%s', using default white point\n", entry->value);
246 return RGBTriplet(1.0f, 1.0f, 1.0f);
249 double x = double(x_nom) / x_den;
250 double y = double(y_nom) / y_den;
251 double z = 1.0 - x - y;
253 Matrix3d rgb_to_xyz_matrix = movit::ColorspaceConversionEffect::get_xyz_matrix(COLORSPACE_sRGB);
254 Vector3d rgb = rgb_to_xyz_matrix.inverse() * Vector3d(x, y, z);
256 return RGBTriplet(rgb[0], rgb[1], rgb[2]);
261 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
262 : filename(filename), width(width), height(height), video_timebase{1, 1}
264 description = "Video: " + filename;
266 last_frame = steady_clock::now();
268 avformat_network_init(); // In case someone wants this.
272 FFmpegCapture::FFmpegCapture(int srt_sock, const string &stream_id)
273 : srt_sock(srt_sock),
274 width(0), // Don't resize; SRT streams typically have stable resolution, and should behave much like regular cards in general.
276 pixel_format(bmusb::PixelFormat_8BitYCbCrPlanar),
279 if (stream_id.empty()) {
280 description = "SRT stream";
282 description = stream_id;
284 play_as_fast_as_possible = true;
286 last_frame = steady_clock::now();
290 FFmpegCapture::~FFmpegCapture()
292 if (has_dequeue_callbacks) {
293 dequeue_cleanup_callback();
295 swr_free(&resampler);
297 if (srt_sock != -1) {
303 void FFmpegCapture::configure_card()
305 if (video_frame_allocator == nullptr) {
306 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
307 set_video_frame_allocator(owned_video_frame_allocator.get());
309 if (audio_frame_allocator == nullptr) {
310 // Audio can come out in pretty large chunks, so increase from the default 1 MB.
311 owned_audio_frame_allocator.reset(new MallocFrameAllocator(1 << 20, NUM_QUEUED_AUDIO_FRAMES));
312 set_audio_frame_allocator(owned_audio_frame_allocator.get());
316 void FFmpegCapture::start_bm_capture()
322 producer_thread_should_quit.unquit();
323 producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
326 void FFmpegCapture::stop_dequeue_thread()
332 producer_thread_should_quit.quit();
333 producer_thread.join();
336 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
338 // Note: This will never really be shown in the UI.
342 snprintf(buf, sizeof(buf), "%ux%u", sws_last_width, sws_last_height);
345 mode.autodetect = false;
346 mode.width = sws_last_width;
347 mode.height = sws_last_height;
348 mode.frame_rate_num = 60;
349 mode.frame_rate_den = 1;
350 mode.interlaced = false;
352 return {{ 0, mode }};
355 void FFmpegCapture::producer_thread_func()
357 char thread_name[16];
358 snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
359 pthread_setname_np(pthread_self(), thread_name);
361 while (!producer_thread_should_quit.should_quit()) {
362 string filename_copy;
364 lock_guard<mutex> lock(filename_mu);
365 filename_copy = filename;
369 if (srt_sock == -1) {
370 pathname = search_for_file(filename_copy);
372 pathname = description;
374 if (pathname.empty()) {
375 send_disconnected_frame();
379 producer_thread_should_quit.sleep_for(seconds(1));
380 fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename_copy.c_str());
383 should_interrupt = false;
384 if (!play_video(pathname)) {
386 send_disconnected_frame();
390 fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
391 producer_thread_should_quit.sleep_for(seconds(1));
396 send_disconnected_frame();
400 // Probably just EOF, will exit the loop above on next test.
403 if (has_dequeue_callbacks) {
404 dequeue_cleanup_callback();
405 has_dequeue_callbacks = false;
409 void FFmpegCapture::send_disconnected_frame()
411 // Send an empty frame to signal that we have no signal anymore.
412 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
413 size_t frame_width = width == 0 ? global_flags.width : width;
414 size_t frame_height = height == 0 ? global_flags.height : height;
415 if (video_frame.data) {
416 VideoFormat video_format;
417 video_format.width = frame_width;
418 video_format.height = frame_height;
419 video_format.frame_rate_nom = 60;
420 video_format.frame_rate_den = 1;
421 video_format.is_connected = false;
422 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
423 video_format.stride = frame_width * 4;
424 video_frame.len = frame_width * frame_height * 4;
425 memset(video_frame.data, 0, video_frame.len);
427 video_format.stride = frame_width;
428 current_frame_ycbcr_format.luma_coefficients = YCBCR_REC_709;
429 current_frame_ycbcr_format.full_range = true;
430 current_frame_ycbcr_format.num_levels = 256;
431 current_frame_ycbcr_format.chroma_subsampling_x = 2;
432 current_frame_ycbcr_format.chroma_subsampling_y = 2;
433 current_frame_ycbcr_format.cb_x_position = 0.0f;
434 current_frame_ycbcr_format.cb_y_position = 0.0f;
435 current_frame_ycbcr_format.cr_x_position = 0.0f;
436 current_frame_ycbcr_format.cr_y_position = 0.0f;
437 video_frame.len = frame_width * frame_height * 2;
438 memset(video_frame.data, 0, frame_width * frame_height);
439 memset(video_frame.data + frame_width * frame_height, 128, frame_width * frame_height); // Valid for both NV12 and planar.
442 if (frame_callback != nullptr) {
443 frame_callback(-1, AVRational{1, TIMEBASE}, -1, AVRational{1, TIMEBASE}, timecode++,
444 video_frame, /*video_offset=*/0, video_format,
445 FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
447 last_frame_was_connected = false;
452 if (card_disconnected_callback != nullptr) {
453 card_disconnected_callback();
458 template<AVHWDeviceType type>
459 AVPixelFormat get_hw_format(AVCodecContext *ctx, const AVPixelFormat *fmt)
461 bool found_config_of_right_type = false;
462 for (int i = 0;; ++i) { // Termination condition inside loop.
463 const AVCodecHWConfig *config = avcodec_get_hw_config(ctx->codec, i);
464 if (config == nullptr) { // End of list.
467 if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) ||
468 config->device_type != type) {
469 // Not interesting for us.
473 // We have a config of the right type, but does it actually support
474 // the pixel format we want? (Seemingly, FFmpeg's way of signaling errors
475 // is to just replace the pixel format with a software-decoded one,
477 found_config_of_right_type = true;
478 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
479 if (config->pix_fmt == *fmt_ptr) {
480 fprintf(stderr, "Initialized '%s' hardware decoding for codec '%s'.\n",
481 av_hwdevice_get_type_name(type), ctx->codec->name);
482 return config->pix_fmt;
485 fprintf(stderr, "Decoder '%s' supports only these pixel formats:", ctx->codec->name);
486 unordered_set<AVPixelFormat> seen;
487 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
488 if (!seen.count(*fmt_ptr)) {
489 fprintf(stderr, " %s", av_get_pix_fmt_name(*fmt_ptr));
490 seen.insert(*fmt_ptr);
493 fprintf(stderr, " (wanted %s for hardware acceleration)\n", av_get_pix_fmt_name(config->pix_fmt));
497 if (!found_config_of_right_type) {
498 fprintf(stderr, "Decoder '%s' does not support device type '%s'.\n", ctx->codec->name, av_hwdevice_get_type_name(type));
501 // We found no VA-API formats, so take the best software format.
505 bool FFmpegCapture::play_video(const string &pathname)
507 // Note: Call before open, not after; otherwise, there's a race.
508 // (There is now, too, but it tips the correct way. We could use fstat()
509 // if we had the file descriptor.)
510 timespec last_modified;
512 if (stat(pathname.c_str(), &buf) != 0) {
513 // Probably some sort of protocol, so can't stat.
514 last_modified.tv_sec = -1;
516 last_modified = buf.st_mtim;
518 last_colorspace = static_cast<AVColorSpace>(-1);
519 last_chroma_location = static_cast<AVChromaLocation>(-1);
521 AVFormatContextWithCloser format_ctx;
522 if (srt_sock == -1) {
524 format_ctx = avformat_open_input_unique(pathname.c_str(), /*fmt=*/nullptr,
526 AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
529 // SRT socket, already opened.
530 const AVInputFormat *mpegts_fmt = av_find_input_format("mpegts");
531 format_ctx = avformat_open_input_unique(&FFmpegCapture::read_srt_thunk, this,
532 mpegts_fmt, /*options=*/nullptr,
533 AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
538 if (format_ctx == nullptr) {
539 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
543 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
544 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
548 int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
549 if (video_stream_index == -1) {
550 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
554 int audio_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_AUDIO);
555 int subtitle_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_SUBTITLE);
556 has_last_subtitle = false;
558 // Open video decoder.
559 const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
560 const AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
562 video_timebase = format_ctx->streams[video_stream_index]->time_base;
563 AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
564 if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
565 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
568 if (video_codec == nullptr) {
569 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
573 // Seemingly, it's not too easy to make something that just initializes
574 // “whatever goes”, so we don't get CUDA or VULKAN or whatever here
575 // without enumerating through several different types.
576 // VA-API and VDPAU will do for now. We prioritize VDPAU for the
577 // simple reason that there's a VA-API-via-VDPAU emulation for NVidia
578 // cards that seems to work, but just hangs when trying to transfer the frame.
580 // Note that we don't actually check codec support beforehand,
581 // so if you have a low-end VDPAU device but a high-end VA-API device,
582 // you lose out on the extra codec support from the latter.
583 AVBufferRef *hw_device_ctx = nullptr;
584 if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VDPAU, nullptr, nullptr, 0) >= 0) {
585 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
586 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VDPAU>;
587 } else if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, nullptr, nullptr, 0) >= 0) {
588 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
589 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VAAPI>;
591 fprintf(stderr, "Failed to initialize VA-API or VDPAU for FFmpeg acceleration. Decoding video in software.\n");
594 if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
595 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
598 unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
599 video_codec_ctx.get(), avcodec_close);
601 // Used in decode_ycbcr_format().
602 is_mjpeg = video_codecpar->codec_id == AV_CODEC_ID_MJPEG;
604 // Open audio decoder, if we have audio.
605 AVCodecContextWithDeleter audio_codec_ctx;
606 if (audio_stream_index != -1) {
607 audio_codec_ctx = avcodec_alloc_context3_unique(nullptr);
608 const AVCodecParameters *audio_codecpar = format_ctx->streams[audio_stream_index]->codecpar;
609 audio_timebase = format_ctx->streams[audio_stream_index]->time_base;
610 if (avcodec_parameters_to_context(audio_codec_ctx.get(), audio_codecpar) < 0) {
611 fprintf(stderr, "%s: Cannot fill audio codec parameters\n", pathname.c_str());
614 const AVCodec *audio_codec = avcodec_find_decoder(audio_codecpar->codec_id);
615 if (audio_codec == nullptr) {
616 fprintf(stderr, "%s: Cannot find audio decoder\n", pathname.c_str());
619 if (avcodec_open2(audio_codec_ctx.get(), audio_codec, nullptr) < 0) {
620 fprintf(stderr, "%s: Cannot open audio decoder\n", pathname.c_str());
624 unique_ptr<AVCodecContext, decltype(avcodec_close)*> audio_codec_ctx_cleanup(
625 audio_codec_ctx.get(), avcodec_close);
630 bool first_frame = true;
631 int consecutive_errors = 0;
632 while (!producer_thread_should_quit.should_quit()) {
633 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
636 if (should_interrupt.load()) {
637 // Check as a failsafe, so that we don't need to rely on avio if we don't have to.
640 UniqueFrame audio_frame = audio_frame_allocator->alloc_frame();
641 AudioFormat audio_format;
645 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(), audio_codec_ctx.get(),
646 pathname, video_stream_index, audio_stream_index, subtitle_stream_index, audio_frame.get(), &audio_format, &audio_pts, &error);
648 if (++consecutive_errors >= 100) {
649 fprintf(stderr, "More than 100 consecutive video frames, aborting playback.\n");
655 consecutive_errors = 0;
657 if (frame == nullptr) {
658 // EOF. Loop back to the start if we can.
659 if (format_ctx->pb != nullptr && format_ctx->pb->seekable == 0) {
660 // Not seekable (but seemingly, sometimes av_seek_frame() would return 0 anyway,
664 if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
665 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
668 if (video_codec_ctx != nullptr) {
669 avcodec_flush_buffers(video_codec_ctx.get());
671 if (audio_codec_ctx != nullptr) {
672 avcodec_flush_buffers(audio_codec_ctx.get());
674 // If the file has changed since last time, return to get it reloaded.
675 // Note that depending on how you move the file into place, you might
676 // end up corrupting the one you're already playing, so this path
677 // might not trigger.
678 if (changed_since(pathname, last_modified)) {
685 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
686 if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
687 // Invalid frame rate; try constructing it from the previous frame length.
688 // (This is especially important if we are the master card, for SRT,
689 // since it affects audio. Not all senders have good timebases
690 // (e.g., Larix rounds first to timebase 1000 and then multiplies by
691 // 90 from there, it seems), but it's much better to have an oscillating
692 // value than just locking at 60.
693 if (last_pts != 0 && frame->pts > last_pts) {
694 int64_t pts_diff = frame->pts - last_pts;
695 video_format.frame_rate_nom = video_timebase.den;
696 video_format.frame_rate_den = video_timebase.num * pts_diff;
698 video_format.frame_rate_nom = 60;
699 video_format.frame_rate_den = 1;
702 UniqueFrame video_frame = make_video_frame(frame.get(), pathname, &error);
708 if (last_pts == 0 && pts_origin == 0) {
709 pts_origin = frame->pts;
711 steady_clock::time_point now = steady_clock::now();
712 if (play_as_fast_as_possible) {
713 video_frame->received_timestamp = now;
714 audio_frame->received_timestamp = now;
715 next_frame_start = now;
717 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
718 if (first_frame && last_frame_was_connected) {
719 // If reconnect took more than one second, this is probably a live feed,
720 // and we should reset the resampler. (Or the rate is really, really low,
721 // in which case a reset on the first frame is fine anyway.)
722 if (duration<double>(next_frame_start - last_frame).count() >= 1.0) {
723 last_frame_was_connected = false;
726 video_frame->received_timestamp = next_frame_start;
728 // The easiest way to get all the rate conversions etc. right is to move the
729 // audio PTS into the video PTS timebase and go from there. (We'll get some
730 // rounding issues, but they should not be a big problem.)
731 int64_t audio_pts_as_video_pts = av_rescale_q(audio_pts, audio_timebase, video_timebase);
732 audio_frame->received_timestamp = compute_frame_start(audio_pts_as_video_pts, pts_origin, video_timebase, start, rate);
734 if (audio_frame->len != 0) {
735 // The received timestamps in Nageru are measured after we've just received the frame.
736 // However, pts (especially audio pts) is at the _beginning_ of the frame.
737 // If we have locked audio, the distinction doesn't really matter, as pts is
738 // on a relative scale and a fixed offset is fine. But if we don't, we will have
739 // a different number of samples each time, which will cause huge audio jitter
740 // and throw off the resampler.
742 // In a sense, we should have compensated by adding the frame and audio lengths
743 // to video_frame->received_timestamp and audio_frame->received_timestamp respectively,
744 // but that would mean extra waiting in sleep_until(). All we need is that they
745 // are correct relative to each other, though (and to the other frames we send),
746 // so just align the end of the audio frame, and we're fine.
747 size_t num_samples = (audio_frame->len * 8) / audio_format.bits_per_sample / audio_format.num_channels;
748 double offset = double(num_samples) / OUTPUT_FREQUENCY -
749 double(video_format.frame_rate_den) / video_format.frame_rate_nom;
750 audio_frame->received_timestamp += duration_cast<steady_clock::duration>(duration<double>(offset));
753 if (duration<double>(now - next_frame_start).count() >= 0.1) {
754 // If we don't have enough CPU to keep up, or if we have a live stream
755 // where the initial origin was somehow wrong, we could be behind indefinitely.
756 // In particular, this will give the audio resampler problems as it tries
757 // to speed up to reduce the delay, hitting the low end of the buffer every time.
758 fprintf(stderr, "%s: Playback %.0f ms behind, resetting time scale\n",
760 1e3 * duration<double>(now - next_frame_start).count());
761 pts_origin = frame->pts;
762 start = next_frame_start = now;
763 timecode += TYPICAL_FPS * 2 + 1;
766 bool finished_wakeup;
767 if (play_as_fast_as_possible) {
768 finished_wakeup = !producer_thread_should_quit.should_quit();
770 finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
772 if (finished_wakeup) {
773 if (audio_frame->len > 0) {
774 assert(audio_pts != -1);
776 if (!last_frame_was_connected) {
777 // We're recovering from an error (or really slow load, see above).
778 // Make sure to get the audio resampler reset. (This is a hack;
779 // ideally, the frame callback should just accept a way to signal
780 // audio discontinuity.)
781 timecode += TYPICAL_FPS * 2 + 1;
783 last_neutral_color = get_neutral_color(frame->metadata);
784 if (frame_callback != nullptr) {
785 frame_callback(frame->pts, video_timebase, audio_pts, audio_timebase, timecode++,
786 video_frame.get_and_release(), 0, video_format,
787 audio_frame.get_and_release(), 0, audio_format);
790 last_frame = steady_clock::now();
791 last_frame_was_connected = true;
794 if (producer_thread_should_quit.should_quit()) break;
796 bool rewound = false;
797 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
800 // If we just rewound, drop this frame on the floor and be done.
804 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
805 // but if it's now in the past, we'll reset the origin, so that we don't
806 // generate a huge backlog of frames that we need to run through quickly.
807 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
808 steady_clock::time_point now = steady_clock::now();
809 if (next_frame_start < now) {
810 pts_origin = frame->pts;
811 start = next_frame_start = now;
815 last_pts = frame->pts;
820 void FFmpegCapture::internal_rewind()
822 pts_origin = last_pts = 0;
823 start = next_frame_start = steady_clock::now();
826 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
828 // Process any queued commands from other threads.
829 vector<QueuedCommand> commands;
831 lock_guard<mutex> lock(queue_mu);
832 swap(commands, command_queue);
834 for (const QueuedCommand &cmd : commands) {
835 switch (cmd.command) {
836 case QueuedCommand::REWIND:
837 if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
838 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
840 // If the file has changed since last time, return to get it reloaded.
841 // Note that depending on how you move the file into place, you might
842 // end up corrupting the one you're already playing, so this path
843 // might not trigger.
844 if (changed_since(pathname, last_modified)) {
848 if (rewound != nullptr) {
853 case QueuedCommand::CHANGE_RATE:
854 // Change the origin to the last played frame.
855 start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
856 pts_origin = last_pts;
858 play_as_fast_as_possible = (rate >= 10.0);
869 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
870 const std::string &pathname, int video_stream_index, int audio_stream_index, int subtitle_stream_index,
871 FrameAllocator::Frame *audio_frame, AudioFormat *audio_format, int64_t *audio_pts, bool *error)
875 // Read packets until we have a frame or there are none left.
876 bool frame_finished = false;
877 AVFrameWithDeleter audio_avframe = av_frame_alloc_unique();
878 AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
881 bool has_audio = false;
884 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
885 &pkt, av_packet_unref);
886 av_init_packet(&pkt);
889 if (av_read_frame(format_ctx, &pkt) == 0) {
890 if (pkt.stream_index == audio_stream_index && audio_callback != nullptr) {
891 audio_callback(&pkt, format_ctx->streams[audio_stream_index]->time_base);
893 if (pkt.stream_index == video_stream_index && video_callback != nullptr) {
894 video_callback(&pkt, format_ctx->streams[video_stream_index]->time_base);
896 if (pkt.stream_index == video_stream_index && global_flags.transcode_video) {
897 if (avcodec_send_packet(video_codec_ctx, &pkt) < 0) {
898 fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
900 return AVFrameWithDeleter(nullptr);
902 } else if (pkt.stream_index == audio_stream_index && global_flags.transcode_audio) {
904 if (avcodec_send_packet(audio_codec_ctx, &pkt) < 0) {
905 fprintf(stderr, "%s: Cannot send packet to audio codec.\n", pathname.c_str());
907 return AVFrameWithDeleter(nullptr);
909 } else if (pkt.stream_index == subtitle_stream_index) {
910 last_subtitle = string(reinterpret_cast<const char *>(pkt.data), pkt.size);
911 has_last_subtitle = true;
914 eof = true; // Or error, but ignore that for the time being.
917 // Decode audio, if any.
920 int err = avcodec_receive_frame(audio_codec_ctx, audio_avframe.get());
922 if (*audio_pts == -1) {
923 *audio_pts = audio_avframe->pts;
925 convert_audio(audio_avframe.get(), audio_frame, audio_format);
926 } else if (err == AVERROR(EAGAIN)) {
929 fprintf(stderr, "%s: Cannot receive frame from audio codec.\n", pathname.c_str());
931 return AVFrameWithDeleter(nullptr);
936 // Decode video, if we have a frame.
937 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
939 if (video_avframe->format == AV_PIX_FMT_VAAPI ||
940 video_avframe->format == AV_PIX_FMT_VDPAU) {
941 // Get the frame down to the CPU. (TODO: See if we can keep it
942 // on the GPU all the way, since it will be going up again later.
943 // However, this only works if the OpenGL GPU is the same one.)
944 AVFrameWithDeleter sw_frame = av_frame_alloc_unique();
945 int err = av_hwframe_transfer_data(sw_frame.get(), video_avframe.get(), 0);
947 fprintf(stderr, "%s: Cannot transfer hardware video frame to software.\n", pathname.c_str());
949 return AVFrameWithDeleter(nullptr);
951 sw_frame->pts = video_avframe->pts;
952 sw_frame->pkt_duration = video_avframe->pkt_duration;
953 video_avframe = move(sw_frame);
955 frame_finished = true;
957 } else if (err != AVERROR(EAGAIN)) {
958 fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
960 return AVFrameWithDeleter(nullptr);
965 return video_avframe;
967 return AVFrameWithDeleter(nullptr);
970 void FFmpegCapture::convert_audio(const AVFrame *audio_avframe, FrameAllocator::Frame *audio_frame, AudioFormat *audio_format)
972 // Decide on a format. If there already is one in this audio frame,
973 // we're pretty much forced to use it. If not, we try to find an exact match.
974 // If that still doesn't work, we default to 32-bit signed chunked
975 // (float would be nice, but there's really no way to signal that yet).
976 AVSampleFormat dst_format;
977 if (audio_format->bits_per_sample == 0) {
978 switch (audio_avframe->format) {
979 case AV_SAMPLE_FMT_S16:
980 case AV_SAMPLE_FMT_S16P:
981 audio_format->bits_per_sample = 16;
982 dst_format = AV_SAMPLE_FMT_S16;
984 case AV_SAMPLE_FMT_S32:
985 case AV_SAMPLE_FMT_S32P:
987 audio_format->bits_per_sample = 32;
988 dst_format = AV_SAMPLE_FMT_S32;
991 } else if (audio_format->bits_per_sample == 16) {
992 dst_format = AV_SAMPLE_FMT_S16;
993 } else if (audio_format->bits_per_sample == 32) {
994 dst_format = AV_SAMPLE_FMT_S32;
998 audio_format->num_channels = 2;
1000 int64_t channel_layout = audio_avframe->channel_layout;
1001 if (channel_layout == 0) {
1002 channel_layout = av_get_default_channel_layout(audio_avframe->channels);
1005 if (resampler == nullptr ||
1006 audio_avframe->format != last_src_format ||
1007 dst_format != last_dst_format ||
1008 channel_layout != last_channel_layout ||
1009 audio_avframe->sample_rate != last_sample_rate) {
1010 swr_free(&resampler);
1011 resampler = swr_alloc_set_opts(nullptr,
1012 /*out_ch_layout=*/AV_CH_LAYOUT_STEREO_DOWNMIX,
1013 /*out_sample_fmt=*/dst_format,
1014 /*out_sample_rate=*/OUTPUT_FREQUENCY,
1015 /*in_ch_layout=*/channel_layout,
1016 /*in_sample_fmt=*/AVSampleFormat(audio_avframe->format),
1017 /*in_sample_rate=*/audio_avframe->sample_rate,
1019 /*log_ctx=*/nullptr);
1021 if (resampler == nullptr) {
1022 fprintf(stderr, "Allocating resampler failed.\n");
1026 if (swr_init(resampler) < 0) {
1027 fprintf(stderr, "Could not open resample context.\n");
1031 last_src_format = AVSampleFormat(audio_avframe->format);
1032 last_dst_format = dst_format;
1033 last_channel_layout = channel_layout;
1034 last_sample_rate = audio_avframe->sample_rate;
1037 size_t bytes_per_sample = (audio_format->bits_per_sample / 8) * 2;
1038 size_t num_samples_room = (audio_frame->size - audio_frame->len) / bytes_per_sample;
1040 uint8_t *data = audio_frame->data + audio_frame->len;
1041 int out_samples = swr_convert(resampler, &data, num_samples_room,
1042 const_cast<const uint8_t **>(audio_avframe->data), audio_avframe->nb_samples);
1043 if (out_samples < 0) {
1044 fprintf(stderr, "Audio conversion failed.\n");
1048 audio_frame->len += out_samples * bytes_per_sample;
1051 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
1053 VideoFormat video_format;
1054 video_format.width = frame_width(frame);
1055 video_format.height = frame_height(frame);
1056 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1057 video_format.stride = frame_width(frame) * 4;
1058 } else if (pixel_format == FFmpegCapture::PixelFormat_NV12) {
1059 video_format.stride = frame_width(frame);
1061 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1062 video_format.stride = frame_width(frame);
1064 video_format.frame_rate_nom = video_timebase.den;
1065 video_format.frame_rate_den = frame->pkt_duration * video_timebase.num;
1066 video_format.has_signal = true;
1067 video_format.is_connected = true;
1068 return video_format;
1071 UniqueFrame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
1075 UniqueFrame video_frame(video_frame_allocator->alloc_frame());
1076 if (video_frame->data == nullptr) {
1080 if (sws_ctx == nullptr ||
1081 sws_last_width != frame->width ||
1082 sws_last_height != frame->height ||
1083 sws_last_src_format != frame->format) {
1084 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
1086 sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
1087 frame_width(frame), frame_height(frame), sws_dst_format,
1088 SWS_BICUBIC, nullptr, nullptr, nullptr));
1089 sws_last_width = frame->width;
1090 sws_last_height = frame->height;
1091 sws_last_src_format = frame->format;
1093 if (sws_ctx == nullptr) {
1094 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
1099 uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
1100 int linesizes[4] = { 0, 0, 0, 0 };
1101 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
1102 pic_data[0] = video_frame->data;
1103 linesizes[0] = frame_width(frame) * 4;
1104 video_frame->len = (frame_width(frame) * 4) * frame_height(frame);
1105 } else if (pixel_format == PixelFormat_NV12) {
1106 pic_data[0] = video_frame->data;
1107 linesizes[0] = frame_width(frame);
1109 pic_data[1] = pic_data[0] + frame_width(frame) * frame_height(frame);
1110 linesizes[1] = frame_width(frame);
1112 video_frame->len = (frame_width(frame) * 2) * frame_height(frame);
1114 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
1115 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame, is_mjpeg, &last_colorspace, &last_chroma_location);
1117 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
1118 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
1120 int chroma_width = AV_CEIL_RSHIFT(int(frame_width(frame)), desc->log2_chroma_w);
1121 int chroma_height = AV_CEIL_RSHIFT(int(frame_height(frame)), desc->log2_chroma_h);
1123 pic_data[0] = video_frame->data;
1124 linesizes[0] = frame_width(frame);
1126 pic_data[1] = pic_data[0] + frame_width(frame) * frame_height(frame);
1127 linesizes[1] = chroma_width;
1129 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
1130 linesizes[2] = chroma_width;
1132 video_frame->len = frame_width(frame) * frame_height(frame) + 2 * chroma_width * chroma_height;
1134 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame, is_mjpeg, &last_colorspace, &last_chroma_location);
1136 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
1141 int FFmpegCapture::interrupt_cb_thunk(void *opaque)
1143 return reinterpret_cast<FFmpegCapture *>(opaque)->interrupt_cb();
1146 int FFmpegCapture::interrupt_cb()
1148 return should_interrupt.load();
1151 unsigned FFmpegCapture::frame_width(const AVFrame *frame) const
1154 return frame->width;
1160 unsigned FFmpegCapture::frame_height(const AVFrame *frame) const
1163 return frame->height;
1170 int FFmpegCapture::read_srt_thunk(void *opaque, uint8_t *buf, int buf_size)
1172 return reinterpret_cast<FFmpegCapture *>(opaque)->read_srt(buf, buf_size);
1175 int FFmpegCapture::read_srt(uint8_t *buf, int buf_size)
1177 SRT_MSGCTRL mc = srt_msgctrl_default;
1178 return srt_recvmsg2(srt_sock, reinterpret_cast<char *>(buf), buf_size, &mc);