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