]> git.sesse.net Git - nageru/blob - nageru/ffmpeg_capture.cpp
Heed the Exif white point when playing back (MJPEG) video.
[nageru] / 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 <Eigen/Core>
31 #include <Eigen/LU>
32 #include <movit/colorspace_conversion_effect.h>
33
34 #include "bmusb/bmusb.h"
35 #include "shared/ffmpeg_raii.h"
36 #include "ffmpeg_util.h"
37 #include "flags.h"
38 #include "image_input.h"
39 #include "ref_counted_frame.h"
40 #include "shared/timebase.h"
41
42 #define FRAME_SIZE (8 << 20)  // 8 MB.
43
44 using namespace std;
45 using namespace std::chrono;
46 using namespace bmusb;
47 using namespace movit;
48 using namespace Eigen;
49
50 namespace {
51
52 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)
53 {
54         const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
55         return origin + duration_cast<steady_clock::duration>(pts / rate);
56 }
57
58 bool changed_since(const std::string &pathname, const timespec &ts)
59 {
60         if (ts.tv_sec < 0) {
61                 return false;
62         }
63         struct stat buf;
64         if (stat(pathname.c_str(), &buf) != 0) {
65                 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
66                 return false;
67         }
68         return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
69 }
70
71 bool is_full_range(const AVPixFmtDescriptor *desc)
72 {
73         // This is horrible, but there's no better way that I know of.
74         return (strchr(desc->name, 'j') != nullptr);
75 }
76
77 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
78 {
79         if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
80                 return AV_PIX_FMT_BGRA;
81         }
82         if (dst_format_type == FFmpegCapture::PixelFormat_NV12) {
83                 return AV_PIX_FMT_NV12;
84         }
85
86         assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
87
88         // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
89         // and be done with it. It's too strange to spend a lot of time on.
90         // (Let's hope there's no alpha.)
91         const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
92         if (src_desc == nullptr ||
93             src_desc->nb_components != 3 ||
94             (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
95                 return AV_PIX_FMT_YUV444P;
96         }
97
98         // The best for us would be Cb and Cr together if possible,
99         // but FFmpeg doesn't support that except in the special case of
100         // NV12, so we need to go to planar even for the case of NV12.
101         // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
102         // that matches in color range. (This will also include the case of
103         // the source format already being acceptable.)
104         bool src_full_range = is_full_range(src_desc);
105         const char *best_format = "yuv444p";
106         unsigned best_score = numeric_limits<unsigned>::max();
107         for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
108              desc;
109              desc = av_pix_fmt_desc_next(desc)) {
110                 // Find planar Y'CbCr formats only.
111                 if (desc->nb_components != 3) continue;
112                 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
113                 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
114                 if (desc->comp[0].plane != 0 ||
115                     desc->comp[1].plane != 1 ||
116                     desc->comp[2].plane != 2) continue;
117
118                 // 8-bit formats only.
119                 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
120                 if (desc->comp[0].depth != 8) continue;
121
122                 // Same or better chroma resolution only.
123                 int chroma_w_diff = desc->log2_chroma_w - src_desc->log2_chroma_w;
124                 int chroma_h_diff = desc->log2_chroma_h - src_desc->log2_chroma_h;
125                 if (chroma_w_diff < 0 || chroma_h_diff < 0)
126                         continue;
127
128                 // Matching full/limited range only.
129                 if (is_full_range(desc) != src_full_range)
130                         continue;
131
132                 // Pick something with as little excess chroma resolution as possible.
133                 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
134                 if (score < best_score) {
135                         best_score = score;
136                         best_format = desc->name;
137                 }
138         }
139         return av_get_pix_fmt(best_format);
140 }
141
142 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame, bool is_mjpeg)
143 {
144         YCbCrFormat format;
145         AVColorSpace colorspace = frame->colorspace;
146         switch (colorspace) {
147         case AVCOL_SPC_BT709:
148                 format.luma_coefficients = YCBCR_REC_709;
149                 break;
150         case AVCOL_SPC_BT470BG:
151         case AVCOL_SPC_SMPTE170M:
152         case AVCOL_SPC_SMPTE240M:
153                 format.luma_coefficients = YCBCR_REC_601;
154                 break;
155         case AVCOL_SPC_BT2020_NCL:
156                 format.luma_coefficients = YCBCR_REC_2020;
157                 break;
158         case AVCOL_SPC_UNSPECIFIED:
159                 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
160                 break;
161         default:
162                 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
163                         colorspace);
164                 format.luma_coefficients = YCBCR_REC_709;
165                 break;
166         }
167
168         format.full_range = is_full_range(desc);
169         format.num_levels = 1 << desc->comp[0].depth;
170         format.chroma_subsampling_x = 1 << desc->log2_chroma_w;
171         format.chroma_subsampling_y = 1 << desc->log2_chroma_h;
172
173         switch (frame->chroma_location) {
174         case AVCHROMA_LOC_LEFT:
175                 format.cb_x_position = 0.0;
176                 format.cb_y_position = 0.5;
177                 break;
178         case AVCHROMA_LOC_CENTER:
179                 format.cb_x_position = 0.5;
180                 format.cb_y_position = 0.5;
181                 break;
182         case AVCHROMA_LOC_TOPLEFT:
183                 format.cb_x_position = 0.0;
184                 format.cb_y_position = 0.0;
185                 break;
186         case AVCHROMA_LOC_TOP:
187                 format.cb_x_position = 0.5;
188                 format.cb_y_position = 0.0;
189                 break;
190         case AVCHROMA_LOC_BOTTOMLEFT:
191                 format.cb_x_position = 0.0;
192                 format.cb_y_position = 1.0;
193                 break;
194         case AVCHROMA_LOC_BOTTOM:
195                 format.cb_x_position = 0.5;
196                 format.cb_y_position = 1.0;
197                 break;
198         default:
199                 fprintf(stderr, "Unknown chroma location coefficient enum %d from FFmpeg; choosing center.\n",
200                         frame->chroma_location);
201                 format.cb_x_position = 0.5;
202                 format.cb_y_position = 0.5;
203                 break;
204         }
205
206         if (is_mjpeg && !format.full_range) {
207                 // Limited-range MJPEG is only detected by FFmpeg whenever a special
208                 // JPEG comment is set, which means that in practice, the stream is
209                 // almost certainly generated by Futatabi. Override FFmpeg's forced
210                 // MJPEG defaults (it disregards the values set in the mux) with what
211                 // Futatabi sets.
212                 format.luma_coefficients = YCBCR_REC_709;
213                 format.cb_x_position = 0.0;
214                 format.cb_y_position = 0.5;
215         }
216
217         format.cr_x_position = format.cb_x_position;
218         format.cr_y_position = format.cb_y_position;
219         return format;
220 }
221
222 RGBTriplet get_neutral_color(AVDictionary *metadata)
223 {
224         if (metadata == nullptr) {
225                 return RGBTriplet(1.0f, 1.0f, 1.0f);
226         }
227         AVDictionaryEntry *entry = av_dict_get(metadata, "WhitePoint", nullptr, 0);
228         if (entry == nullptr) {
229                 return RGBTriplet(1.0f, 1.0f, 1.0f);
230         }
231
232         unsigned x_nom, x_den, y_nom, y_den;
233         if (sscanf(entry->value, " %u:%u , %u:%u", &x_nom, &x_den, &y_nom, &y_den) != 4) {
234                 fprintf(stderr, "WARNING: Unable to parse white point '%s', using default white point\n", entry->value);
235                 return RGBTriplet(1.0f, 1.0f, 1.0f);
236         }
237
238         double x = double(x_nom) / x_den;
239         double y = double(y_nom) / y_den;
240         double z = 1.0 - x - y;
241
242         Matrix3d rgb_to_xyz_matrix = movit::ColorspaceConversionEffect::get_xyz_matrix(COLORSPACE_sRGB);
243         Vector3d rgb = rgb_to_xyz_matrix.inverse() * Vector3d(x, y, z);
244
245         return RGBTriplet(rgb[0], rgb[1], rgb[2]);
246 }
247
248 }  // namespace
249
250 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
251         : filename(filename), width(width), height(height), video_timebase{1, 1}
252 {
253         description = "Video: " + filename;
254
255         last_frame = steady_clock::now();
256
257         avformat_network_init();  // In case someone wants this.
258 }
259
260 FFmpegCapture::~FFmpegCapture()
261 {
262         if (has_dequeue_callbacks) {
263                 dequeue_cleanup_callback();
264         }
265         swr_free(&resampler);
266 }
267
268 void FFmpegCapture::configure_card()
269 {
270         if (video_frame_allocator == nullptr) {
271                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
272                 set_video_frame_allocator(owned_video_frame_allocator.get());
273         }
274         if (audio_frame_allocator == nullptr) {
275                 // Audio can come out in pretty large chunks, so increase from the default 1 MB.
276                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(1 << 20, NUM_QUEUED_AUDIO_FRAMES));
277                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
278         }
279 }
280
281 void FFmpegCapture::start_bm_capture()
282 {
283         if (running) {
284                 return;
285         }
286         running = true;
287         producer_thread_should_quit.unquit();
288         producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
289 }
290
291 void FFmpegCapture::stop_dequeue_thread()
292 {
293         if (!running) {
294                 return;
295         }
296         running = false;
297         producer_thread_should_quit.quit();
298         producer_thread.join();
299 }
300
301 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
302 {
303         // Note: This will never really be shown in the UI.
304         VideoMode mode;
305
306         char buf[256];
307         snprintf(buf, sizeof(buf), "%ux%u", width, height);
308         mode.name = buf;
309         
310         mode.autodetect = false;
311         mode.width = width;
312         mode.height = height;
313         mode.frame_rate_num = 60;
314         mode.frame_rate_den = 1;
315         mode.interlaced = false;
316
317         return {{ 0, mode }};
318 }
319
320 void FFmpegCapture::producer_thread_func()
321 {
322         char thread_name[16];
323         snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
324         pthread_setname_np(pthread_self(), thread_name);
325
326         while (!producer_thread_should_quit.should_quit()) {
327                 string filename_copy;
328                 {
329                         lock_guard<mutex> lock(filename_mu);
330                         filename_copy = filename;
331                 }
332
333                 string pathname = search_for_file(filename_copy);
334                 if (pathname.empty()) {
335                         fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename_copy.c_str());
336                         send_disconnected_frame();
337                         producer_thread_should_quit.sleep_for(seconds(1));
338                         continue;
339                 }
340                 should_interrupt = false;
341                 if (!play_video(pathname)) {
342                         // Error.
343                         fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
344                         send_disconnected_frame();
345                         producer_thread_should_quit.sleep_for(seconds(1));
346                         continue;
347                 }
348
349                 // Probably just EOF, will exit the loop above on next test.
350         }
351
352         if (has_dequeue_callbacks) {
353                 dequeue_cleanup_callback();
354                 has_dequeue_callbacks = false;
355         }
356 }
357
358 void FFmpegCapture::send_disconnected_frame()
359 {
360         // Send an empty frame to signal that we have no signal anymore.
361         FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
362         if (video_frame.data) {
363                 VideoFormat video_format;
364                 video_format.width = width;
365                 video_format.height = height;
366                 video_format.frame_rate_nom = 60;
367                 video_format.frame_rate_den = 1;
368                 video_format.is_connected = false;
369                 if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
370                         video_format.stride = width * 4;
371                         video_frame.len = width * height * 4;
372                         memset(video_frame.data, 0, video_frame.len);
373                 } else {
374                         video_format.stride = width;
375                         current_frame_ycbcr_format.luma_coefficients = YCBCR_REC_709;
376                         current_frame_ycbcr_format.full_range = true;
377                         current_frame_ycbcr_format.num_levels = 256;
378                         current_frame_ycbcr_format.chroma_subsampling_x = 2;
379                         current_frame_ycbcr_format.chroma_subsampling_y = 2;
380                         current_frame_ycbcr_format.cb_x_position = 0.0f;
381                         current_frame_ycbcr_format.cb_y_position = 0.0f;
382                         current_frame_ycbcr_format.cr_x_position = 0.0f;
383                         current_frame_ycbcr_format.cr_y_position = 0.0f;
384                         video_frame.len = width * height * 2;
385                         memset(video_frame.data, 0, width * height);
386                         memset(video_frame.data + width * height, 128, width * height);  // Valid for both NV12 and planar.
387                 }
388
389                 frame_callback(-1, AVRational{1, TIMEBASE}, -1, AVRational{1, TIMEBASE}, timecode++,
390                         video_frame, /*video_offset=*/0, video_format,
391                         FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
392                 last_frame_was_connected = false;
393         }
394 }
395
396 bool FFmpegCapture::play_video(const string &pathname)
397 {
398         // Note: Call before open, not after; otherwise, there's a race.
399         // (There is now, too, but it tips the correct way. We could use fstat()
400         // if we had the file descriptor.)
401         timespec last_modified;
402         struct stat buf;
403         if (stat(pathname.c_str(), &buf) != 0) {
404                 // Probably some sort of protocol, so can't stat.
405                 last_modified.tv_sec = -1;
406         } else {
407                 last_modified = buf.st_mtim;
408         }
409
410         auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr, AVIOInterruptCB{ &FFmpegCapture::interrupt_cb_thunk, this });
411         if (format_ctx == nullptr) {
412                 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
413                 return false;
414         }
415
416         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
417                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
418                 return false;
419         }
420
421         int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
422         if (video_stream_index == -1) {
423                 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
424                 return false;
425         }
426
427         int audio_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_AUDIO);
428         int subtitle_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_SUBTITLE);
429         has_last_subtitle = false;
430
431         // Open video decoder.
432         const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
433         AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
434         video_timebase = format_ctx->streams[video_stream_index]->time_base;
435         AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
436         if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
437                 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
438                 return false;
439         }
440         if (video_codec == nullptr) {
441                 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
442                 return false;
443         }
444         if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
445                 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
446                 return false;
447         }
448         unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
449                 video_codec_ctx.get(), avcodec_close);
450
451         // Used in decode_ycbcr_format().
452         is_mjpeg = video_codecpar->codec_id == AV_CODEC_ID_MJPEG;
453
454         // Open audio decoder, if we have audio.
455         AVCodecContextWithDeleter audio_codec_ctx;
456         if (audio_stream_index != -1) {
457                 audio_codec_ctx = avcodec_alloc_context3_unique(nullptr);
458                 const AVCodecParameters *audio_codecpar = format_ctx->streams[audio_stream_index]->codecpar;
459                 audio_timebase = format_ctx->streams[audio_stream_index]->time_base;
460                 if (avcodec_parameters_to_context(audio_codec_ctx.get(), audio_codecpar) < 0) {
461                         fprintf(stderr, "%s: Cannot fill audio codec parameters\n", pathname.c_str());
462                         return false;
463                 }
464                 AVCodec *audio_codec = avcodec_find_decoder(audio_codecpar->codec_id);
465                 if (audio_codec == nullptr) {
466                         fprintf(stderr, "%s: Cannot find audio decoder\n", pathname.c_str());
467                         return false;
468                 }
469                 if (avcodec_open2(audio_codec_ctx.get(), audio_codec, nullptr) < 0) {
470                         fprintf(stderr, "%s: Cannot open audio decoder\n", pathname.c_str());
471                         return false;
472                 }
473         }
474         unique_ptr<AVCodecContext, decltype(avcodec_close)*> audio_codec_ctx_cleanup(
475                 audio_codec_ctx.get(), avcodec_close);
476
477         internal_rewind();
478
479         // Main loop.
480         bool first_frame = true;
481         while (!producer_thread_should_quit.should_quit()) {
482                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
483                         return true;
484                 }
485                 if (should_interrupt.load()) {
486                         // Check as a failsafe, so that we don't need to rely on avio if we don't have to.
487                         return false;
488                 }
489                 UniqueFrame audio_frame = audio_frame_allocator->alloc_frame();
490                 AudioFormat audio_format;
491
492                 int64_t audio_pts;
493                 bool error;
494                 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(), audio_codec_ctx.get(),
495                         pathname, video_stream_index, audio_stream_index, subtitle_stream_index, audio_frame.get(), &audio_format, &audio_pts, &error);
496                 if (error) {
497                         return false;
498                 }
499                 if (frame == nullptr) {
500                         // EOF. Loop back to the start if we can.
501                         if (format_ctx->pb != nullptr && format_ctx->pb->seekable == 0) {
502                                 // Not seekable (but seemingly, sometimes av_seek_frame() would return 0 anyway,
503                                 // so don't try).
504                                 return true;
505                         }
506                         if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
507                                 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
508                                 return true;
509                         }
510                         if (video_codec_ctx != nullptr) {
511                                 avcodec_flush_buffers(video_codec_ctx.get());
512                         }
513                         if (audio_codec_ctx != nullptr) {
514                                 avcodec_flush_buffers(audio_codec_ctx.get());
515                         }
516                         // If the file has changed since last time, return to get it reloaded.
517                         // Note that depending on how you move the file into place, you might
518                         // end up corrupting the one you're already playing, so this path
519                         // might not trigger.
520                         if (changed_since(pathname, last_modified)) {
521                                 return true;
522                         }
523                         internal_rewind();
524                         continue;
525                 }
526
527                 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
528                 UniqueFrame video_frame = make_video_frame(frame.get(), pathname, &error);
529                 if (error) {
530                         return false;
531                 }
532
533                 for ( ;; ) {
534                         if (last_pts == 0 && pts_origin == 0) {
535                                 pts_origin = frame->pts;        
536                         }
537                         steady_clock::time_point now = steady_clock::now();
538                         if (play_as_fast_as_possible) {
539                                 video_frame->received_timestamp = now;
540                                 audio_frame->received_timestamp = now;
541                                 next_frame_start = now;
542                         } else {
543                                 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
544                                 if (first_frame && last_frame_was_connected) {
545                                         // If reconnect took more than one second, this is probably a live feed,
546                                         // and we should reset the resampler. (Or the rate is really, really low,
547                                         // in which case a reset on the first frame is fine anyway.)
548                                         if (duration<double>(next_frame_start - last_frame).count() >= 1.0) {
549                                                 last_frame_was_connected = false;
550                                         }
551                                 }
552                                 video_frame->received_timestamp = next_frame_start;
553
554                                 // The easiest way to get all the rate conversions etc. right is to move the
555                                 // audio PTS into the video PTS timebase and go from there. (We'll get some
556                                 // rounding issues, but they should not be a big problem.)
557                                 int64_t audio_pts_as_video_pts = av_rescale_q(audio_pts, audio_timebase, video_timebase);
558                                 audio_frame->received_timestamp = compute_frame_start(audio_pts_as_video_pts, pts_origin, video_timebase, start, rate);
559
560                                 if (audio_frame->len != 0) {
561                                         // The received timestamps in Nageru are measured after we've just received the frame.
562                                         // However, pts (especially audio pts) is at the _beginning_ of the frame.
563                                         // If we have locked audio, the distinction doesn't really matter, as pts is
564                                         // on a relative scale and a fixed offset is fine. But if we don't, we will have
565                                         // a different number of samples each time, which will cause huge audio jitter
566                                         // and throw off the resampler.
567                                         //
568                                         // In a sense, we should have compensated by adding the frame and audio lengths
569                                         // to video_frame->received_timestamp and audio_frame->received_timestamp respectively,
570                                         // but that would mean extra waiting in sleep_until(). All we need is that they
571                                         // are correct relative to each other, though (and to the other frames we send),
572                                         // so just align the end of the audio frame, and we're fine.
573                                         size_t num_samples = (audio_frame->len * 8) / audio_format.bits_per_sample / audio_format.num_channels;
574                                         double offset = double(num_samples) / OUTPUT_FREQUENCY -
575                                                 double(video_format.frame_rate_den) / video_format.frame_rate_nom;
576                                         audio_frame->received_timestamp += duration_cast<steady_clock::duration>(duration<double>(offset));
577                                 }
578
579                                 if (duration<double>(now - next_frame_start).count() >= 0.1) {
580                                         // If we don't have enough CPU to keep up, or if we have a live stream
581                                         // where the initial origin was somehow wrong, we could be behind indefinitely.
582                                         // In particular, this will give the audio resampler problems as it tries
583                                         // to speed up to reduce the delay, hitting the low end of the buffer every time.
584                                         fprintf(stderr, "%s: Playback %.0f ms behind, resetting time scale\n",
585                                                 pathname.c_str(),
586                                                 1e3 * duration<double>(now - next_frame_start).count());
587                                         pts_origin = frame->pts;
588                                         start = next_frame_start = now;
589                                         timecode += MAX_FPS * 2 + 1;
590                                 }
591                         }
592                         bool finished_wakeup;
593                         if (play_as_fast_as_possible) {
594                                 finished_wakeup = !producer_thread_should_quit.should_quit();
595                         } else {
596                                 finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
597                         }
598                         if (finished_wakeup) {
599                                 if (audio_frame->len > 0) {
600                                         assert(audio_pts != -1);
601                                 }
602                                 if (!last_frame_was_connected) {
603                                         // We're recovering from an error (or really slow load, see above).
604                                         // Make sure to get the audio resampler reset. (This is a hack;
605                                         // ideally, the frame callback should just accept a way to signal
606                                         // audio discontinuity.)
607                                         timecode += MAX_FPS * 2 + 1;
608                                 }
609                                 last_neutral_color = get_neutral_color(frame->metadata);
610                                 frame_callback(frame->pts, video_timebase, audio_pts, audio_timebase, timecode++,
611                                         video_frame.get_and_release(), 0, video_format,
612                                         audio_frame.get_and_release(), 0, audio_format);
613                                 first_frame = false;
614                                 last_frame = steady_clock::now();
615                                 last_frame_was_connected = true;
616                                 break;
617                         } else {
618                                 if (producer_thread_should_quit.should_quit()) break;
619
620                                 bool rewound = false;
621                                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
622                                         return true;
623                                 }
624                                 // If we just rewound, drop this frame on the floor and be done.
625                                 if (rewound) {
626                                         break;
627                                 }
628                                 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
629                                 // but if it's now in the past, we'll reset the origin, so that we don't
630                                 // generate a huge backlog of frames that we need to run through quickly.
631                                 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
632                                 steady_clock::time_point now = steady_clock::now();
633                                 if (next_frame_start < now) {
634                                         pts_origin = frame->pts;
635                                         start = next_frame_start = now;
636                                 }
637                         }
638                 }
639                 last_pts = frame->pts;
640         }
641         return true;
642 }
643
644 void FFmpegCapture::internal_rewind()
645 {                               
646         pts_origin = last_pts = 0;
647         start = next_frame_start = steady_clock::now();
648 }
649
650 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
651 {
652         // Process any queued commands from other threads.
653         vector<QueuedCommand> commands;
654         {
655                 lock_guard<mutex> lock(queue_mu);
656                 swap(commands, command_queue);
657         }
658         for (const QueuedCommand &cmd : commands) {
659                 switch (cmd.command) {
660                 case QueuedCommand::REWIND:
661                         if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
662                                 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
663                         }
664                         // If the file has changed since last time, return to get it reloaded.
665                         // Note that depending on how you move the file into place, you might
666                         // end up corrupting the one you're already playing, so this path
667                         // might not trigger.
668                         if (changed_since(pathname, last_modified)) {
669                                 return true;
670                         }
671                         internal_rewind();
672                         if (rewound != nullptr) {
673                                 *rewound = true;
674                         }
675                         break;
676
677                 case QueuedCommand::CHANGE_RATE:
678                         // Change the origin to the last played frame.
679                         start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
680                         pts_origin = last_pts;
681                         rate = cmd.new_rate;
682                         play_as_fast_as_possible = (rate >= 10.0);
683                         break;
684                 }
685         }
686         return false;
687 }
688
689 namespace {
690
691 }  // namespace
692
693 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, AVCodecContext *audio_codec_ctx,
694         const std::string &pathname, int video_stream_index, int audio_stream_index, int subtitle_stream_index,
695         FrameAllocator::Frame *audio_frame, AudioFormat *audio_format, int64_t *audio_pts, bool *error)
696 {
697         *error = false;
698
699         // Read packets until we have a frame or there are none left.
700         bool frame_finished = false;
701         AVFrameWithDeleter audio_avframe = av_frame_alloc_unique();
702         AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
703         bool eof = false;
704         *audio_pts = -1;
705         bool has_audio = false;
706         do {
707                 AVPacket pkt;
708                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
709                         &pkt, av_packet_unref);
710                 av_init_packet(&pkt);
711                 pkt.data = nullptr;
712                 pkt.size = 0;
713                 if (av_read_frame(format_ctx, &pkt) == 0) {
714                         if (pkt.stream_index == audio_stream_index && audio_callback != nullptr) {
715                                 audio_callback(&pkt, format_ctx->streams[audio_stream_index]->time_base);
716                         }
717                         if (pkt.stream_index == video_stream_index) {
718                                 if (avcodec_send_packet(video_codec_ctx, &pkt) < 0) {
719                                         fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
720                                         *error = true;
721                                         return AVFrameWithDeleter(nullptr);
722                                 }
723                         } else if (pkt.stream_index == audio_stream_index) {
724                                 has_audio = true;
725                                 if (avcodec_send_packet(audio_codec_ctx, &pkt) < 0) {
726                                         fprintf(stderr, "%s: Cannot send packet to audio codec.\n", pathname.c_str());
727                                         *error = true;
728                                         return AVFrameWithDeleter(nullptr);
729                                 }
730                         } else if (pkt.stream_index == subtitle_stream_index) {
731                                 last_subtitle = string(reinterpret_cast<const char *>(pkt.data), pkt.size);
732                                 has_last_subtitle = true;
733                         }
734                 } else {
735                         eof = true;  // Or error, but ignore that for the time being.
736                 }
737
738                 // Decode audio, if any.
739                 if (has_audio) {
740                         for ( ;; ) {
741                                 int err = avcodec_receive_frame(audio_codec_ctx, audio_avframe.get());
742                                 if (err == 0) {
743                                         if (*audio_pts == -1) {
744                                                 *audio_pts = audio_avframe->pts;
745                                         }
746                                         convert_audio(audio_avframe.get(), audio_frame, audio_format);
747                                 } else if (err == AVERROR(EAGAIN)) {
748                                         break;
749                                 } else {
750                                         fprintf(stderr, "%s: Cannot receive frame from audio codec.\n", pathname.c_str());
751                                         *error = true;
752                                         return AVFrameWithDeleter(nullptr);
753                                 }
754                         }
755                 }
756
757                 // Decode video, if we have a frame.
758                 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
759                 if (err == 0) {
760                         frame_finished = true;
761                         break;
762                 } else if (err != AVERROR(EAGAIN)) {
763                         fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
764                         *error = true;
765                         return AVFrameWithDeleter(nullptr);
766                 }
767         } while (!eof);
768
769         if (frame_finished)
770                 return video_avframe;
771         else
772                 return AVFrameWithDeleter(nullptr);
773 }
774
775 void FFmpegCapture::convert_audio(const AVFrame *audio_avframe, FrameAllocator::Frame *audio_frame, AudioFormat *audio_format)
776 {
777         // Decide on a format. If there already is one in this audio frame,
778         // we're pretty much forced to use it. If not, we try to find an exact match.
779         // If that still doesn't work, we default to 32-bit signed chunked
780         // (float would be nice, but there's really no way to signal that yet).
781         AVSampleFormat dst_format;
782         if (audio_format->bits_per_sample == 0) {
783                 switch (audio_avframe->format) {
784                 case AV_SAMPLE_FMT_S16:
785                 case AV_SAMPLE_FMT_S16P:
786                         audio_format->bits_per_sample = 16;
787                         dst_format = AV_SAMPLE_FMT_S16;
788                         break;
789                 case AV_SAMPLE_FMT_S32:
790                 case AV_SAMPLE_FMT_S32P:
791                 default:
792                         audio_format->bits_per_sample = 32;
793                         dst_format = AV_SAMPLE_FMT_S32;
794                         break;
795                 }
796         } else if (audio_format->bits_per_sample == 16) {
797                 dst_format = AV_SAMPLE_FMT_S16;
798         } else if (audio_format->bits_per_sample == 32) {
799                 dst_format = AV_SAMPLE_FMT_S32;
800         } else {
801                 assert(false);
802         }
803         audio_format->num_channels = 2;
804
805         int64_t channel_layout = audio_avframe->channel_layout;
806         if (channel_layout == 0) {
807                 channel_layout = av_get_default_channel_layout(audio_avframe->channels);
808         }
809
810         if (resampler == nullptr ||
811             audio_avframe->format != last_src_format ||
812             dst_format != last_dst_format ||
813             channel_layout != last_channel_layout ||
814             audio_avframe->sample_rate != last_sample_rate) {
815                 swr_free(&resampler);
816                 resampler = swr_alloc_set_opts(nullptr,
817                                                /*out_ch_layout=*/AV_CH_LAYOUT_STEREO_DOWNMIX,
818                                                /*out_sample_fmt=*/dst_format,
819                                                /*out_sample_rate=*/OUTPUT_FREQUENCY,
820                                                /*in_ch_layout=*/channel_layout,
821                                                /*in_sample_fmt=*/AVSampleFormat(audio_avframe->format),
822                                                /*in_sample_rate=*/audio_avframe->sample_rate,
823                                                /*log_offset=*/0,
824                                                /*log_ctx=*/nullptr);
825
826                 if (resampler == nullptr) {
827                         fprintf(stderr, "Allocating resampler failed.\n");
828                         abort();
829                 }
830
831                 if (swr_init(resampler) < 0) {
832                         fprintf(stderr, "Could not open resample context.\n");
833                         abort();
834                 }
835
836                 last_src_format = AVSampleFormat(audio_avframe->format);
837                 last_dst_format = dst_format;
838                 last_channel_layout = channel_layout;
839                 last_sample_rate = audio_avframe->sample_rate;
840         }
841
842         size_t bytes_per_sample = (audio_format->bits_per_sample / 8) * 2;
843         size_t num_samples_room = (audio_frame->size - audio_frame->len) / bytes_per_sample;
844
845         uint8_t *data = audio_frame->data + audio_frame->len;
846         int out_samples = swr_convert(resampler, &data, num_samples_room,
847                 const_cast<const uint8_t **>(audio_avframe->data), audio_avframe->nb_samples);
848         if (out_samples < 0) {
849                 fprintf(stderr, "Audio conversion failed.\n");
850                 abort();
851         }
852
853         audio_frame->len += out_samples * bytes_per_sample;
854 }
855
856 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
857 {
858         VideoFormat video_format;
859         video_format.width = width;
860         video_format.height = height;
861         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
862                 video_format.stride = width * 4;
863         } else if (pixel_format == FFmpegCapture::PixelFormat_NV12) {
864                 video_format.stride = width;
865         } else {
866                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
867                 video_format.stride = width;
868         }
869         video_format.frame_rate_nom = video_timebase.den;
870         video_format.frame_rate_den = frame->pkt_duration * video_timebase.num;
871         if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
872                 // Invalid frame rate.
873                 video_format.frame_rate_nom = 60;
874                 video_format.frame_rate_den = 1;
875         }
876         video_format.has_signal = true;
877         video_format.is_connected = true;
878         return video_format;
879 }
880
881 UniqueFrame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
882 {
883         *error = false;
884
885         UniqueFrame video_frame(video_frame_allocator->alloc_frame());
886         if (video_frame->data == nullptr) {
887                 return video_frame;
888         }
889
890         if (sws_ctx == nullptr ||
891             sws_last_width != frame->width ||
892             sws_last_height != frame->height ||
893             sws_last_src_format != frame->format) {
894                 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
895                 sws_ctx.reset(
896                         sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
897                                 width, height, sws_dst_format,
898                                 SWS_BICUBIC, nullptr, nullptr, nullptr));
899                 sws_last_width = frame->width;
900                 sws_last_height = frame->height;
901                 sws_last_src_format = frame->format;
902         }
903         if (sws_ctx == nullptr) {
904                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
905                 *error = true;
906                 return video_frame;
907         }
908
909         uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
910         int linesizes[4] = { 0, 0, 0, 0 };
911         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
912                 pic_data[0] = video_frame->data;
913                 linesizes[0] = width * 4;
914                 video_frame->len = (width * 4) * height;
915         } else if (pixel_format == PixelFormat_NV12) {
916                 pic_data[0] = video_frame->data;
917                 linesizes[0] = width;
918
919                 pic_data[1] = pic_data[0] + width * height;
920                 linesizes[1] = width;
921
922                 video_frame->len = (width * 2) * height;
923
924                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
925                 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame, is_mjpeg);
926         } else {
927                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
928                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
929
930                 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
931                 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
932
933                 pic_data[0] = video_frame->data;
934                 linesizes[0] = width;
935
936                 pic_data[1] = pic_data[0] + width * height;
937                 linesizes[1] = chroma_width;
938
939                 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
940                 linesizes[2] = chroma_width;
941
942                 video_frame->len = width * height + 2 * chroma_width * chroma_height;
943
944                 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame, is_mjpeg);
945         }
946         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
947
948         return video_frame;
949 }
950
951 int FFmpegCapture::interrupt_cb_thunk(void *unique)
952 {
953         return reinterpret_cast<FFmpegCapture *>(unique)->interrupt_cb();
954 }
955
956 int FFmpegCapture::interrupt_cb()
957 {
958         return should_interrupt.load();
959 }