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