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"
35 #define FRAME_SIZE (8 << 20) // 8 MB.
38 using namespace std::chrono;
39 using namespace bmusb;
40 using namespace movit;
44 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)
46 const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
47 return origin + duration_cast<steady_clock::duration>(pts / rate);
50 bool changed_since(const std::string &pathname, const timespec &ts)
56 if (stat(pathname.c_str(), &buf) != 0) {
57 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
60 return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
63 bool is_full_range(const AVPixFmtDescriptor *desc)
65 // This is horrible, but there's no better way that I know of.
66 return (strchr(desc->name, 'j') != nullptr);
69 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
71 if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
72 return AV_PIX_FMT_BGRA;
75 assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
77 // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
78 // and be done with it. It's too strange to spend a lot of time on.
79 // (Let's hope there's no alpha.)
80 const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
81 if (src_desc == nullptr ||
82 src_desc->nb_components != 3 ||
83 (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
84 return AV_PIX_FMT_YUV444P;
87 // The best for us would be Cb and Cr together if possible,
88 // but FFmpeg doesn't support that except in the special case of
89 // NV12, so we need to go to planar even for the case of NV12.
90 // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
91 // that matches in color range. (This will also include the case of
92 // the source format already being acceptable.)
93 bool src_full_range = is_full_range(src_desc);
94 const char *best_format = "yuv444p";
95 unsigned best_score = numeric_limits<unsigned>::max();
96 for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
98 desc = av_pix_fmt_desc_next(desc)) {
99 // Find planar Y'CbCr formats only.
100 if (desc->nb_components != 3) continue;
101 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
102 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
103 if (desc->comp[0].plane != 0 ||
104 desc->comp[1].plane != 1 ||
105 desc->comp[2].plane != 2) continue;
107 // 8-bit formats only.
108 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
109 if (desc->comp[0].depth != 8) continue;
111 // Same or better chroma resolution only.
112 int chroma_w_diff = desc->log2_chroma_w - src_desc->log2_chroma_w;
113 int chroma_h_diff = desc->log2_chroma_h - src_desc->log2_chroma_h;
114 if (chroma_w_diff < 0 || chroma_h_diff < 0)
117 // Matching full/limited range only.
118 if (is_full_range(desc) != src_full_range)
121 // Pick something with as little excess chroma resolution as possible.
122 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
123 if (score < best_score) {
125 best_format = desc->name;
128 return av_get_pix_fmt(best_format);
131 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame)
134 AVColorSpace colorspace = av_frame_get_colorspace(frame);
135 switch (colorspace) {
136 case AVCOL_SPC_BT709:
137 format.luma_coefficients = YCBCR_REC_709;
139 case AVCOL_SPC_BT470BG:
140 case AVCOL_SPC_SMPTE170M:
141 case AVCOL_SPC_SMPTE240M:
142 format.luma_coefficients = YCBCR_REC_601;
144 case AVCOL_SPC_BT2020_NCL:
145 format.luma_coefficients = YCBCR_REC_2020;
147 case AVCOL_SPC_UNSPECIFIED:
148 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
151 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
153 format.luma_coefficients = YCBCR_REC_709;
157 format.full_range = is_full_range(desc);
158 format.num_levels = 1 << desc->comp[0].depth;
159 format.chroma_subsampling_x = 1 << desc->log2_chroma_w;
160 format.chroma_subsampling_y = 1 << desc->log2_chroma_h;
162 switch (frame->chroma_location) {
163 case AVCHROMA_LOC_LEFT:
164 format.cb_x_position = 0.0;
165 format.cb_y_position = 0.5;
167 case AVCHROMA_LOC_CENTER:
168 format.cb_x_position = 0.5;
169 format.cb_y_position = 0.5;
171 case AVCHROMA_LOC_TOPLEFT:
172 format.cb_x_position = 0.0;
173 format.cb_y_position = 0.0;
175 case AVCHROMA_LOC_TOP:
176 format.cb_x_position = 0.5;
177 format.cb_y_position = 0.0;
179 case AVCHROMA_LOC_BOTTOMLEFT:
180 format.cb_x_position = 0.0;
181 format.cb_y_position = 1.0;
183 case AVCHROMA_LOC_BOTTOM:
184 format.cb_x_position = 0.5;
185 format.cb_y_position = 1.0;
188 fprintf(stderr, "Unknown chroma location coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
189 frame->chroma_location);
190 format.cb_x_position = 0.5;
191 format.cb_y_position = 0.5;
195 format.cr_x_position = format.cb_x_position;
196 format.cr_y_position = format.cb_y_position;
202 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
203 : filename(filename), width(width), height(height), video_timebase{1, 1}
205 // Not really used for anything.
206 description = "Video: " + filename;
208 avformat_network_init(); // In case someone wants this.
211 FFmpegCapture::~FFmpegCapture()
213 if (has_dequeue_callbacks) {
214 dequeue_cleanup_callback();
218 void FFmpegCapture::configure_card()
220 if (video_frame_allocator == nullptr) {
221 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
222 set_video_frame_allocator(owned_video_frame_allocator.get());
224 if (audio_frame_allocator == nullptr) {
225 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
226 set_audio_frame_allocator(owned_audio_frame_allocator.get());
230 void FFmpegCapture::start_bm_capture()
236 producer_thread_should_quit.unquit();
237 producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
240 void FFmpegCapture::stop_dequeue_thread()
246 producer_thread_should_quit.quit();
247 producer_thread.join();
250 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
252 // Note: This will never really be shown in the UI.
256 snprintf(buf, sizeof(buf), "%ux%u", width, height);
259 mode.autodetect = false;
261 mode.height = height;
262 mode.frame_rate_num = 60;
263 mode.frame_rate_den = 1;
264 mode.interlaced = false;
266 return {{ 0, mode }};
269 void FFmpegCapture::producer_thread_func()
271 char thread_name[16];
272 snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
273 pthread_setname_np(pthread_self(), thread_name);
275 while (!producer_thread_should_quit.should_quit()) {
276 string pathname = search_for_file(filename);
277 if (filename.empty()) {
278 fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename.c_str());
279 send_disconnected_frame();
280 producer_thread_should_quit.sleep_for(seconds(1));
283 if (!play_video(pathname)) {
285 fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
286 send_disconnected_frame();
287 producer_thread_should_quit.sleep_for(seconds(1));
291 // Probably just EOF, will exit the loop above on next test.
294 if (has_dequeue_callbacks) {
295 dequeue_cleanup_callback();
296 has_dequeue_callbacks = false;
300 void FFmpegCapture::send_disconnected_frame()
302 // Send an empty frame to signal that we have no signal anymore.
303 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
304 if (video_frame.data) {
305 VideoFormat video_format;
306 video_format.width = width;
307 video_format.height = height;
308 video_format.stride = width * 4;
309 video_format.frame_rate_nom = 60;
310 video_format.frame_rate_den = 1;
311 video_format.is_connected = false;
313 video_frame.len = width * height * 4;
314 memset(video_frame.data, 0, video_frame.len);
316 frame_callback(timecode++,
317 video_frame, /*video_offset=*/0, video_format,
318 FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
322 bool FFmpegCapture::play_video(const string &pathname)
324 // Note: Call before open, not after; otherwise, there's a race.
325 // (There is now, too, but it tips the correct way. We could use fstat()
326 // if we had the file descriptor.)
327 timespec last_modified;
329 if (stat(pathname.c_str(), &buf) != 0) {
330 // Probably some sort of protocol, so can't stat.
331 last_modified.tv_sec = -1;
333 last_modified = buf.st_mtim;
336 auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
337 if (format_ctx == nullptr) {
338 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
342 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
343 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
347 int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
348 if (video_stream_index == -1) {
349 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
353 const AVCodecParameters *codecpar = format_ctx->streams[video_stream_index]->codecpar;
354 video_timebase = format_ctx->streams[video_stream_index]->time_base;
355 AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
356 if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
357 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
360 AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
361 if (codec == nullptr) {
362 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
365 if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
366 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
369 unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
370 codec_ctx.get(), avcodec_close);
375 while (!producer_thread_should_quit.should_quit()) {
376 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
381 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), codec_ctx.get(), pathname, video_stream_index, &error);
385 if (frame == nullptr) {
386 // EOF. Loop back to the start if we can.
387 if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
388 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
391 // If the file has changed since last time, return to get it reloaded.
392 // Note that depending on how you move the file into place, you might
393 // end up corrupting the one you're already playing, so this path
394 // might not trigger.
395 if (changed_since(pathname, last_modified)) {
402 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
403 FrameAllocator::Frame video_frame = make_video_frame(frame.get(), pathname, &error);
408 FrameAllocator::Frame audio_frame;
409 AudioFormat audio_format;
410 audio_format.bits_per_sample = 32;
411 audio_format.num_channels = 8;
414 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
415 video_frame.received_timestamp = next_frame_start;
416 bool finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
417 if (finished_wakeup) {
418 frame_callback(timecode++,
419 video_frame, 0, video_format,
420 audio_frame, 0, audio_format);
423 if (producer_thread_should_quit.should_quit()) break;
425 bool rewound = false;
426 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
429 // If we just rewound, drop this frame on the floor and be done.
431 video_frame_allocator->release_frame(video_frame);
434 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
435 // but if it's now in the past, we'll reset the origin, so that we don't
436 // generate a huge backlog of frames that we need to run through quickly.
437 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
438 steady_clock::time_point now = steady_clock::now();
439 if (next_frame_start < now) {
440 pts_origin = frame->pts;
441 start = next_frame_start = now;
445 last_pts = frame->pts;
450 void FFmpegCapture::internal_rewind()
452 pts_origin = last_pts = 0;
453 start = next_frame_start = steady_clock::now();
456 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
458 // Process any queued commands from other threads.
459 vector<QueuedCommand> commands;
461 lock_guard<mutex> lock(queue_mu);
462 swap(commands, command_queue);
464 for (const QueuedCommand &cmd : commands) {
465 switch (cmd.command) {
466 case QueuedCommand::REWIND:
467 if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
468 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
470 // If the file has changed since last time, return to get it reloaded.
471 // Note that depending on how you move the file into place, you might
472 // end up corrupting the one you're already playing, so this path
473 // might not trigger.
474 if (changed_since(pathname, last_modified)) {
478 if (rewound != nullptr) {
483 case QueuedCommand::CHANGE_RATE:
484 // Change the origin to the last played frame.
485 start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
486 pts_origin = last_pts;
494 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *codec_ctx, const std::string &pathname, int video_stream_index, bool *error)
498 // Read packets until we have a frame or there are none left.
499 bool frame_finished = false;
500 AVFrameWithDeleter frame = av_frame_alloc_unique();
504 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
505 &pkt, av_packet_unref);
506 av_init_packet(&pkt);
509 if (av_read_frame(format_ctx, &pkt) == 0) {
510 if (pkt.stream_index != video_stream_index) {
511 // Ignore audio for now.
514 if (avcodec_send_packet(codec_ctx, &pkt) < 0) {
515 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
517 return AVFrameWithDeleter(nullptr);
520 eof = true; // Or error, but ignore that for the time being.
523 int err = avcodec_receive_frame(codec_ctx, frame.get());
525 frame_finished = true;
527 } else if (err != AVERROR(EAGAIN)) {
528 fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
530 return AVFrameWithDeleter(nullptr);
537 return AVFrameWithDeleter(nullptr);
540 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
542 VideoFormat video_format;
543 video_format.width = width;
544 video_format.height = height;
545 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
546 video_format.stride = width * 4;
548 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
549 video_format.stride = width;
551 video_format.frame_rate_nom = video_timebase.den;
552 video_format.frame_rate_den = av_frame_get_pkt_duration(frame) * video_timebase.num;
553 if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
554 // Invalid frame rate.
555 video_format.frame_rate_nom = 60;
556 video_format.frame_rate_den = 1;
558 video_format.has_signal = true;
559 video_format.is_connected = true;
563 FrameAllocator::Frame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
567 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
568 if (video_frame.data == nullptr) {
572 if (sws_ctx == nullptr ||
573 sws_last_width != frame->width ||
574 sws_last_height != frame->height ||
575 sws_last_src_format != frame->format) {
576 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
578 sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
579 width, height, sws_dst_format,
580 SWS_BICUBIC, nullptr, nullptr, nullptr));
581 sws_last_width = frame->width;
582 sws_last_height = frame->height;
583 sws_last_src_format = frame->format;
585 if (sws_ctx == nullptr) {
586 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
591 uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
592 int linesizes[4] = { 0, 0, 0, 0 };
593 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
594 pic_data[0] = video_frame.data;
595 linesizes[0] = width * 4;
596 video_frame.len = (width * 4) * height;
598 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
599 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
601 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
602 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
604 pic_data[0] = video_frame.data;
605 linesizes[0] = width;
607 pic_data[1] = pic_data[0] + width * height;
608 linesizes[1] = chroma_width;
610 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
611 linesizes[2] = chroma_width;
613 video_frame.len = width * height + 2 * chroma_width * chroma_height;
615 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
617 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);