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