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 <libswscale/swscale.h>
29 #include "bmusb/bmusb.h"
30 #include "ffmpeg_raii.h"
31 #include "ffmpeg_util.h"
33 #include "image_input.h"
36 #define FRAME_SIZE (8 << 20) // 8 MB.
39 using namespace std::chrono;
40 using namespace bmusb;
41 using namespace movit;
45 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)
47 const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
48 return origin + duration_cast<steady_clock::duration>(pts / rate);
51 bool changed_since(const std::string &pathname, const timespec &ts)
57 if (stat(pathname.c_str(), &buf) != 0) {
58 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
61 return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
64 bool is_full_range(const AVPixFmtDescriptor *desc)
66 // This is horrible, but there's no better way that I know of.
67 return (strchr(desc->name, 'j') != nullptr);
70 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
72 if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
73 return AV_PIX_FMT_BGRA;
75 if (dst_format_type == FFmpegCapture::PixelFormat_NV12) {
76 return AV_PIX_FMT_NV12;
79 assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
81 // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
82 // and be done with it. It's too strange to spend a lot of time on.
83 // (Let's hope there's no alpha.)
84 const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
85 if (src_desc == nullptr ||
86 src_desc->nb_components != 3 ||
87 (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
88 return AV_PIX_FMT_YUV444P;
91 // The best for us would be Cb and Cr together if possible,
92 // but FFmpeg doesn't support that except in the special case of
93 // NV12, so we need to go to planar even for the case of NV12.
94 // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
95 // that matches in color range. (This will also include the case of
96 // the source format already being acceptable.)
97 bool src_full_range = is_full_range(src_desc);
98 const char *best_format = "yuv444p";
99 unsigned best_score = numeric_limits<unsigned>::max();
100 for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
102 desc = av_pix_fmt_desc_next(desc)) {
103 // Find planar Y'CbCr formats only.
104 if (desc->nb_components != 3) continue;
105 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
106 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
107 if (desc->comp[0].plane != 0 ||
108 desc->comp[1].plane != 1 ||
109 desc->comp[2].plane != 2) continue;
111 // 8-bit formats only.
112 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
113 if (desc->comp[0].depth != 8) continue;
115 // Same or better chroma resolution only.
116 int chroma_w_diff = desc->log2_chroma_w - src_desc->log2_chroma_w;
117 int chroma_h_diff = desc->log2_chroma_h - src_desc->log2_chroma_h;
118 if (chroma_w_diff < 0 || chroma_h_diff < 0)
121 // Matching full/limited range only.
122 if (is_full_range(desc) != src_full_range)
125 // Pick something with as little excess chroma resolution as possible.
126 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
127 if (score < best_score) {
129 best_format = desc->name;
132 return av_get_pix_fmt(best_format);
135 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame)
138 AVColorSpace colorspace = av_frame_get_colorspace(frame);
139 switch (colorspace) {
140 case AVCOL_SPC_BT709:
141 format.luma_coefficients = YCBCR_REC_709;
143 case AVCOL_SPC_BT470BG:
144 case AVCOL_SPC_SMPTE170M:
145 case AVCOL_SPC_SMPTE240M:
146 format.luma_coefficients = YCBCR_REC_601;
148 case AVCOL_SPC_BT2020_NCL:
149 format.luma_coefficients = YCBCR_REC_2020;
151 case AVCOL_SPC_UNSPECIFIED:
152 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
155 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
157 format.luma_coefficients = YCBCR_REC_709;
161 format.full_range = is_full_range(desc);
162 format.num_levels = 1 << desc->comp[0].depth;
163 format.chroma_subsampling_x = 1 << desc->log2_chroma_w;
164 format.chroma_subsampling_y = 1 << desc->log2_chroma_h;
166 switch (frame->chroma_location) {
167 case AVCHROMA_LOC_LEFT:
168 format.cb_x_position = 0.0;
169 format.cb_y_position = 0.5;
171 case AVCHROMA_LOC_CENTER:
172 format.cb_x_position = 0.5;
173 format.cb_y_position = 0.5;
175 case AVCHROMA_LOC_TOPLEFT:
176 format.cb_x_position = 0.0;
177 format.cb_y_position = 0.0;
179 case AVCHROMA_LOC_TOP:
180 format.cb_x_position = 0.5;
181 format.cb_y_position = 0.0;
183 case AVCHROMA_LOC_BOTTOMLEFT:
184 format.cb_x_position = 0.0;
185 format.cb_y_position = 1.0;
187 case AVCHROMA_LOC_BOTTOM:
188 format.cb_x_position = 0.5;
189 format.cb_y_position = 1.0;
192 fprintf(stderr, "Unknown chroma location coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
193 frame->chroma_location);
194 format.cb_x_position = 0.5;
195 format.cb_y_position = 0.5;
199 format.cr_x_position = format.cb_x_position;
200 format.cr_y_position = format.cb_y_position;
206 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
207 : filename(filename), width(width), height(height), video_timebase{1, 1}
209 // Not really used for anything.
210 description = "Video: " + filename;
212 avformat_network_init(); // In case someone wants this.
215 FFmpegCapture::~FFmpegCapture()
217 if (has_dequeue_callbacks) {
218 dequeue_cleanup_callback();
222 void FFmpegCapture::configure_card()
224 if (video_frame_allocator == nullptr) {
225 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
226 set_video_frame_allocator(owned_video_frame_allocator.get());
228 if (audio_frame_allocator == nullptr) {
229 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
230 set_audio_frame_allocator(owned_audio_frame_allocator.get());
234 void FFmpegCapture::start_bm_capture()
240 producer_thread_should_quit.unquit();
241 producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
244 void FFmpegCapture::stop_dequeue_thread()
250 producer_thread_should_quit.quit();
251 producer_thread.join();
254 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
256 // Note: This will never really be shown in the UI.
260 snprintf(buf, sizeof(buf), "%ux%u", width, height);
263 mode.autodetect = false;
265 mode.height = height;
266 mode.frame_rate_num = 60;
267 mode.frame_rate_den = 1;
268 mode.interlaced = false;
270 return {{ 0, mode }};
273 void FFmpegCapture::producer_thread_func()
275 char thread_name[16];
276 snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
277 pthread_setname_np(pthread_self(), thread_name);
279 while (!producer_thread_should_quit.should_quit()) {
280 string pathname = search_for_file(filename);
281 if (filename.empty()) {
282 fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename.c_str());
283 send_disconnected_frame();
284 producer_thread_should_quit.sleep_for(seconds(1));
287 if (!play_video(pathname)) {
289 fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
290 send_disconnected_frame();
291 producer_thread_should_quit.sleep_for(seconds(1));
295 // Probably just EOF, will exit the loop above on next test.
298 if (has_dequeue_callbacks) {
299 dequeue_cleanup_callback();
300 has_dequeue_callbacks = false;
304 void FFmpegCapture::send_disconnected_frame()
306 // Send an empty frame to signal that we have no signal anymore.
307 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
308 if (video_frame.data) {
309 VideoFormat video_format;
310 video_format.width = width;
311 video_format.height = height;
312 video_format.stride = width * 4;
313 video_format.frame_rate_nom = 60;
314 video_format.frame_rate_den = 1;
315 video_format.is_connected = false;
317 video_frame.len = width * height * 4;
318 memset(video_frame.data, 0, video_frame.len);
320 frame_callback(-1, AVRational{1, TIMEBASE}, timecode++,
321 video_frame, /*video_offset=*/0, video_format,
322 FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
326 bool FFmpegCapture::play_video(const string &pathname)
328 // Note: Call before open, not after; otherwise, there's a race.
329 // (There is now, too, but it tips the correct way. We could use fstat()
330 // if we had the file descriptor.)
331 timespec last_modified;
333 if (stat(pathname.c_str(), &buf) != 0) {
334 // Probably some sort of protocol, so can't stat.
335 last_modified.tv_sec = -1;
337 last_modified = buf.st_mtim;
340 auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
341 if (format_ctx == nullptr) {
342 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
346 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
347 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
351 int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
352 if (video_stream_index == -1) {
353 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
357 int audio_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_AUDIO);
359 const AVCodecParameters *codecpar = format_ctx->streams[video_stream_index]->codecpar;
360 video_timebase = format_ctx->streams[video_stream_index]->time_base;
361 AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
362 if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
363 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
366 AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
367 if (codec == nullptr) {
368 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
371 if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
372 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
375 unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
376 codec_ctx.get(), avcodec_close);
381 while (!producer_thread_should_quit.should_quit()) {
382 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
387 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), codec_ctx.get(), pathname, video_stream_index, audio_stream_index, &error);
391 if (frame == nullptr) {
392 // EOF. Loop back to the start if we can.
393 if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
394 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
397 // If the file has changed since last time, return to get it reloaded.
398 // Note that depending on how you move the file into place, you might
399 // end up corrupting the one you're already playing, so this path
400 // might not trigger.
401 if (changed_since(pathname, last_modified)) {
408 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
409 FrameAllocator::Frame video_frame = make_video_frame(frame.get(), pathname, &error);
414 FrameAllocator::Frame audio_frame;
415 AudioFormat audio_format;
416 audio_format.bits_per_sample = 32;
417 audio_format.num_channels = 8;
420 if (last_pts == 0 && pts_origin == 0) {
421 pts_origin = frame->pts;
423 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
424 video_frame.received_timestamp = next_frame_start;
425 bool finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
426 if (finished_wakeup) {
427 frame_callback(frame->pts, video_timebase, timecode++,
428 video_frame, 0, video_format,
429 audio_frame, 0, audio_format);
432 if (producer_thread_should_quit.should_quit()) break;
434 bool rewound = false;
435 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
438 // If we just rewound, drop this frame on the floor and be done.
440 video_frame_allocator->release_frame(video_frame);
443 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
444 // but if it's now in the past, we'll reset the origin, so that we don't
445 // generate a huge backlog of frames that we need to run through quickly.
446 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
447 steady_clock::time_point now = steady_clock::now();
448 if (next_frame_start < now) {
449 pts_origin = frame->pts;
450 start = next_frame_start = now;
454 last_pts = frame->pts;
459 void FFmpegCapture::internal_rewind()
461 pts_origin = last_pts = 0;
462 start = next_frame_start = steady_clock::now();
465 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
467 // Process any queued commands from other threads.
468 vector<QueuedCommand> commands;
470 lock_guard<mutex> lock(queue_mu);
471 swap(commands, command_queue);
473 for (const QueuedCommand &cmd : commands) {
474 switch (cmd.command) {
475 case QueuedCommand::REWIND:
476 if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
477 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
479 // If the file has changed since last time, return to get it reloaded.
480 // Note that depending on how you move the file into place, you might
481 // end up corrupting the one you're already playing, so this path
482 // might not trigger.
483 if (changed_since(pathname, last_modified)) {
487 if (rewound != nullptr) {
492 case QueuedCommand::CHANGE_RATE:
493 // Change the origin to the last played frame.
494 start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
495 pts_origin = last_pts;
503 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *codec_ctx, const std::string &pathname, int video_stream_index, int audio_stream_index, bool *error)
507 // Read packets until we have a frame or there are none left.
508 bool frame_finished = false;
509 AVFrameWithDeleter frame = av_frame_alloc_unique();
513 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
514 &pkt, av_packet_unref);
515 av_init_packet(&pkt);
518 if (av_read_frame(format_ctx, &pkt) == 0) {
519 if (pkt.stream_index == audio_stream_index && audio_callback != nullptr) {
520 audio_callback(&pkt, format_ctx->streams[audio_stream_index]->time_base);
522 if (pkt.stream_index != video_stream_index) {
523 // Ignore audio for now.
526 if (avcodec_send_packet(codec_ctx, &pkt) < 0) {
527 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
529 return AVFrameWithDeleter(nullptr);
532 eof = true; // Or error, but ignore that for the time being.
535 int err = avcodec_receive_frame(codec_ctx, frame.get());
537 frame_finished = true;
539 } else if (err != AVERROR(EAGAIN)) {
540 fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
542 return AVFrameWithDeleter(nullptr);
549 return AVFrameWithDeleter(nullptr);
552 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
554 VideoFormat video_format;
555 video_format.width = width;
556 video_format.height = height;
557 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
558 video_format.stride = width * 4;
559 } else if (pixel_format == FFmpegCapture::PixelFormat_NV12) {
560 video_format.stride = width;
562 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
563 video_format.stride = width;
565 video_format.frame_rate_nom = video_timebase.den;
566 video_format.frame_rate_den = av_frame_get_pkt_duration(frame) * video_timebase.num;
567 if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
568 // Invalid frame rate.
569 video_format.frame_rate_nom = 60;
570 video_format.frame_rate_den = 1;
572 video_format.has_signal = true;
573 video_format.is_connected = true;
577 FrameAllocator::Frame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
581 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
582 if (video_frame.data == nullptr) {
586 if (sws_ctx == nullptr ||
587 sws_last_width != frame->width ||
588 sws_last_height != frame->height ||
589 sws_last_src_format != frame->format) {
590 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
592 sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
593 width, height, sws_dst_format,
594 SWS_BICUBIC, nullptr, nullptr, nullptr));
595 sws_last_width = frame->width;
596 sws_last_height = frame->height;
597 sws_last_src_format = frame->format;
599 if (sws_ctx == nullptr) {
600 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
605 uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
606 int linesizes[4] = { 0, 0, 0, 0 };
607 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
608 pic_data[0] = video_frame.data;
609 linesizes[0] = width * 4;
610 video_frame.len = (width * 4) * height;
611 } else if (pixel_format == PixelFormat_NV12) {
612 pic_data[0] = video_frame.data;
613 linesizes[0] = width;
615 pic_data[1] = pic_data[0] + width * height;
616 linesizes[1] = width;
618 video_frame.len = (width * 2) * height;
620 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
621 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
623 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
624 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
626 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
627 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
629 pic_data[0] = video_frame.data;
630 linesizes[0] = width;
632 pic_data[1] = pic_data[0] + width * height;
633 linesizes[1] = chroma_width;
635 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
636 linesizes[2] = chroma_width;
638 video_frame.len = width * height + 2 * chroma_width * chroma_height;
640 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
642 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);