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)
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 AVRational 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);
374 unique_ptr<SwsContext, decltype(sws_freeContext)*> sws_ctx(nullptr, sws_freeContext);
375 int sws_last_width = -1, sws_last_height = -1, sws_last_src_format = -1;
376 AVPixelFormat sws_dst_format = AVPixelFormat(-1); // In practice, always initialized.
379 while (!producer_thread_should_quit.should_quit()) {
380 if (process_queued_commands(format_ctx.get(), pathname, last_modified)) {
384 // Read packets until we have a frame or there are none left.
385 int frame_finished = 0;
386 AVFrameWithDeleter frame = av_frame_alloc_unique();
390 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
391 &pkt, av_packet_unref);
392 av_init_packet(&pkt);
395 if (av_read_frame(format_ctx.get(), &pkt) == 0) {
396 if (pkt.stream_index != video_stream_index) {
397 // Ignore audio for now.
400 if (avcodec_send_packet(codec_ctx.get(), &pkt) < 0) {
401 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
405 eof = true; // Or error, but ignore that for the time being.
408 int err = avcodec_receive_frame(codec_ctx.get(), frame.get());
410 frame_finished = true;
412 } else if (err != AVERROR(EAGAIN)) {
413 fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
418 if (!frame_finished) {
419 // EOF. Loop back to the start if we can.
420 if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
421 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
424 // If the file has changed since last time, return to get it reloaded.
425 // Note that depending on how you move the file into place, you might
426 // end up corrupting the one you're already playing, so this path
427 // might not trigger.
428 if (changed_since(pathname, last_modified)) {
435 if (sws_ctx == nullptr ||
436 sws_last_width != frame->width ||
437 sws_last_height != frame->height ||
438 sws_last_src_format != frame->format) {
439 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
441 sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
442 width, height, sws_dst_format,
443 SWS_BICUBIC, nullptr, nullptr, nullptr));
444 sws_last_width = frame->width;
445 sws_last_height = frame->height;
446 sws_last_src_format = frame->format;
448 if (sws_ctx == nullptr) {
449 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
453 VideoFormat video_format;
454 video_format.width = width;
455 video_format.height = height;
456 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
457 video_format.stride = width * 4;
459 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
460 video_format.stride = width;
462 video_format.frame_rate_nom = video_timebase.den;
463 video_format.frame_rate_den = av_frame_get_pkt_duration(frame.get()) * video_timebase.num;
464 if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
465 // Invalid frame rate.
466 video_format.frame_rate_nom = 60;
467 video_format.frame_rate_den = 1;
469 video_format.has_signal = true;
470 video_format.is_connected = true;
472 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
473 last_pts = frame->pts;
475 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
476 if (video_frame.data != nullptr) {
477 uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
478 int linesizes[4] = { 0, 0, 0, 0 };
479 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
480 pic_data[0] = video_frame.data;
481 linesizes[0] = video_format.stride;
482 video_frame.len = video_format.stride * height;
484 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
485 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
487 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
488 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
490 pic_data[0] = video_frame.data;
491 linesizes[0] = width;
493 pic_data[1] = pic_data[0] + width * height;
494 linesizes[1] = chroma_width;
496 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
497 linesizes[2] = chroma_width;
499 video_frame.len = width * height + 2 * chroma_width * chroma_height;
501 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame.get());
503 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
504 video_frame.received_timestamp = next_frame_start;
507 FrameAllocator::Frame audio_frame;
508 AudioFormat audio_format;
509 audio_format.bits_per_sample = 32;
510 audio_format.num_channels = 8;
512 producer_thread_should_quit.sleep_until(next_frame_start);
513 frame_callback(timecode++,
514 video_frame, 0, video_format,
515 audio_frame, 0, audio_format);
520 void FFmpegCapture::internal_rewind()
522 pts_origin = last_pts = 0;
523 start = next_frame_start = steady_clock::now();
526 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified)
528 // Process any queued commands from other threads.
529 vector<QueuedCommand> commands;
531 lock_guard<mutex> lock(queue_mu);
532 swap(commands, command_queue);
534 for (const QueuedCommand &cmd : commands) {
535 switch (cmd.command) {
536 case QueuedCommand::REWIND:
537 if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
538 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
540 // If the file has changed since last time, return to get it reloaded.
541 // Note that depending on how you move the file into place, you might
542 // end up corrupting the one you're already playing, so this path
543 // might not trigger.
544 if (changed_since(pathname, last_modified)) {
550 case QueuedCommand::CHANGE_RATE:
551 start = next_frame_start;
552 pts_origin = last_pts;