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