]> git.sesse.net Git - nageru/blob - ffmpeg_capture.cpp
Correct FFmpeg capture audio timestamps for non-locked audio.
[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         last_frame = steady_clock::now();
215
216         avformat_network_init();  // In case someone wants this.
217 }
218
219 FFmpegCapture::~FFmpegCapture()
220 {
221         if (has_dequeue_callbacks) {
222                 dequeue_cleanup_callback();
223         }
224         avresample_free(&resampler);
225 }
226
227 void FFmpegCapture::configure_card()
228 {
229         if (video_frame_allocator == nullptr) {
230                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
231                 set_video_frame_allocator(owned_video_frame_allocator.get());
232         }
233         if (audio_frame_allocator == nullptr) {
234                 // Audio can come out in pretty large chunks, so increase from the default 1 MB.
235                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(1 << 20, NUM_QUEUED_AUDIO_FRAMES));
236                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
237         }
238 }
239
240 void FFmpegCapture::start_bm_capture()
241 {
242         if (running) {
243                 return;
244         }
245         running = true;
246         producer_thread_should_quit.unquit();
247         producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
248 }
249
250 void FFmpegCapture::stop_dequeue_thread()
251 {
252         if (!running) {
253                 return;
254         }
255         running = false;
256         producer_thread_should_quit.quit();
257         producer_thread.join();
258 }
259
260 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
261 {
262         // Note: This will never really be shown in the UI.
263         VideoMode mode;
264
265         char buf[256];
266         snprintf(buf, sizeof(buf), "%ux%u", width, height);
267         mode.name = buf;
268         
269         mode.autodetect = false;
270         mode.width = width;
271         mode.height = height;
272         mode.frame_rate_num = 60;
273         mode.frame_rate_den = 1;
274         mode.interlaced = false;
275
276         return {{ 0, mode }};
277 }
278
279 void FFmpegCapture::producer_thread_func()
280 {
281         char thread_name[16];
282         snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
283         pthread_setname_np(pthread_self(), thread_name);
284
285         while (!producer_thread_should_quit.should_quit()) {
286                 string pathname = search_for_file(filename);
287                 if (filename.empty()) {
288                         fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename.c_str());
289                         send_disconnected_frame();
290                         producer_thread_should_quit.sleep_for(seconds(1));
291                         continue;
292                 }
293                 should_interrupt = false;
294                 if (!play_video(pathname)) {
295                         // Error.
296                         fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
297                         send_disconnected_frame();
298                         producer_thread_should_quit.sleep_for(seconds(1));
299                         continue;
300                 }
301
302                 // Probably just EOF, will exit the loop above on next test.
303         }
304
305         if (has_dequeue_callbacks) {
306                 dequeue_cleanup_callback();
307                 has_dequeue_callbacks = false;
308         }
309 }
310
311 void FFmpegCapture::send_disconnected_frame()
312 {
313         // Send an empty frame to signal that we have no signal anymore.
314         FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
315         if (video_frame.data) {
316                 VideoFormat video_format;
317                 video_format.width = width;
318                 video_format.height = height;
319                 video_format.frame_rate_nom = 60;
320                 video_format.frame_rate_den = 1;
321                 video_format.is_connected = false;
322                 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
323                         video_format.stride = width * 4;
324                         video_frame.len = width * height * 4;
325                 } else {
326                         video_format.stride = width;
327                         current_frame_ycbcr_format.luma_coefficients = YCBCR_REC_709;
328                         current_frame_ycbcr_format.full_range = true;
329                         current_frame_ycbcr_format.num_levels = 256;
330                         current_frame_ycbcr_format.chroma_subsampling_x = 2;
331                         current_frame_ycbcr_format.chroma_subsampling_y = 2;
332                         current_frame_ycbcr_format.cb_x_position = 0.0f;
333                         current_frame_ycbcr_format.cb_y_position = 0.0f;
334                         current_frame_ycbcr_format.cr_x_position = 0.0f;
335                         current_frame_ycbcr_format.cr_y_position = 0.0f;
336                         video_frame.len = width * height * 2;
337                 }
338                 memset(video_frame.data, 0, video_frame.len);
339
340                 frame_callback(-1, AVRational{1, TIMEBASE}, -1, AVRational{1, TIMEBASE}, timecode++,
341                         video_frame, /*video_offset=*/0, video_format,
342                         FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
343                 last_frame_was_connected = false;
344         }
345 }
346
347 bool FFmpegCapture::play_video(const string &pathname)
348 {
349         // Note: Call before open, not after; otherwise, there's a race.
350         // (There is now, too, but it tips the correct way. We could use fstat()
351         // if we had the file descriptor.)
352         timespec last_modified;
353         struct stat buf;
354         if (stat(pathname.c_str(), &buf) != 0) {
355                 // Probably some sort of protocol, so can't stat.
356                 last_modified.tv_sec = -1;
357         } else {
358                 last_modified = buf.st_mtim;
359         }
360
361         AVDictionary *opts = nullptr;
362         av_dict_set(&opts, "fflags", "nobuffer", 0);
363
364         auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, &opts, AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
365         if (format_ctx == nullptr) {
366                 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
367                 return false;
368         }
369
370         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
371                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
372                 return false;
373         }
374
375         int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
376         if (video_stream_index == -1) {
377                 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
378                 return false;
379         }
380
381         int audio_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_AUDIO);
382
383         // Open video decoder.
384         const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
385         AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
386         video_timebase = format_ctx->streams[video_stream_index]->time_base;
387         AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
388         if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
389                 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
390                 return false;
391         }
392         if (video_codec == nullptr) {
393                 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
394                 return false;
395         }
396         if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
397                 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
398                 return false;
399         }
400         unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
401                 video_codec_ctx.get(), avcodec_close);
402
403         // Open audio decoder, if we have audio.
404         AVCodecContextWithDeleter audio_codec_ctx;
405         if (audio_stream_index != -1) {
406                 audio_codec_ctx = avcodec_alloc_context3_unique(nullptr);
407                 const AVCodecParameters *audio_codecpar = format_ctx->streams[audio_stream_index]->codecpar;
408                 audio_timebase = format_ctx->streams[audio_stream_index]->time_base;
409                 if (avcodec_parameters_to_context(audio_codec_ctx.get(), audio_codecpar) < 0) {
410                         fprintf(stderr, "%s: Cannot fill audio codec parameters\n", pathname.c_str());
411                         return false;
412                 }
413                 AVCodec *audio_codec = avcodec_find_decoder(audio_codecpar->codec_id);
414                 if (audio_codec == nullptr) {
415                         fprintf(stderr, "%s: Cannot find audio decoder\n", pathname.c_str());
416                         return false;
417                 }
418                 if (avcodec_open2(audio_codec_ctx.get(), audio_codec, nullptr) < 0) {
419                         fprintf(stderr, "%s: Cannot open audio decoder\n", pathname.c_str());
420                         return false;
421                 }
422         }
423         unique_ptr<AVCodecContext, decltype(avcodec_close)*> audio_codec_ctx_cleanup(
424                 audio_codec_ctx.get(), avcodec_close);
425
426         internal_rewind();
427
428         // Main loop.
429         bool first_frame = true;
430         while (!producer_thread_should_quit.should_quit()) {
431                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
432                         return true;
433                 }
434                 UniqueFrame audio_frame = audio_frame_allocator->alloc_frame();
435                 AudioFormat audio_format;
436
437                 int64_t audio_pts;
438                 bool error;
439                 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(), audio_codec_ctx.get(),
440                         pathname, video_stream_index, audio_stream_index, audio_frame.get(), &audio_format, &audio_pts, &error);
441                 if (error) {
442                         return false;
443                 }
444                 if (frame == nullptr) {
445                         // EOF. Loop back to the start if we can.
446                         if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
447                                 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
448                                 return true;
449                         }
450                         if (video_codec_ctx != nullptr) {
451                                 avcodec_flush_buffers(video_codec_ctx.get());
452                         }
453                         if (audio_codec_ctx != nullptr) {
454                                 avcodec_flush_buffers(audio_codec_ctx.get());
455                         }
456                         // If the file has changed since last time, return to get it reloaded.
457                         // Note that depending on how you move the file into place, you might
458                         // end up corrupting the one you're already playing, so this path
459                         // might not trigger.
460                         if (changed_since(pathname, last_modified)) {
461                                 return true;
462                         }
463                         internal_rewind();
464                         continue;
465                 }
466
467                 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
468                 UniqueFrame video_frame = make_video_frame(frame.get(), pathname, &error);
469                 if (error) {
470                         return false;
471                 }
472
473                 for ( ;; ) {
474                         if (last_pts == 0 && pts_origin == 0) {
475                                 pts_origin = frame->pts;        
476                         }
477                         next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
478                         if (first_frame && last_frame_was_connected) {
479                                 // If reconnect took more than one second, this is probably a live feed,
480                                 // and we should reset the resampler. (Or the rate is really, really low,
481                                 // in which case a reset on the first frame is fine anyway.)
482                                 if (duration<double>(next_frame_start - last_frame).count() >= 1.0) {
483                                         last_frame_was_connected = false;
484                                 }
485                         }
486                         video_frame->received_timestamp = next_frame_start;
487
488                         // The easiest way to get all the rate conversions etc. right is to move the
489                         // audio PTS into the video PTS timebase and go from there. (We'll get some
490                         // rounding issues, but they should not be a big problem.)
491                         int64_t audio_pts_as_video_pts = av_rescale_q(audio_pts, audio_timebase, video_timebase);
492                         audio_frame->received_timestamp = compute_frame_start(audio_pts_as_video_pts, pts_origin, video_timebase, start, rate);
493
494                         if (audio_frame->len != 0) {
495                                 // The received timestamps in Nageru are measured after we've just received the frame.
496                                 // However, pts (especially audio pts) is at the _beginning_ of the frame.
497                                 // If we have locked audio, the distinction doesn't really matter, as pts is
498                                 // on a relative scale and a fixed offset is fine. But if we don't, we will have
499                                 // a different number of samples each time, which will cause huge audio jitter
500                                 // and throw off the resampler.
501                                 //
502                                 // In a sense, we should have compensated by adding the frame and audio lengths
503                                 // to video_frame->received_timestamp and audio_frame->received_timestamp respectively,
504                                 // but that would mean extra waiting in sleep_until(). All we need is that they
505                                 // are correct relative to each other, though (and to the other frames we send),
506                                 // so just align the end of the audio frame, and we're fine.
507                                 size_t num_samples = (audio_frame->len * 8) / audio_format.bits_per_sample / audio_format.num_channels;
508                                 double offset = double(num_samples) / OUTPUT_FREQUENCY -
509                                         double(video_format.frame_rate_den) / video_format.frame_rate_nom;
510                                 audio_frame->received_timestamp += duration_cast<steady_clock::duration>(duration<double>(offset));
511                         }
512
513                         bool finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
514                         if (finished_wakeup) {
515                                 if (audio_frame->len > 0) {
516                                         assert(audio_pts != -1);
517                                 }
518                                 if (!last_frame_was_connected) {
519                                         // We're recovering from an error (or really slow load, see above).
520                                         // Make sure to get the audio resampler reset. (This is a hack;
521                                         // ideally, the frame callback should just accept a way to signal
522                                         // audio discontinuity.)
523                                         timecode += MAX_FPS * 2 + 1;
524                                 }
525                                 frame_callback(frame->pts, video_timebase, audio_pts, audio_timebase, timecode++,
526                                         video_frame.get_and_release(), 0, video_format,
527                                         audio_frame.get_and_release(), 0, audio_format);
528                                 first_frame = false;
529                                 last_frame = steady_clock::now();
530                                 last_frame_was_connected = true;
531                                 break;
532                         } else {
533                                 if (producer_thread_should_quit.should_quit()) break;
534
535                                 bool rewound = false;
536                                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
537                                         return true;
538                                 }
539                                 // If we just rewound, drop this frame on the floor and be done.
540                                 if (rewound) {
541                                         break;
542                                 }
543                                 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
544                                 // but if it's now in the past, we'll reset the origin, so that we don't
545                                 // generate a huge backlog of frames that we need to run through quickly.
546                                 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
547                                 steady_clock::time_point now = steady_clock::now();
548                                 if (next_frame_start < now) {
549                                         pts_origin = frame->pts;
550                                         start = next_frame_start = now;
551                                 }
552                         }
553                 }
554                 last_pts = frame->pts;
555         }
556         return true;
557 }
558
559 void FFmpegCapture::internal_rewind()
560 {                               
561         pts_origin = last_pts = 0;
562         start = next_frame_start = steady_clock::now();
563 }
564
565 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
566 {
567         // Process any queued commands from other threads.
568         vector<QueuedCommand> commands;
569         {
570                 lock_guard<mutex> lock(queue_mu);
571                 swap(commands, command_queue);
572         }
573         for (const QueuedCommand &cmd : commands) {
574                 switch (cmd.command) {
575                 case QueuedCommand::REWIND:
576                         if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
577                                 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
578                         }
579                         // If the file has changed since last time, return to get it reloaded.
580                         // Note that depending on how you move the file into place, you might
581                         // end up corrupting the one you're already playing, so this path
582                         // might not trigger.
583                         if (changed_since(pathname, last_modified)) {
584                                 return true;
585                         }
586                         internal_rewind();
587                         if (rewound != nullptr) {
588                                 *rewound = true;
589                         }
590                         break;
591
592                 case QueuedCommand::CHANGE_RATE:
593                         // Change the origin to the last played frame.
594                         start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
595                         pts_origin = last_pts;
596                         rate = cmd.new_rate;
597                         break;
598                 }
599         }
600         return false;
601 }
602
603 namespace {
604
605 }  // namespace
606
607 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
608         const std::string &pathname, int video_stream_index, int audio_stream_index,
609         FrameAllocator::Frame *audio_frame, AudioFormat *audio_format, int64_t *audio_pts, bool *error)
610 {
611         *error = false;
612
613         // Read packets until we have a frame or there are none left.
614         bool frame_finished = false;
615         AVFrameWithDeleter audio_avframe = av_frame_alloc_unique();
616         AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
617         bool eof = false;
618         *audio_pts = -1;
619         bool has_audio = false;
620         do {
621                 AVPacket pkt;
622                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
623                         &pkt, av_packet_unref);
624                 av_init_packet(&pkt);
625                 pkt.data = nullptr;
626                 pkt.size = 0;
627                 if (av_read_frame(format_ctx, &pkt) == 0) {
628                         if (pkt.stream_index == audio_stream_index && audio_callback != nullptr) {
629                                 audio_callback(&pkt, format_ctx->streams[audio_stream_index]->time_base);
630                         }
631                         if (pkt.stream_index == video_stream_index) {
632                                 if (avcodec_send_packet(video_codec_ctx, &pkt) < 0) {
633                                         fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
634                                         *error = true;
635                                         return AVFrameWithDeleter(nullptr);
636                                 }
637                         } else if (pkt.stream_index == audio_stream_index) {
638                                 has_audio = true;
639                                 if (avcodec_send_packet(audio_codec_ctx, &pkt) < 0) {
640                                         fprintf(stderr, "%s: Cannot send packet to audio codec.\n", pathname.c_str());
641                                         *error = true;
642                                         return AVFrameWithDeleter(nullptr);
643                                 }
644                         }
645                 } else {
646                         eof = true;  // Or error, but ignore that for the time being.
647                 }
648
649                 // Decode audio, if any.
650                 if (has_audio) {
651                         for ( ;; ) {
652                                 int err = avcodec_receive_frame(audio_codec_ctx, audio_avframe.get());
653                                 if (err == 0) {
654                                         if (*audio_pts == -1) {
655                                                 *audio_pts = audio_avframe->pts;
656                                         }
657                                         convert_audio(audio_avframe.get(), audio_frame, audio_format);
658                                 } else if (err == AVERROR(EAGAIN)) {
659                                         break;
660                                 } else {
661                                         fprintf(stderr, "%s: Cannot receive frame from audio codec.\n", pathname.c_str());
662                                         *error = true;
663                                         return AVFrameWithDeleter(nullptr);
664                                 }
665                         }
666                 }
667
668                 // Decode video, if we have a frame.
669                 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
670                 if (err == 0) {
671                         frame_finished = true;
672                         break;
673                 } else if (err != AVERROR(EAGAIN)) {
674                         fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
675                         *error = true;
676                         return AVFrameWithDeleter(nullptr);
677                 }
678         } while (!eof);
679
680         if (frame_finished)
681                 return video_avframe;
682         else
683                 return AVFrameWithDeleter(nullptr);
684 }
685
686 void FFmpegCapture::convert_audio(const AVFrame *audio_avframe, FrameAllocator::Frame *audio_frame, AudioFormat *audio_format)
687 {
688         // Decide on a format. If there already is one in this audio frame,
689         // we're pretty much forced to use it. If not, we try to find an exact match.
690         // If that still doesn't work, we default to 32-bit signed chunked
691         // (float would be nice, but there's really no way to signal that yet).
692         AVSampleFormat dst_format;
693         if (audio_format->bits_per_sample == 0) {
694                 switch (audio_avframe->format) {
695                 case AV_SAMPLE_FMT_S16:
696                 case AV_SAMPLE_FMT_S16P:
697                         audio_format->bits_per_sample = 16;
698                         dst_format = AV_SAMPLE_FMT_S16;
699                         break;
700                 case AV_SAMPLE_FMT_S32:
701                 case AV_SAMPLE_FMT_S32P:
702                 default:
703                         audio_format->bits_per_sample = 32;
704                         dst_format = AV_SAMPLE_FMT_S32;
705                         break;
706                 }
707         } else if (audio_format->bits_per_sample == 16) {
708                 dst_format = AV_SAMPLE_FMT_S16;
709         } else if (audio_format->bits_per_sample == 32) {
710                 dst_format = AV_SAMPLE_FMT_S32;
711         } else {
712                 assert(false);
713         }
714         audio_format->num_channels = 2;
715
716         int64_t channel_layout = audio_avframe->channel_layout;
717         if (channel_layout == 0) {
718                 channel_layout = av_get_default_channel_layout(audio_avframe->channels);
719         }
720
721         if (resampler == nullptr ||
722             audio_avframe->format != last_src_format ||
723             dst_format != last_dst_format ||
724             channel_layout != last_channel_layout ||
725             av_frame_get_sample_rate(audio_avframe) != last_sample_rate) {
726                 avresample_free(&resampler);
727                 resampler = avresample_alloc_context();
728                 if (resampler == nullptr) {
729                         fprintf(stderr, "Allocating resampler failed.\n");
730                         exit(1);
731                 }
732
733                 av_opt_set_int(resampler, "in_channel_layout",  channel_layout,                             0);
734                 av_opt_set_int(resampler, "out_channel_layout", AV_CH_LAYOUT_STEREO,                        0);
735                 av_opt_set_int(resampler, "in_sample_rate",     av_frame_get_sample_rate(audio_avframe),    0);
736                 av_opt_set_int(resampler, "out_sample_rate",    OUTPUT_FREQUENCY,                           0);
737                 av_opt_set_int(resampler, "in_sample_fmt",      audio_avframe->format,                      0);
738                 av_opt_set_int(resampler, "out_sample_fmt",     dst_format,                                 0);
739
740                 if (avresample_open(resampler) < 0) {
741                         fprintf(stderr, "Could not open resample context.\n");
742                         exit(1);
743                 }
744
745                 last_src_format = AVSampleFormat(audio_avframe->format);
746                 last_dst_format = dst_format;
747                 last_channel_layout = channel_layout;
748                 last_sample_rate = av_frame_get_sample_rate(audio_avframe);
749         }
750
751         size_t bytes_per_sample = (audio_format->bits_per_sample / 8) * 2;
752         size_t num_samples_room = (audio_frame->size - audio_frame->len) / bytes_per_sample;
753
754         uint8_t *data = audio_frame->data + audio_frame->len;
755         int out_samples = avresample_convert(resampler, &data, 0, num_samples_room,
756                 const_cast<uint8_t **>(audio_avframe->data), audio_avframe->linesize[0], audio_avframe->nb_samples);
757         if (out_samples < 0) {
758                 fprintf(stderr, "Audio conversion failed.\n");
759                 exit(1);
760         }
761
762         audio_frame->len += out_samples * bytes_per_sample;
763 }
764
765 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
766 {
767         VideoFormat video_format;
768         video_format.width = width;
769         video_format.height = height;
770         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
771                 video_format.stride = width * 4;
772         } else if (pixel_format == FFmpegCapture::PixelFormat_NV12) {
773                 video_format.stride = width;
774         } else {
775                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
776                 video_format.stride = width;
777         }
778         video_format.frame_rate_nom = video_timebase.den;
779         video_format.frame_rate_den = av_frame_get_pkt_duration(frame) * video_timebase.num;
780         if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
781                 // Invalid frame rate.
782                 video_format.frame_rate_nom = 60;
783                 video_format.frame_rate_den = 1;
784         }
785         video_format.has_signal = true;
786         video_format.is_connected = true;
787         return video_format;
788 }
789
790 UniqueFrame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
791 {
792         *error = false;
793
794         UniqueFrame video_frame(video_frame_allocator->alloc_frame());
795         if (video_frame->data == nullptr) {
796                 return video_frame;
797         }
798
799         if (sws_ctx == nullptr ||
800             sws_last_width != frame->width ||
801             sws_last_height != frame->height ||
802             sws_last_src_format != frame->format) {
803                 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
804                 sws_ctx.reset(
805                         sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
806                                 width, height, sws_dst_format,
807                                 SWS_BICUBIC, nullptr, nullptr, nullptr));
808                 sws_last_width = frame->width;
809                 sws_last_height = frame->height;
810                 sws_last_src_format = frame->format;
811         }
812         if (sws_ctx == nullptr) {
813                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
814                 *error = true;
815                 return video_frame;
816         }
817
818         uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
819         int linesizes[4] = { 0, 0, 0, 0 };
820         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
821                 pic_data[0] = video_frame->data;
822                 linesizes[0] = width * 4;
823                 video_frame->len = (width * 4) * height;
824         } else if (pixel_format == PixelFormat_NV12) {
825                 pic_data[0] = video_frame->data;
826                 linesizes[0] = width;
827
828                 pic_data[1] = pic_data[0] + width * height;
829                 linesizes[1] = width;
830
831                 video_frame->len = (width * 2) * height;
832
833                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
834                 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
835         } else {
836                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
837                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
838
839                 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
840                 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
841
842                 pic_data[0] = video_frame->data;
843                 linesizes[0] = width;
844
845                 pic_data[1] = pic_data[0] + width * height;
846                 linesizes[1] = chroma_width;
847
848                 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
849                 linesizes[2] = chroma_width;
850
851                 video_frame->len = width * height + 2 * chroma_width * chroma_height;
852
853                 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
854         }
855         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
856
857         return video_frame;
858 }
859
860 int FFmpegCapture::interrupt_cb_thunk(void *unique)
861 {
862         return reinterpret_cast<FFmpegCapture *>(unique)->interrupt_cb();
863 }
864
865 int FFmpegCapture::interrupt_cb()
866 {
867         return should_interrupt.load();
868 }