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