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