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>
30 #include "bmusb/bmusb.h"
31 #include "ffmpeg_raii.h"
32 #include "ffmpeg_util.h"
34 #include "image_input.h"
35 #include "ref_counted_frame.h"
38 #define FRAME_SIZE (8 << 20) // 8 MB.
41 using namespace std::chrono;
42 using namespace bmusb;
43 using namespace movit;
47 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)
49 const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
50 return origin + duration_cast<steady_clock::duration>(pts / rate);
53 bool changed_since(const std::string &pathname, const timespec &ts)
59 if (stat(pathname.c_str(), &buf) != 0) {
60 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
63 return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
66 bool is_full_range(const AVPixFmtDescriptor *desc)
68 // This is horrible, but there's no better way that I know of.
69 return (strchr(desc->name, 'j') != nullptr);
72 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
74 if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
75 return AV_PIX_FMT_BGRA;
77 if (dst_format_type == FFmpegCapture::PixelFormat_NV12) {
78 return AV_PIX_FMT_NV12;
81 assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
83 // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
84 // and be done with it. It's too strange to spend a lot of time on.
85 // (Let's hope there's no alpha.)
86 const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
87 if (src_desc == nullptr ||
88 src_desc->nb_components != 3 ||
89 (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
90 return AV_PIX_FMT_YUV444P;
93 // The best for us would be Cb and Cr together if possible,
94 // but FFmpeg doesn't support that except in the special case of
95 // NV12, so we need to go to planar even for the case of NV12.
96 // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
97 // that matches in color range. (This will also include the case of
98 // the source format already being acceptable.)
99 bool src_full_range = is_full_range(src_desc);
100 const char *best_format = "yuv444p";
101 unsigned best_score = numeric_limits<unsigned>::max();
102 for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
104 desc = av_pix_fmt_desc_next(desc)) {
105 // Find planar Y'CbCr formats only.
106 if (desc->nb_components != 3) continue;
107 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
108 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
109 if (desc->comp[0].plane != 0 ||
110 desc->comp[1].plane != 1 ||
111 desc->comp[2].plane != 2) continue;
113 // 8-bit formats only.
114 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
115 if (desc->comp[0].depth != 8) continue;
117 // Same or better chroma resolution only.
118 int chroma_w_diff = desc->log2_chroma_w - src_desc->log2_chroma_w;
119 int chroma_h_diff = desc->log2_chroma_h - src_desc->log2_chroma_h;
120 if (chroma_w_diff < 0 || chroma_h_diff < 0)
123 // Matching full/limited range only.
124 if (is_full_range(desc) != src_full_range)
127 // Pick something with as little excess chroma resolution as possible.
128 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
129 if (score < best_score) {
131 best_format = desc->name;
134 return av_get_pix_fmt(best_format);
137 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame)
140 AVColorSpace colorspace = av_frame_get_colorspace(frame);
141 switch (colorspace) {
142 case AVCOL_SPC_BT709:
143 format.luma_coefficients = YCBCR_REC_709;
145 case AVCOL_SPC_BT470BG:
146 case AVCOL_SPC_SMPTE170M:
147 case AVCOL_SPC_SMPTE240M:
148 format.luma_coefficients = YCBCR_REC_601;
150 case AVCOL_SPC_BT2020_NCL:
151 format.luma_coefficients = YCBCR_REC_2020;
153 case AVCOL_SPC_UNSPECIFIED:
154 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
157 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
159 format.luma_coefficients = YCBCR_REC_709;
163 format.full_range = is_full_range(desc);
164 format.num_levels = 1 << desc->comp[0].depth;
165 format.chroma_subsampling_x = 1 << desc->log2_chroma_w;
166 format.chroma_subsampling_y = 1 << desc->log2_chroma_h;
168 switch (frame->chroma_location) {
169 case AVCHROMA_LOC_LEFT:
170 format.cb_x_position = 0.0;
171 format.cb_y_position = 0.5;
173 case AVCHROMA_LOC_CENTER:
174 format.cb_x_position = 0.5;
175 format.cb_y_position = 0.5;
177 case AVCHROMA_LOC_TOPLEFT:
178 format.cb_x_position = 0.0;
179 format.cb_y_position = 0.0;
181 case AVCHROMA_LOC_TOP:
182 format.cb_x_position = 0.5;
183 format.cb_y_position = 0.0;
185 case AVCHROMA_LOC_BOTTOMLEFT:
186 format.cb_x_position = 0.0;
187 format.cb_y_position = 1.0;
189 case AVCHROMA_LOC_BOTTOM:
190 format.cb_x_position = 0.5;
191 format.cb_y_position = 1.0;
194 fprintf(stderr, "Unknown chroma location coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
195 frame->chroma_location);
196 format.cb_x_position = 0.5;
197 format.cb_y_position = 0.5;
201 format.cr_x_position = format.cb_x_position;
202 format.cr_y_position = format.cb_y_position;
208 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
209 : filename(filename), width(width), height(height), video_timebase{1, 1}
211 description = "Video: " + filename;
213 last_frame = steady_clock::now();
215 avformat_network_init(); // In case someone wants this.
218 FFmpegCapture::~FFmpegCapture()
220 if (has_dequeue_callbacks) {
221 dequeue_cleanup_callback();
223 avresample_free(&resampler);
226 void FFmpegCapture::configure_card()
228 if (video_frame_allocator == nullptr) {
229 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
230 set_video_frame_allocator(owned_video_frame_allocator.get());
232 if (audio_frame_allocator == nullptr) {
233 // Audio can come out in pretty large chunks, so increase from the default 1 MB.
234 owned_audio_frame_allocator.reset(new MallocFrameAllocator(1 << 20, NUM_QUEUED_AUDIO_FRAMES));
235 set_audio_frame_allocator(owned_audio_frame_allocator.get());
239 void FFmpegCapture::start_bm_capture()
245 producer_thread_should_quit.unquit();
246 producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
249 void FFmpegCapture::stop_dequeue_thread()
255 producer_thread_should_quit.quit();
256 producer_thread.join();
259 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
261 // Note: This will never really be shown in the UI.
265 snprintf(buf, sizeof(buf), "%ux%u", width, height);
268 mode.autodetect = false;
270 mode.height = height;
271 mode.frame_rate_num = 60;
272 mode.frame_rate_den = 1;
273 mode.interlaced = false;
275 return {{ 0, mode }};
278 void FFmpegCapture::producer_thread_func()
280 char thread_name[16];
281 snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
282 pthread_setname_np(pthread_self(), thread_name);
284 while (!producer_thread_should_quit.should_quit()) {
285 string pathname = search_for_file(filename);
286 if (filename.empty()) {
287 fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename.c_str());
288 send_disconnected_frame();
289 producer_thread_should_quit.sleep_for(seconds(1));
292 should_interrupt = false;
293 if (!play_video(pathname)) {
295 fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
296 send_disconnected_frame();
297 producer_thread_should_quit.sleep_for(seconds(1));
301 // Probably just EOF, will exit the loop above on next test.
304 if (has_dequeue_callbacks) {
305 dequeue_cleanup_callback();
306 has_dequeue_callbacks = false;
310 void FFmpegCapture::send_disconnected_frame()
312 // Send an empty frame to signal that we have no signal anymore.
313 FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
314 if (video_frame.data) {
315 VideoFormat video_format;
316 video_format.width = width;
317 video_format.height = height;
318 video_format.frame_rate_nom = 60;
319 video_format.frame_rate_den = 1;
320 video_format.is_connected = false;
321 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
322 video_format.stride = width * 4;
323 video_frame.len = width * height * 4;
325 video_format.stride = width;
326 current_frame_ycbcr_format.luma_coefficients = YCBCR_REC_709;
327 current_frame_ycbcr_format.full_range = true;
328 current_frame_ycbcr_format.num_levels = 256;
329 current_frame_ycbcr_format.chroma_subsampling_x = 2;
330 current_frame_ycbcr_format.chroma_subsampling_y = 2;
331 current_frame_ycbcr_format.cb_x_position = 0.0f;
332 current_frame_ycbcr_format.cb_y_position = 0.0f;
333 current_frame_ycbcr_format.cr_x_position = 0.0f;
334 current_frame_ycbcr_format.cr_y_position = 0.0f;
335 video_frame.len = width * height * 2;
337 memset(video_frame.data, 0, video_frame.len);
339 frame_callback(-1, AVRational{1, TIMEBASE}, -1, AVRational{1, TIMEBASE}, timecode++,
340 video_frame, /*video_offset=*/0, video_format,
341 FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
342 last_frame_was_connected = false;
346 bool FFmpegCapture::play_video(const string &pathname)
348 // Note: Call before open, not after; otherwise, there's a race.
349 // (There is now, too, but it tips the correct way. We could use fstat()
350 // if we had the file descriptor.)
351 timespec last_modified;
353 if (stat(pathname.c_str(), &buf) != 0) {
354 // Probably some sort of protocol, so can't stat.
355 last_modified.tv_sec = -1;
357 last_modified = buf.st_mtim;
360 AVDictionary *opts = nullptr;
361 av_dict_set(&opts, "fflags", "nobuffer", 0);
363 auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, &opts, AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
364 if (format_ctx == nullptr) {
365 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
369 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
370 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
374 int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
375 if (video_stream_index == -1) {
376 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
380 int audio_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_AUDIO);
382 // Open video decoder.
383 const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
384 AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
385 video_timebase = format_ctx->streams[video_stream_index]->time_base;
386 AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
387 if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
388 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
391 if (video_codec == nullptr) {
392 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
395 if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
396 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
399 unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
400 video_codec_ctx.get(), avcodec_close);
402 // Open audio decoder, if we have audio.
403 AVCodecContextWithDeleter audio_codec_ctx;
404 if (audio_stream_index != -1) {
405 audio_codec_ctx = avcodec_alloc_context3_unique(nullptr);
406 const AVCodecParameters *audio_codecpar = format_ctx->streams[audio_stream_index]->codecpar;
407 audio_timebase = format_ctx->streams[audio_stream_index]->time_base;
408 if (avcodec_parameters_to_context(audio_codec_ctx.get(), audio_codecpar) < 0) {
409 fprintf(stderr, "%s: Cannot fill audio codec parameters\n", pathname.c_str());
412 AVCodec *audio_codec = avcodec_find_decoder(audio_codecpar->codec_id);
413 if (audio_codec == nullptr) {
414 fprintf(stderr, "%s: Cannot find audio decoder\n", pathname.c_str());
417 if (avcodec_open2(audio_codec_ctx.get(), audio_codec, nullptr) < 0) {
418 fprintf(stderr, "%s: Cannot open audio decoder\n", pathname.c_str());
422 unique_ptr<AVCodecContext, decltype(avcodec_close)*> audio_codec_ctx_cleanup(
423 audio_codec_ctx.get(), avcodec_close);
428 bool first_frame = true;
429 while (!producer_thread_should_quit.should_quit()) {
430 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
433 UniqueFrame audio_frame = audio_frame_allocator->alloc_frame();
434 AudioFormat audio_format;
438 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(), audio_codec_ctx.get(),
439 pathname, video_stream_index, audio_stream_index, audio_frame.get(), &audio_format, &audio_pts, &error);
443 if (frame == nullptr) {
444 // EOF. Loop back to the start if we can.
445 if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
446 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
449 if (video_codec_ctx != nullptr) {
450 avcodec_flush_buffers(video_codec_ctx.get());
452 if (audio_codec_ctx != nullptr) {
453 avcodec_flush_buffers(audio_codec_ctx.get());
455 // If the file has changed since last time, return to get it reloaded.
456 // Note that depending on how you move the file into place, you might
457 // end up corrupting the one you're already playing, so this path
458 // might not trigger.
459 if (changed_since(pathname, last_modified)) {
466 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
467 UniqueFrame video_frame = make_video_frame(frame.get(), pathname, &error);
473 if (last_pts == 0 && pts_origin == 0) {
474 pts_origin = frame->pts;
476 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
477 if (first_frame && last_frame_was_connected) {
478 // If reconnect took more than one second, this is probably a live feed,
479 // and we should reset the resampler. (Or the rate is really, really low,
480 // in which case a reset on the first frame is fine anyway.)
481 if (duration<double>(next_frame_start - last_frame).count() >= 1.0) {
482 last_frame_was_connected = false;
485 video_frame->received_timestamp = next_frame_start;
487 // The easiest way to get all the rate conversions etc. right is to move the
488 // audio PTS into the video PTS timebase and go from there. (We'll get some
489 // rounding issues, but they should not be a big problem.)
490 int64_t audio_pts_as_video_pts = av_rescale_q(audio_pts, audio_timebase, video_timebase);
491 audio_frame->received_timestamp = compute_frame_start(audio_pts_as_video_pts, pts_origin, video_timebase, start, rate);
493 if (audio_frame->len != 0) {
494 // The received timestamps in Nageru are measured after we've just received the frame.
495 // However, pts (especially audio pts) is at the _beginning_ of the frame.
496 // If we have locked audio, the distinction doesn't really matter, as pts is
497 // on a relative scale and a fixed offset is fine. But if we don't, we will have
498 // a different number of samples each time, which will cause huge audio jitter
499 // and throw off the resampler.
501 // In a sense, we should have compensated by adding the frame and audio lengths
502 // to video_frame->received_timestamp and audio_frame->received_timestamp respectively,
503 // but that would mean extra waiting in sleep_until(). All we need is that they
504 // are correct relative to each other, though (and to the other frames we send),
505 // so just align the end of the audio frame, and we're fine.
506 size_t num_samples = (audio_frame->len * 8) / audio_format.bits_per_sample / audio_format.num_channels;
507 double offset = double(num_samples) / OUTPUT_FREQUENCY -
508 double(video_format.frame_rate_den) / video_format.frame_rate_nom;
509 audio_frame->received_timestamp += duration_cast<steady_clock::duration>(duration<double>(offset));
512 steady_clock::time_point now = steady_clock::now();
513 if (duration<double>(now - next_frame_start).count() >= 0.1) {
514 // If we don't have enough CPU to keep up, or if we have a live stream
515 // where the initial origin was somehow wrong, we could be behind indefinitely.
516 // In particular, this will give the audio resampler problems as it tries
517 // to speed up to reduce the delay, hitting the low end of the buffer every time.
518 fprintf(stderr, "%s: Playback %.0f ms behind, resetting time scale\n",
520 1e3 * duration<double>(now - next_frame_start).count());
521 pts_origin = frame->pts;
522 start = next_frame_start = now;
523 timecode += MAX_FPS * 2 + 1;
525 bool finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
526 if (finished_wakeup) {
527 if (audio_frame->len > 0) {
528 assert(audio_pts != -1);
530 if (!last_frame_was_connected) {
531 // We're recovering from an error (or really slow load, see above).
532 // Make sure to get the audio resampler reset. (This is a hack;
533 // ideally, the frame callback should just accept a way to signal
534 // audio discontinuity.)
535 timecode += MAX_FPS * 2 + 1;
537 frame_callback(frame->pts, video_timebase, audio_pts, audio_timebase, timecode++,
538 video_frame.get_and_release(), 0, video_format,
539 audio_frame.get_and_release(), 0, audio_format);
541 last_frame = steady_clock::now();
542 last_frame_was_connected = true;
545 if (producer_thread_should_quit.should_quit()) break;
547 bool rewound = false;
548 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
551 // If we just rewound, drop this frame on the floor and be done.
555 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
556 // but if it's now in the past, we'll reset the origin, so that we don't
557 // generate a huge backlog of frames that we need to run through quickly.
558 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
559 steady_clock::time_point now = steady_clock::now();
560 if (next_frame_start < now) {
561 pts_origin = frame->pts;
562 start = next_frame_start = now;
566 last_pts = frame->pts;
571 void FFmpegCapture::internal_rewind()
573 pts_origin = last_pts = 0;
574 start = next_frame_start = steady_clock::now();
577 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
579 // Process any queued commands from other threads.
580 vector<QueuedCommand> commands;
582 lock_guard<mutex> lock(queue_mu);
583 swap(commands, command_queue);
585 for (const QueuedCommand &cmd : commands) {
586 switch (cmd.command) {
587 case QueuedCommand::REWIND:
588 if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
589 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
591 // If the file has changed since last time, return to get it reloaded.
592 // Note that depending on how you move the file into place, you might
593 // end up corrupting the one you're already playing, so this path
594 // might not trigger.
595 if (changed_since(pathname, last_modified)) {
599 if (rewound != nullptr) {
604 case QueuedCommand::CHANGE_RATE:
605 // Change the origin to the last played frame.
606 start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
607 pts_origin = last_pts;
619 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
620 const std::string &pathname, int video_stream_index, int audio_stream_index,
621 FrameAllocator::Frame *audio_frame, AudioFormat *audio_format, int64_t *audio_pts, bool *error)
625 // Read packets until we have a frame or there are none left.
626 bool frame_finished = false;
627 AVFrameWithDeleter audio_avframe = av_frame_alloc_unique();
628 AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
631 bool has_audio = false;
634 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
635 &pkt, av_packet_unref);
636 av_init_packet(&pkt);
639 if (av_read_frame(format_ctx, &pkt) == 0) {
640 if (pkt.stream_index == audio_stream_index && audio_callback != nullptr) {
641 audio_callback(&pkt, format_ctx->streams[audio_stream_index]->time_base);
643 if (pkt.stream_index == video_stream_index) {
644 if (avcodec_send_packet(video_codec_ctx, &pkt) < 0) {
645 fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
647 return AVFrameWithDeleter(nullptr);
649 } else if (pkt.stream_index == audio_stream_index) {
651 if (avcodec_send_packet(audio_codec_ctx, &pkt) < 0) {
652 fprintf(stderr, "%s: Cannot send packet to audio codec.\n", pathname.c_str());
654 return AVFrameWithDeleter(nullptr);
658 eof = true; // Or error, but ignore that for the time being.
661 // Decode audio, if any.
664 int err = avcodec_receive_frame(audio_codec_ctx, audio_avframe.get());
666 if (*audio_pts == -1) {
667 *audio_pts = audio_avframe->pts;
669 convert_audio(audio_avframe.get(), audio_frame, audio_format);
670 } else if (err == AVERROR(EAGAIN)) {
673 fprintf(stderr, "%s: Cannot receive frame from audio codec.\n", pathname.c_str());
675 return AVFrameWithDeleter(nullptr);
680 // Decode video, if we have a frame.
681 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
683 frame_finished = true;
685 } else if (err != AVERROR(EAGAIN)) {
686 fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
688 return AVFrameWithDeleter(nullptr);
693 return video_avframe;
695 return AVFrameWithDeleter(nullptr);
698 void FFmpegCapture::convert_audio(const AVFrame *audio_avframe, FrameAllocator::Frame *audio_frame, AudioFormat *audio_format)
700 // Decide on a format. If there already is one in this audio frame,
701 // we're pretty much forced to use it. If not, we try to find an exact match.
702 // If that still doesn't work, we default to 32-bit signed chunked
703 // (float would be nice, but there's really no way to signal that yet).
704 AVSampleFormat dst_format;
705 if (audio_format->bits_per_sample == 0) {
706 switch (audio_avframe->format) {
707 case AV_SAMPLE_FMT_S16:
708 case AV_SAMPLE_FMT_S16P:
709 audio_format->bits_per_sample = 16;
710 dst_format = AV_SAMPLE_FMT_S16;
712 case AV_SAMPLE_FMT_S32:
713 case AV_SAMPLE_FMT_S32P:
715 audio_format->bits_per_sample = 32;
716 dst_format = AV_SAMPLE_FMT_S32;
719 } else if (audio_format->bits_per_sample == 16) {
720 dst_format = AV_SAMPLE_FMT_S16;
721 } else if (audio_format->bits_per_sample == 32) {
722 dst_format = AV_SAMPLE_FMT_S32;
726 audio_format->num_channels = 2;
728 int64_t channel_layout = audio_avframe->channel_layout;
729 if (channel_layout == 0) {
730 channel_layout = av_get_default_channel_layout(audio_avframe->channels);
733 if (resampler == nullptr ||
734 audio_avframe->format != last_src_format ||
735 dst_format != last_dst_format ||
736 channel_layout != last_channel_layout ||
737 av_frame_get_sample_rate(audio_avframe) != last_sample_rate) {
738 avresample_free(&resampler);
739 resampler = avresample_alloc_context();
740 if (resampler == nullptr) {
741 fprintf(stderr, "Allocating resampler failed.\n");
745 av_opt_set_int(resampler, "in_channel_layout", channel_layout, 0);
746 av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
747 av_opt_set_int(resampler, "in_sample_rate", av_frame_get_sample_rate(audio_avframe), 0);
748 av_opt_set_int(resampler, "out_sample_rate", OUTPUT_FREQUENCY, 0);
749 av_opt_set_int(resampler, "in_sample_fmt", audio_avframe->format, 0);
750 av_opt_set_int(resampler, "out_sample_fmt", dst_format, 0);
752 if (avresample_open(resampler) < 0) {
753 fprintf(stderr, "Could not open resample context.\n");
757 last_src_format = AVSampleFormat(audio_avframe->format);
758 last_dst_format = dst_format;
759 last_channel_layout = channel_layout;
760 last_sample_rate = av_frame_get_sample_rate(audio_avframe);
763 size_t bytes_per_sample = (audio_format->bits_per_sample / 8) * 2;
764 size_t num_samples_room = (audio_frame->size - audio_frame->len) / bytes_per_sample;
766 uint8_t *data = audio_frame->data + audio_frame->len;
767 int out_samples = avresample_convert(resampler, &data, 0, num_samples_room,
768 const_cast<uint8_t **>(audio_avframe->data), audio_avframe->linesize[0], audio_avframe->nb_samples);
769 if (out_samples < 0) {
770 fprintf(stderr, "Audio conversion failed.\n");
774 audio_frame->len += out_samples * bytes_per_sample;
777 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
779 VideoFormat video_format;
780 video_format.width = width;
781 video_format.height = height;
782 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
783 video_format.stride = width * 4;
784 } else if (pixel_format == FFmpegCapture::PixelFormat_NV12) {
785 video_format.stride = width;
787 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
788 video_format.stride = width;
790 video_format.frame_rate_nom = video_timebase.den;
791 video_format.frame_rate_den = av_frame_get_pkt_duration(frame) * video_timebase.num;
792 if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
793 // Invalid frame rate.
794 video_format.frame_rate_nom = 60;
795 video_format.frame_rate_den = 1;
797 video_format.has_signal = true;
798 video_format.is_connected = true;
802 UniqueFrame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
806 UniqueFrame video_frame(video_frame_allocator->alloc_frame());
807 if (video_frame->data == nullptr) {
811 if (sws_ctx == nullptr ||
812 sws_last_width != frame->width ||
813 sws_last_height != frame->height ||
814 sws_last_src_format != frame->format) {
815 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
817 sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
818 width, height, sws_dst_format,
819 SWS_BICUBIC, nullptr, nullptr, nullptr));
820 sws_last_width = frame->width;
821 sws_last_height = frame->height;
822 sws_last_src_format = frame->format;
824 if (sws_ctx == nullptr) {
825 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
830 uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
831 int linesizes[4] = { 0, 0, 0, 0 };
832 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
833 pic_data[0] = video_frame->data;
834 linesizes[0] = width * 4;
835 video_frame->len = (width * 4) * height;
836 } else if (pixel_format == PixelFormat_NV12) {
837 pic_data[0] = video_frame->data;
838 linesizes[0] = width;
840 pic_data[1] = pic_data[0] + width * height;
841 linesizes[1] = width;
843 video_frame->len = (width * 2) * height;
845 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
846 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
848 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
849 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
851 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
852 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
854 pic_data[0] = video_frame->data;
855 linesizes[0] = width;
857 pic_data[1] = pic_data[0] + width * height;
858 linesizes[1] = chroma_width;
860 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
861 linesizes[2] = chroma_width;
863 video_frame->len = width * height + 2 * chroma_width * chroma_height;
865 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
867 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
872 int FFmpegCapture::interrupt_cb_thunk(void *unique)
874 return reinterpret_cast<FFmpegCapture *>(unique)->interrupt_cb();
877 int FFmpegCapture::interrupt_cb()
879 return should_interrupt.load();