]> git.sesse.net Git - nageru/blob - ffmpeg_capture.cpp
Fix a few Clang warnings.
[nageru] / ffmpeg_capture.cpp
1 #include "ffmpeg_capture.h"
2
3 #include <assert.h>
4 #include <pthread.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11
12 extern "C" {
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>
23 }
24
25 #include <chrono>
26 #include <cstdint>
27 #include <utility>
28 #include <vector>
29
30 #include "bmusb/bmusb.h"
31 #include "ffmpeg_raii.h"
32 #include "ffmpeg_util.h"
33 #include "flags.h"
34 #include "image_input.h"
35 #include "ref_counted_frame.h"
36 #include "timebase.h"
37
38 #define FRAME_SIZE (8 << 20)  // 8 MB.
39
40 using namespace std;
41 using namespace std::chrono;
42 using namespace bmusb;
43 using namespace movit;
44
45 namespace {
46
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)
48 {
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);
51 }
52
53 bool changed_since(const std::string &pathname, const timespec &ts)
54 {
55         if (ts.tv_sec < 0) {
56                 return false;
57         }
58         struct stat buf;
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());
61                 return false;
62         }
63         return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
64 }
65
66 bool is_full_range(const AVPixFmtDescriptor *desc)
67 {
68         // This is horrible, but there's no better way that I know of.
69         return (strchr(desc->name, 'j') != nullptr);
70 }
71
72 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
73 {
74         if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
75                 return AV_PIX_FMT_BGRA;
76         }
77         if (dst_format_type == FFmpegCapture::PixelFormat_NV12) {
78                 return AV_PIX_FMT_NV12;
79         }
80
81         assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
82
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;
91         }
92
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);
103              desc;
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;
112
113                 // 8-bit formats only.
114                 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
115                 if (desc->comp[0].depth != 8) continue;
116
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)
121                         continue;
122
123                 // Matching full/limited range only.
124                 if (is_full_range(desc) != src_full_range)
125                         continue;
126
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) {
130                         best_score = score;
131                         best_format = desc->name;
132                 }
133         }
134         return av_get_pix_fmt(best_format);
135 }
136
137 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame)
138 {
139         YCbCrFormat format;
140         AVColorSpace colorspace = av_frame_get_colorspace(frame);
141         switch (colorspace) {
142         case AVCOL_SPC_BT709:
143                 format.luma_coefficients = YCBCR_REC_709;
144                 break;
145         case AVCOL_SPC_BT470BG:
146         case AVCOL_SPC_SMPTE170M:
147         case AVCOL_SPC_SMPTE240M:
148                 format.luma_coefficients = YCBCR_REC_601;
149                 break;
150         case AVCOL_SPC_BT2020_NCL:
151                 format.luma_coefficients = YCBCR_REC_2020;
152                 break;
153         case AVCOL_SPC_UNSPECIFIED:
154                 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
155                 break;
156         default:
157                 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
158                         colorspace);
159                 format.luma_coefficients = YCBCR_REC_709;
160                 break;
161         }
162
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;
167
168         switch (frame->chroma_location) {
169         case AVCHROMA_LOC_LEFT:
170                 format.cb_x_position = 0.0;
171                 format.cb_y_position = 0.5;
172                 break;
173         case AVCHROMA_LOC_CENTER:
174                 format.cb_x_position = 0.5;
175                 format.cb_y_position = 0.5;
176                 break;
177         case AVCHROMA_LOC_TOPLEFT:
178                 format.cb_x_position = 0.0;
179                 format.cb_y_position = 0.0;
180                 break;
181         case AVCHROMA_LOC_TOP:
182                 format.cb_x_position = 0.5;
183                 format.cb_y_position = 0.0;
184                 break;
185         case AVCHROMA_LOC_BOTTOMLEFT:
186                 format.cb_x_position = 0.0;
187                 format.cb_y_position = 1.0;
188                 break;
189         case AVCHROMA_LOC_BOTTOM:
190                 format.cb_x_position = 0.5;
191                 format.cb_y_position = 1.0;
192                 break;
193         default:
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;
198                 break;
199         }
200
201         format.cr_x_position = format.cb_x_position;
202         format.cr_y_position = format.cb_y_position;
203         return format;
204 }
205
206 }  // namespace
207
208 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
209         : filename(filename), width(width), height(height), video_timebase{1, 1}
210 {
211         // Not really used for anything.
212         description = "Video: " + filename;
213
214         avformat_network_init();  // In case someone wants this.
215 }
216
217 FFmpegCapture::~FFmpegCapture()
218 {
219         if (has_dequeue_callbacks) {
220                 dequeue_cleanup_callback();
221         }
222         avresample_free(&resampler);
223 }
224
225 void FFmpegCapture::configure_card()
226 {
227         if (video_frame_allocator == nullptr) {
228                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
229                 set_video_frame_allocator(owned_video_frame_allocator.get());
230         }
231         if (audio_frame_allocator == nullptr) {
232                 // Audio can come out in pretty large chunks, so increase from the default 1 MB.
233                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(1 << 20, NUM_QUEUED_AUDIO_FRAMES));
234                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
235         }
236 }
237
238 void FFmpegCapture::start_bm_capture()
239 {
240         if (running) {
241                 return;
242         }
243         running = true;
244         producer_thread_should_quit.unquit();
245         producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
246 }
247
248 void FFmpegCapture::stop_dequeue_thread()
249 {
250         if (!running) {
251                 return;
252         }
253         running = false;
254         producer_thread_should_quit.quit();
255         producer_thread.join();
256 }
257
258 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
259 {
260         // Note: This will never really be shown in the UI.
261         VideoMode mode;
262
263         char buf[256];
264         snprintf(buf, sizeof(buf), "%ux%u", width, height);
265         mode.name = buf;
266         
267         mode.autodetect = false;
268         mode.width = width;
269         mode.height = height;
270         mode.frame_rate_num = 60;
271         mode.frame_rate_den = 1;
272         mode.interlaced = false;
273
274         return {{ 0, mode }};
275 }
276
277 void FFmpegCapture::producer_thread_func()
278 {
279         char thread_name[16];
280         snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
281         pthread_setname_np(pthread_self(), thread_name);
282
283         while (!producer_thread_should_quit.should_quit()) {
284                 string pathname = search_for_file(filename);
285                 if (filename.empty()) {
286                         fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename.c_str());
287                         send_disconnected_frame();
288                         producer_thread_should_quit.sleep_for(seconds(1));
289                         continue;
290                 }
291                 should_interrupt = false;
292                 if (!play_video(pathname)) {
293                         // Error.
294                         fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
295                         send_disconnected_frame();
296                         producer_thread_should_quit.sleep_for(seconds(1));
297                         continue;
298                 }
299
300                 // Probably just EOF, will exit the loop above on next test.
301         }
302
303         if (has_dequeue_callbacks) {
304                 dequeue_cleanup_callback();
305                 has_dequeue_callbacks = false;
306         }
307 }
308
309 void FFmpegCapture::send_disconnected_frame()
310 {
311         // Send an empty frame to signal that we have no signal anymore.
312         FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
313         if (video_frame.data) {
314                 VideoFormat video_format;
315                 video_format.width = width;
316                 video_format.height = height;
317                 video_format.frame_rate_nom = 60;
318                 video_format.frame_rate_den = 1;
319                 video_format.is_connected = false;
320                 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
321                         video_format.stride = width * 4;
322                         video_frame.len = width * height * 4;
323                 } else {
324                         video_format.stride = width;
325                         current_frame_ycbcr_format.full_range = true;
326                         current_frame_ycbcr_format.num_levels = 256;
327                         current_frame_ycbcr_format.chroma_subsampling_x = 2;
328                         current_frame_ycbcr_format.chroma_subsampling_y = 2;
329                         video_frame.len = width * height * 2;
330                 }
331                 memset(video_frame.data, 0, video_frame.len);
332
333                 frame_callback(-1, AVRational{1, TIMEBASE}, -1, AVRational{1, TIMEBASE}, timecode++,
334                         video_frame, /*video_offset=*/0, video_format,
335                         FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
336         }
337 }
338
339 bool FFmpegCapture::play_video(const string &pathname)
340 {
341         // Note: Call before open, not after; otherwise, there's a race.
342         // (There is now, too, but it tips the correct way. We could use fstat()
343         // if we had the file descriptor.)
344         timespec last_modified;
345         struct stat buf;
346         if (stat(pathname.c_str(), &buf) != 0) {
347                 // Probably some sort of protocol, so can't stat.
348                 last_modified.tv_sec = -1;
349         } else {
350                 last_modified = buf.st_mtim;
351         }
352
353         AVDictionary *opts = nullptr;
354         av_dict_set(&opts, "fflags", "nobuffer", 0);
355
356         auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, &opts, AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
357         if (format_ctx == nullptr) {
358                 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
359                 return false;
360         }
361
362         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
363                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
364                 return false;
365         }
366
367         int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
368         if (video_stream_index == -1) {
369                 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
370                 return false;
371         }
372
373         int audio_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_AUDIO);
374
375         // Open video decoder.
376         const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
377         AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
378         video_timebase = format_ctx->streams[video_stream_index]->time_base;
379         AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
380         if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
381                 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
382                 return false;
383         }
384         if (video_codec == nullptr) {
385                 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
386                 return false;
387         }
388         if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
389                 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
390                 return false;
391         }
392         unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
393                 video_codec_ctx.get(), avcodec_close);
394
395         // Open audio decoder, if we have audio.
396         AVCodecContextWithDeleter audio_codec_ctx;
397         if (audio_stream_index != -1) {
398                 audio_codec_ctx = avcodec_alloc_context3_unique(nullptr);
399                 const AVCodecParameters *audio_codecpar = format_ctx->streams[audio_stream_index]->codecpar;
400                 audio_timebase = format_ctx->streams[audio_stream_index]->time_base;
401                 if (avcodec_parameters_to_context(audio_codec_ctx.get(), audio_codecpar) < 0) {
402                         fprintf(stderr, "%s: Cannot fill audio codec parameters\n", pathname.c_str());
403                         return false;
404                 }
405                 AVCodec *audio_codec = avcodec_find_decoder(audio_codecpar->codec_id);
406                 if (audio_codec == nullptr) {
407                         fprintf(stderr, "%s: Cannot find audio decoder\n", pathname.c_str());
408                         return false;
409                 }
410                 if (avcodec_open2(audio_codec_ctx.get(), audio_codec, nullptr) < 0) {
411                         fprintf(stderr, "%s: Cannot open audio decoder\n", pathname.c_str());
412                         return false;
413                 }
414         }
415         unique_ptr<AVCodecContext, decltype(avcodec_close)*> audio_codec_ctx_cleanup(
416                 audio_codec_ctx.get(), avcodec_close);
417
418         internal_rewind();
419
420         // Main loop.
421         while (!producer_thread_should_quit.should_quit()) {
422                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
423                         return true;
424                 }
425                 UniqueFrame audio_frame = audio_frame_allocator->alloc_frame();
426                 AudioFormat audio_format;
427
428                 int64_t audio_pts;
429                 bool error;
430                 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(), audio_codec_ctx.get(),
431                         pathname, video_stream_index, audio_stream_index, audio_frame.get(), &audio_format, &audio_pts, &error);
432                 if (error) {
433                         return false;
434                 }
435                 if (frame == nullptr) {
436                         // EOF. Loop back to the start if we can.
437                         if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
438                                 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
439                                 return true;
440                         }
441                         if (video_codec_ctx != nullptr) {
442                                 avcodec_flush_buffers(video_codec_ctx.get());
443                         }
444                         if (audio_codec_ctx != nullptr) {
445                                 avcodec_flush_buffers(audio_codec_ctx.get());
446                         }
447                         // If the file has changed since last time, return to get it reloaded.
448                         // Note that depending on how you move the file into place, you might
449                         // end up corrupting the one you're already playing, so this path
450                         // might not trigger.
451                         if (changed_since(pathname, last_modified)) {
452                                 return true;
453                         }
454                         internal_rewind();
455                         continue;
456                 }
457
458                 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
459                 UniqueFrame video_frame = make_video_frame(frame.get(), pathname, &error);
460                 if (error) {
461                         return false;
462                 }
463
464                 for ( ;; ) {
465                         if (last_pts == 0 && pts_origin == 0) {
466                                 pts_origin = frame->pts;        
467                         }
468                         next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
469                         video_frame->received_timestamp = next_frame_start;
470                         audio_frame->received_timestamp = next_frame_start;
471                         bool finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
472                         if (finished_wakeup) {
473                                 if (audio_frame->len > 0) {
474                                         assert(audio_pts != -1);
475                                 }
476                                 frame_callback(frame->pts, video_timebase, audio_pts, audio_timebase, timecode++,
477                                         video_frame.get_and_release(), 0, video_format,
478                                         audio_frame.get_and_release(), 0, audio_format);
479                                 break;
480                         } else {
481                                 if (producer_thread_should_quit.should_quit()) break;
482
483                                 bool rewound = false;
484                                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
485                                         return true;
486                                 }
487                                 // If we just rewound, drop this frame on the floor and be done.
488                                 if (rewound) {
489                                         break;
490                                 }
491                                 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
492                                 // but if it's now in the past, we'll reset the origin, so that we don't
493                                 // generate a huge backlog of frames that we need to run through quickly.
494                                 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
495                                 steady_clock::time_point now = steady_clock::now();
496                                 if (next_frame_start < now) {
497                                         pts_origin = frame->pts;
498                                         start = next_frame_start = now;
499                                 }
500                         }
501                 }
502                 last_pts = frame->pts;
503         }
504         return true;
505 }
506
507 void FFmpegCapture::internal_rewind()
508 {                               
509         pts_origin = last_pts = 0;
510         start = next_frame_start = steady_clock::now();
511 }
512
513 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
514 {
515         // Process any queued commands from other threads.
516         vector<QueuedCommand> commands;
517         {
518                 lock_guard<mutex> lock(queue_mu);
519                 swap(commands, command_queue);
520         }
521         for (const QueuedCommand &cmd : commands) {
522                 switch (cmd.command) {
523                 case QueuedCommand::REWIND:
524                         if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
525                                 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
526                         }
527                         // If the file has changed since last time, return to get it reloaded.
528                         // Note that depending on how you move the file into place, you might
529                         // end up corrupting the one you're already playing, so this path
530                         // might not trigger.
531                         if (changed_since(pathname, last_modified)) {
532                                 return true;
533                         }
534                         internal_rewind();
535                         if (rewound != nullptr) {
536                                 *rewound = true;
537                         }
538                         break;
539
540                 case QueuedCommand::CHANGE_RATE:
541                         // Change the origin to the last played frame.
542                         start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
543                         pts_origin = last_pts;
544                         rate = cmd.new_rate;
545                         break;
546                 }
547         }
548         return false;
549 }
550
551 namespace {
552
553 }  // namespace
554
555 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
556         const std::string &pathname, int video_stream_index, int audio_stream_index,
557         FrameAllocator::Frame *audio_frame, AudioFormat *audio_format, int64_t *audio_pts, bool *error)
558 {
559         *error = false;
560
561         // Read packets until we have a frame or there are none left.
562         bool frame_finished = false;
563         AVFrameWithDeleter audio_avframe = av_frame_alloc_unique();
564         AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
565         bool eof = false;
566         *audio_pts = -1;
567         do {
568                 AVPacket pkt;
569                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
570                         &pkt, av_packet_unref);
571                 av_init_packet(&pkt);
572                 pkt.data = nullptr;
573                 pkt.size = 0;
574                 if (av_read_frame(format_ctx, &pkt) == 0) {
575                         if (pkt.stream_index == audio_stream_index && audio_callback != nullptr) {
576                                 audio_callback(&pkt, format_ctx->streams[audio_stream_index]->time_base);
577                         }
578                         if (pkt.stream_index == video_stream_index) {
579                                 if (avcodec_send_packet(video_codec_ctx, &pkt) < 0) {
580                                         fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
581                                         *error = true;
582                                         return AVFrameWithDeleter(nullptr);
583                                 }
584                         } else if (pkt.stream_index == audio_stream_index) {
585                                 if (*audio_pts == -1) {
586                                         *audio_pts = pkt.pts;
587                                 }
588                                 if (avcodec_send_packet(audio_codec_ctx, &pkt) < 0) {
589                                         fprintf(stderr, "%s: Cannot send packet to audio codec.\n", pathname.c_str());
590                                         *error = true;
591                                         return AVFrameWithDeleter(nullptr);
592                                 }
593                         }
594                 } else {
595                         eof = true;  // Or error, but ignore that for the time being.
596                 }
597
598                 // Decode audio, if any.
599                 if (*audio_pts != -1) {
600                         for ( ;; ) {
601                                 int err = avcodec_receive_frame(audio_codec_ctx, audio_avframe.get());
602                                 if (err == 0) {
603                                         convert_audio(audio_avframe.get(), audio_frame, audio_format);
604                                 } else if (err == AVERROR(EAGAIN)) {
605                                         break;
606                                 } else {
607                                         fprintf(stderr, "%s: Cannot receive frame from audio codec.\n", pathname.c_str());
608                                         *error = true;
609                                         return AVFrameWithDeleter(nullptr);
610                                 }
611                         }
612                 }
613
614                 // Decode video, if we have a frame.
615                 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
616                 if (err == 0) {
617                         frame_finished = true;
618                         break;
619                 } else if (err != AVERROR(EAGAIN)) {
620                         fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
621                         *error = true;
622                         return AVFrameWithDeleter(nullptr);
623                 }
624         } while (!eof);
625
626         if (frame_finished)
627                 return video_avframe;
628         else
629                 return AVFrameWithDeleter(nullptr);
630 }
631
632 void FFmpegCapture::convert_audio(const AVFrame *audio_avframe, FrameAllocator::Frame *audio_frame, AudioFormat *audio_format)
633 {
634         // Decide on a format. If there already is one in this audio frame,
635         // we're pretty much forced to use it. If not, we try to find an exact match.
636         // If that still doesn't work, we default to 32-bit signed chunked
637         // (float would be nice, but there's really no way to signal that yet).
638         AVSampleFormat dst_format;
639         if (audio_format->bits_per_sample == 0) {
640                 switch (audio_avframe->format) {
641                 case AV_SAMPLE_FMT_S16:
642                 case AV_SAMPLE_FMT_S16P:
643                         audio_format->bits_per_sample = 16;
644                         dst_format = AV_SAMPLE_FMT_S16;
645                         break;
646                 case AV_SAMPLE_FMT_S32:
647                 case AV_SAMPLE_FMT_S32P:
648                 default:
649                         audio_format->bits_per_sample = 32;
650                         dst_format = AV_SAMPLE_FMT_S32;
651                         break;
652                 }
653         } else if (audio_format->bits_per_sample == 16) {
654                 dst_format = AV_SAMPLE_FMT_S16;
655         } else if (audio_format->bits_per_sample == 32) {
656                 dst_format = AV_SAMPLE_FMT_S32;
657         } else {
658                 assert(false);
659         }
660         audio_format->num_channels = 2;
661
662         int64_t channel_layout = audio_avframe->channel_layout;
663         if (channel_layout == 0) {
664                 channel_layout = av_get_default_channel_layout(audio_avframe->channels);
665         }
666
667         if (resampler == nullptr ||
668             audio_avframe->format != last_src_format ||
669             dst_format != last_dst_format ||
670             channel_layout != last_channel_layout ||
671             av_frame_get_sample_rate(audio_avframe) != last_sample_rate) {
672                 avresample_free(&resampler);
673                 resampler = avresample_alloc_context();
674                 if (resampler == nullptr) {
675                         fprintf(stderr, "Allocating resampler failed.\n");
676                         exit(1);
677                 }
678
679                 av_opt_set_int(resampler, "in_channel_layout",  channel_layout,                             0);
680                 av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_STEREO,                        0);
681                 av_opt_set_int(resampler, "in_sample_rate",     av_frame_get_sample_rate(audio_avframe),    0);
682                 av_opt_set_int(resampler, "out_sample_rate",    OUTPUT_FREQUENCY,                           0);
683                 av_opt_set_int(resampler, "in_sample_fmt",      audio_avframe->format,                      0);
684                 av_opt_set_int(resampler, "out_sample_fmt",     dst_format,                                 0);
685
686                 if (avresample_open(resampler) < 0) {
687                         fprintf(stderr, "Could not open resample context.\n");
688                         exit(1);
689                 }
690
691                 last_src_format = AVSampleFormat(audio_avframe->format);
692                 last_dst_format = dst_format;
693                 last_channel_layout = channel_layout;
694                 last_sample_rate = av_frame_get_sample_rate(audio_avframe);
695         }
696
697         size_t bytes_per_sample = (audio_format->bits_per_sample / 8) * 2;
698         size_t num_samples_room = (audio_frame->size - audio_frame->len) / bytes_per_sample;
699
700         uint8_t *data = audio_frame->data + audio_frame->len;
701         int out_samples = avresample_convert(resampler, &data, 0, num_samples_room,
702                 const_cast<uint8_t **>(audio_avframe->data), audio_avframe->linesize[0], audio_avframe->nb_samples);
703         if (out_samples < 0) {
704                 fprintf(stderr, "Audio conversion failed.\n");
705                 exit(1);
706         }
707
708         audio_frame->len += out_samples * bytes_per_sample;
709 }
710
711 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
712 {
713         VideoFormat video_format;
714         video_format.width = width;
715         video_format.height = height;
716         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
717                 video_format.stride = width * 4;
718         } else if (pixel_format == FFmpegCapture::PixelFormat_NV12) {
719                 video_format.stride = width;
720         } else {
721                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
722                 video_format.stride = width;
723         }
724         video_format.frame_rate_nom = video_timebase.den;
725         video_format.frame_rate_den = av_frame_get_pkt_duration(frame) * video_timebase.num;
726         if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
727                 // Invalid frame rate.
728                 video_format.frame_rate_nom = 60;
729                 video_format.frame_rate_den = 1;
730         }
731         video_format.has_signal = true;
732         video_format.is_connected = true;
733         return video_format;
734 }
735
736 UniqueFrame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
737 {
738         *error = false;
739
740         UniqueFrame video_frame(video_frame_allocator->alloc_frame());
741         if (video_frame->data == nullptr) {
742                 return video_frame;
743         }
744
745         if (sws_ctx == nullptr ||
746             sws_last_width != frame->width ||
747             sws_last_height != frame->height ||
748             sws_last_src_format != frame->format) {
749                 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
750                 sws_ctx.reset(
751                         sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
752                                 width, height, sws_dst_format,
753                                 SWS_BICUBIC, nullptr, nullptr, nullptr));
754                 sws_last_width = frame->width;
755                 sws_last_height = frame->height;
756                 sws_last_src_format = frame->format;
757         }
758         if (sws_ctx == nullptr) {
759                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
760                 *error = true;
761                 return video_frame;
762         }
763
764         uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
765         int linesizes[4] = { 0, 0, 0, 0 };
766         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
767                 pic_data[0] = video_frame->data;
768                 linesizes[0] = width * 4;
769                 video_frame->len = (width * 4) * height;
770         } else if (pixel_format == PixelFormat_NV12) {
771                 pic_data[0] = video_frame->data;
772                 linesizes[0] = width;
773
774                 pic_data[1] = pic_data[0] + width * height;
775                 linesizes[1] = width;
776
777                 video_frame->len = (width * 2) * height;
778
779                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
780                 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
781         } else {
782                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
783                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
784
785                 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
786                 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
787
788                 pic_data[0] = video_frame->data;
789                 linesizes[0] = width;
790
791                 pic_data[1] = pic_data[0] + width * height;
792                 linesizes[1] = chroma_width;
793
794                 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
795                 linesizes[2] = chroma_width;
796
797                 video_frame->len = width * height + 2 * chroma_width * chroma_height;
798
799                 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
800         }
801         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
802
803         return video_frame;
804 }
805
806 int FFmpegCapture::interrupt_cb_thunk(void *unique)
807 {
808         return reinterpret_cast<FFmpegCapture *>(unique)->interrupt_cb();
809 }
810
811 int FFmpegCapture::interrupt_cb()
812 {
813         return should_interrupt.load();
814 }