]> git.sesse.net Git - nageru/blob - ffmpeg_capture.cpp
Update the queue length metric after trimming, not before.
[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 <libswscale/swscale.h>
22 }
23
24 #include <chrono>
25 #include <cstdint>
26 #include <utility>
27 #include <vector>
28
29 #include "bmusb/bmusb.h"
30 #include "ffmpeg_raii.h"
31 #include "ffmpeg_util.h"
32 #include "flags.h"
33 #include "image_input.h"
34
35 #define FRAME_SIZE (8 << 20)  // 8 MB.
36
37 using namespace std;
38 using namespace std::chrono;
39 using namespace bmusb;
40 using namespace movit;
41
42 namespace {
43
44 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)
45 {
46         const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
47         return origin + duration_cast<steady_clock::duration>(pts / rate);
48 }
49
50 bool changed_since(const std::string &pathname, const timespec &ts)
51 {
52         if (ts.tv_sec < 0) {
53                 return false;
54         }
55         struct stat buf;
56         if (stat(pathname.c_str(), &buf) != 0) {
57                 fprintf(stderr, "%s: Couldn't check for new version, leaving the old in place.\n", pathname.c_str());
58                 return false;
59         }
60         return (buf.st_mtim.tv_sec != ts.tv_sec || buf.st_mtim.tv_nsec != ts.tv_nsec);
61 }
62
63 bool is_full_range(const AVPixFmtDescriptor *desc)
64 {
65         // This is horrible, but there's no better way that I know of.
66         return (strchr(desc->name, 'j') != nullptr);
67 }
68
69 AVPixelFormat decide_dst_format(AVPixelFormat src_format, bmusb::PixelFormat dst_format_type)
70 {
71         if (dst_format_type == bmusb::PixelFormat_8BitBGRA) {
72                 return AV_PIX_FMT_BGRA;
73         }
74
75         assert(dst_format_type == bmusb::PixelFormat_8BitYCbCrPlanar);
76
77         // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
78         // and be done with it. It's too strange to spend a lot of time on.
79         // (Let's hope there's no alpha.)
80         const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
81         if (src_desc == nullptr ||
82             src_desc->nb_components != 3 ||
83             (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
84                 return AV_PIX_FMT_YUV444P;
85         }
86
87         // The best for us would be Cb and Cr together if possible,
88         // but FFmpeg doesn't support that except in the special case of
89         // NV12, so we need to go to planar even for the case of NV12.
90         // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
91         // that matches in color range. (This will also include the case of
92         // the source format already being acceptable.)
93         bool src_full_range = is_full_range(src_desc);
94         const char *best_format = "yuv444p";
95         unsigned best_score = numeric_limits<unsigned>::max();
96         for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
97              desc;
98              desc = av_pix_fmt_desc_next(desc)) {
99                 // Find planar Y'CbCr formats only.
100                 if (desc->nb_components != 3) continue;
101                 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
102                 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
103                 if (desc->comp[0].plane != 0 ||
104                     desc->comp[1].plane != 1 ||
105                     desc->comp[2].plane != 2) continue;
106
107                 // 8-bit formats only.
108                 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
109                 if (desc->comp[0].depth != 8) continue;
110
111                 // Same or better chroma resolution only.
112                 int chroma_w_diff = desc->log2_chroma_w - src_desc->log2_chroma_w;
113                 int chroma_h_diff = desc->log2_chroma_h - src_desc->log2_chroma_h;
114                 if (chroma_w_diff < 0 || chroma_h_diff < 0)
115                         continue;
116
117                 // Matching full/limited range only.
118                 if (is_full_range(desc) != src_full_range)
119                         continue;
120
121                 // Pick something with as little excess chroma resolution as possible.
122                 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
123                 if (score < best_score) {
124                         best_score = score;
125                         best_format = desc->name;
126                 }
127         }
128         return av_get_pix_fmt(best_format);
129 }
130
131 YCbCrFormat decode_ycbcr_format(const AVPixFmtDescriptor *desc, const AVFrame *frame)
132 {
133         YCbCrFormat format;
134         AVColorSpace colorspace = av_frame_get_colorspace(frame);
135         switch (colorspace) {
136         case AVCOL_SPC_BT709:
137                 format.luma_coefficients = YCBCR_REC_709;
138                 break;
139         case AVCOL_SPC_BT470BG:
140         case AVCOL_SPC_SMPTE170M:
141         case AVCOL_SPC_SMPTE240M:
142                 format.luma_coefficients = YCBCR_REC_601;
143                 break;
144         case AVCOL_SPC_BT2020_NCL:
145                 format.luma_coefficients = YCBCR_REC_2020;
146                 break;
147         case AVCOL_SPC_UNSPECIFIED:
148                 format.luma_coefficients = (frame->height >= 720 ? YCBCR_REC_709 : YCBCR_REC_601);
149                 break;
150         default:
151                 fprintf(stderr, "Unknown Y'CbCr coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
152                         colorspace);
153                 format.luma_coefficients = YCBCR_REC_709;
154                 break;
155         }
156
157         format.full_range = is_full_range(desc);
158         format.num_levels = 1 << desc->comp[0].depth;
159         format.chroma_subsampling_x = 1 << desc->log2_chroma_w;
160         format.chroma_subsampling_y = 1 << desc->log2_chroma_h;
161
162         switch (frame->chroma_location) {
163         case AVCHROMA_LOC_LEFT:
164                 format.cb_x_position = 0.0;
165                 format.cb_y_position = 0.5;
166                 break;
167         case AVCHROMA_LOC_CENTER:
168                 format.cb_x_position = 0.5;
169                 format.cb_y_position = 0.5;
170                 break;
171         case AVCHROMA_LOC_TOPLEFT:
172                 format.cb_x_position = 0.0;
173                 format.cb_y_position = 0.0;
174                 break;
175         case AVCHROMA_LOC_TOP:
176                 format.cb_x_position = 0.5;
177                 format.cb_y_position = 0.0;
178                 break;
179         case AVCHROMA_LOC_BOTTOMLEFT:
180                 format.cb_x_position = 0.0;
181                 format.cb_y_position = 1.0;
182                 break;
183         case AVCHROMA_LOC_BOTTOM:
184                 format.cb_x_position = 0.5;
185                 format.cb_y_position = 1.0;
186                 break;
187         default:
188                 fprintf(stderr, "Unknown chroma location coefficient enum %d from FFmpeg; choosing Rec. 709.\n",
189                         frame->chroma_location);
190                 format.cb_x_position = 0.5;
191                 format.cb_y_position = 0.5;
192                 break;
193         }
194
195         format.cr_x_position = format.cb_x_position;
196         format.cr_y_position = format.cb_y_position;
197         return format;
198 }
199
200 }  // namespace
201
202 FFmpegCapture::FFmpegCapture(const string &filename, unsigned width, unsigned height)
203         : filename(filename), width(width), height(height), video_timebase{1, 1}
204 {
205         // Not really used for anything.
206         description = "Video: " + filename;
207
208         avformat_network_init();  // In case someone wants this.
209 }
210
211 FFmpegCapture::~FFmpegCapture()
212 {
213         if (has_dequeue_callbacks) {
214                 dequeue_cleanup_callback();
215         }
216 }
217
218 void FFmpegCapture::configure_card()
219 {
220         if (video_frame_allocator == nullptr) {
221                 owned_video_frame_allocator.reset(new MallocFrameAllocator(FRAME_SIZE, NUM_QUEUED_VIDEO_FRAMES));
222                 set_video_frame_allocator(owned_video_frame_allocator.get());
223         }
224         if (audio_frame_allocator == nullptr) {
225                 owned_audio_frame_allocator.reset(new MallocFrameAllocator(65536, NUM_QUEUED_AUDIO_FRAMES));
226                 set_audio_frame_allocator(owned_audio_frame_allocator.get());
227         }
228 }
229
230 void FFmpegCapture::start_bm_capture()
231 {
232         if (running) {
233                 return;
234         }
235         running = true;
236         producer_thread_should_quit.unquit();
237         producer_thread = thread(&FFmpegCapture::producer_thread_func, this);
238 }
239
240 void FFmpegCapture::stop_dequeue_thread()
241 {
242         if (!running) {
243                 return;
244         }
245         running = false;
246         producer_thread_should_quit.quit();
247         producer_thread.join();
248 }
249
250 std::map<uint32_t, VideoMode> FFmpegCapture::get_available_video_modes() const
251 {
252         // Note: This will never really be shown in the UI.
253         VideoMode mode;
254
255         char buf[256];
256         snprintf(buf, sizeof(buf), "%ux%u", width, height);
257         mode.name = buf;
258         
259         mode.autodetect = false;
260         mode.width = width;
261         mode.height = height;
262         mode.frame_rate_num = 60;
263         mode.frame_rate_den = 1;
264         mode.interlaced = false;
265
266         return {{ 0, mode }};
267 }
268
269 void FFmpegCapture::producer_thread_func()
270 {
271         char thread_name[16];
272         snprintf(thread_name, sizeof(thread_name), "FFmpeg_C_%d", card_index);
273         pthread_setname_np(pthread_self(), thread_name);
274
275         while (!producer_thread_should_quit.should_quit()) {
276                 string pathname = search_for_file(filename);
277                 if (filename.empty()) {
278                         fprintf(stderr, "%s not found, sleeping one second and trying again...\n", filename.c_str());
279                         send_disconnected_frame();
280                         producer_thread_should_quit.sleep_for(seconds(1));
281                         continue;
282                 }
283                 if (!play_video(pathname)) {
284                         // Error.
285                         fprintf(stderr, "Error when playing %s, sleeping one second and trying again...\n", pathname.c_str());
286                         send_disconnected_frame();
287                         producer_thread_should_quit.sleep_for(seconds(1));
288                         continue;
289                 }
290
291                 // Probably just EOF, will exit the loop above on next test.
292         }
293
294         if (has_dequeue_callbacks) {
295                 dequeue_cleanup_callback();
296                 has_dequeue_callbacks = false;
297         }
298 }
299
300 void FFmpegCapture::send_disconnected_frame()
301 {
302         // Send an empty frame to signal that we have no signal anymore.
303         FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
304         if (video_frame.data) {
305                 VideoFormat video_format;
306                 video_format.width = width;
307                 video_format.height = height;
308                 video_format.stride = width * 4;
309                 video_format.frame_rate_nom = 60;
310                 video_format.frame_rate_den = 1;
311                 video_format.is_connected = false;
312
313                 video_frame.len = width * height * 4;
314                 memset(video_frame.data, 0, video_frame.len);
315
316                 frame_callback(timecode++,
317                         video_frame, /*video_offset=*/0, video_format,
318                         FrameAllocator::Frame(), /*audio_offset=*/0, AudioFormat());
319         }
320 }
321
322 bool FFmpegCapture::play_video(const string &pathname)
323 {
324         // Note: Call before open, not after; otherwise, there's a race.
325         // (There is now, too, but it tips the correct way. We could use fstat()
326         // if we had the file descriptor.)
327         timespec last_modified;
328         struct stat buf;
329         if (stat(pathname.c_str(), &buf) != 0) {
330                 // Probably some sort of protocol, so can't stat.
331                 last_modified.tv_sec = -1;
332         } else {
333                 last_modified = buf.st_mtim;
334         }
335
336         auto format_ctx = avformat_open_input_unique(pathname.c_str(), nullptr, nullptr);
337         if (format_ctx == nullptr) {
338                 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
339                 return false;
340         }
341
342         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
343                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
344                 return false;
345         }
346
347         int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
348         if (video_stream_index == -1) {
349                 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
350                 return false;
351         }
352
353         const AVCodecParameters *codecpar = format_ctx->streams[video_stream_index]->codecpar;
354         video_timebase = format_ctx->streams[video_stream_index]->time_base;
355         AVCodecContextWithDeleter codec_ctx = avcodec_alloc_context3_unique(nullptr);
356         if (avcodec_parameters_to_context(codec_ctx.get(), codecpar) < 0) {
357                 fprintf(stderr, "%s: Cannot fill codec parameters\n", pathname.c_str());
358                 return false;
359         }
360         AVCodec *codec = avcodec_find_decoder(codecpar->codec_id);
361         if (codec == nullptr) {
362                 fprintf(stderr, "%s: Cannot find decoder\n", pathname.c_str());
363                 return false;
364         }
365         if (avcodec_open2(codec_ctx.get(), codec, nullptr) < 0) {
366                 fprintf(stderr, "%s: Cannot open decoder\n", pathname.c_str());
367                 return false;
368         }
369         unique_ptr<AVCodecContext, decltype(avcodec_close)*> codec_ctx_cleanup(
370                 codec_ctx.get(), avcodec_close);
371
372         internal_rewind();
373
374         // Main loop.
375         while (!producer_thread_should_quit.should_quit()) {
376                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, /*rewound=*/nullptr)) {
377                         return true;
378                 }
379
380                 bool error;
381                 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), codec_ctx.get(), pathname, video_stream_index, &error);
382                 if (error) {
383                         return false;
384                 }
385                 if (frame == nullptr) {
386                         // EOF. Loop back to the start if we can.
387                         if (av_seek_frame(format_ctx.get(), /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
388                                 fprintf(stderr, "%s: Rewind failed, not looping.\n", pathname.c_str());
389                                 return true;
390                         }
391                         // If the file has changed since last time, return to get it reloaded.
392                         // Note that depending on how you move the file into place, you might
393                         // end up corrupting the one you're already playing, so this path
394                         // might not trigger.
395                         if (changed_since(pathname, last_modified)) {
396                                 return true;
397                         }
398                         internal_rewind();
399                         continue;
400                 }
401
402                 VideoFormat video_format = construct_video_format(frame.get(), video_timebase);
403                 FrameAllocator::Frame video_frame = make_video_frame(frame.get(), pathname, &error);
404                 if (error) {
405                         return false;
406                 }
407
408                 FrameAllocator::Frame audio_frame;
409                 AudioFormat audio_format;
410                 audio_format.bits_per_sample = 32;
411                 audio_format.num_channels = 8;
412
413                 for ( ;; ) {
414                         next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
415                         video_frame.received_timestamp = next_frame_start;
416                         bool finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
417                         if (finished_wakeup) {
418                                 frame_callback(timecode++,
419                                         video_frame, 0, video_format,
420                                         audio_frame, 0, audio_format);
421                                 break;
422                         } else {
423                                 if (producer_thread_should_quit.should_quit()) break;
424
425                                 bool rewound = false;
426                                 if (process_queued_commands(format_ctx.get(), pathname, last_modified, &rewound)) {
427                                         return true;
428                                 }
429                                 // If we just rewound, drop this frame on the floor and be done.
430                                 if (rewound) {
431                                         video_frame_allocator->release_frame(video_frame);
432                                         break;
433                                 }
434                                 // OK, we didn't, so probably a rate change. Recalculate next_frame_start,
435                                 // but if it's now in the past, we'll reset the origin, so that we don't
436                                 // generate a huge backlog of frames that we need to run through quickly.
437                                 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
438                                 steady_clock::time_point now = steady_clock::now();
439                                 if (next_frame_start < now) {
440                                         pts_origin = frame->pts;
441                                         start = next_frame_start = now;
442                                 }
443                         }
444                 }
445                 last_pts = frame->pts;
446         }
447         return true;
448 }
449
450 void FFmpegCapture::internal_rewind()
451 {                               
452         pts_origin = last_pts = 0;
453         start = next_frame_start = steady_clock::now();
454 }
455
456 bool FFmpegCapture::process_queued_commands(AVFormatContext *format_ctx, const std::string &pathname, timespec last_modified, bool *rewound)
457 {
458         // Process any queued commands from other threads.
459         vector<QueuedCommand> commands;
460         {
461                 lock_guard<mutex> lock(queue_mu);
462                 swap(commands, command_queue);
463         }
464         for (const QueuedCommand &cmd : commands) {
465                 switch (cmd.command) {
466                 case QueuedCommand::REWIND:
467                         if (av_seek_frame(format_ctx, /*stream_index=*/-1, /*timestamp=*/0, /*flags=*/0) < 0) {
468                                 fprintf(stderr, "%s: Rewind failed, stopping play.\n", pathname.c_str());
469                         }
470                         // If the file has changed since last time, return to get it reloaded.
471                         // Note that depending on how you move the file into place, you might
472                         // end up corrupting the one you're already playing, so this path
473                         // might not trigger.
474                         if (changed_since(pathname, last_modified)) {
475                                 return true;
476                         }
477                         internal_rewind();
478                         if (rewound != nullptr) {
479                                 *rewound = true;
480                         }
481                         break;
482
483                 case QueuedCommand::CHANGE_RATE:
484                         // Change the origin to the last played frame.
485                         start = compute_frame_start(last_pts, pts_origin, video_timebase, start, rate);
486                         pts_origin = last_pts;
487                         rate = cmd.new_rate;
488                         break;
489                 }
490         }
491         return false;
492 }
493
494 AVFrameWithDeleter FFmpegCapture::decode_frame(AVFormatContext *format_ctx, AVCodecContext *codec_ctx, const std::string &pathname, int video_stream_index, bool *error)
495 {
496         *error = false;
497
498         // Read packets until we have a frame or there are none left.
499         bool frame_finished = false;
500         AVFrameWithDeleter frame = av_frame_alloc_unique();
501         bool eof = false;
502         do {
503                 AVPacket pkt;
504                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
505                         &pkt, av_packet_unref);
506                 av_init_packet(&pkt);
507                 pkt.data = nullptr;
508                 pkt.size = 0;
509                 if (av_read_frame(format_ctx, &pkt) == 0) {
510                         if (pkt.stream_index != video_stream_index) {
511                                 // Ignore audio for now.
512                                 continue;
513                         }
514                         if (avcodec_send_packet(codec_ctx, &pkt) < 0) {
515                                 fprintf(stderr, "%s: Cannot send packet to codec.\n", pathname.c_str());
516                                 *error = true;
517                                 return AVFrameWithDeleter(nullptr);
518                         }
519                 } else {
520                         eof = true;  // Or error, but ignore that for the time being.
521                 }
522
523                 int err = avcodec_receive_frame(codec_ctx, frame.get());
524                 if (err == 0) {
525                         frame_finished = true;
526                         break;
527                 } else if (err != AVERROR(EAGAIN)) {
528                         fprintf(stderr, "%s: Cannot receive frame from codec.\n", pathname.c_str());
529                         *error = true;
530                         return AVFrameWithDeleter(nullptr);
531                 }
532         } while (!eof);
533
534         if (frame_finished)
535                 return frame;
536         else
537                 return AVFrameWithDeleter(nullptr);
538 }
539
540 VideoFormat FFmpegCapture::construct_video_format(const AVFrame *frame, AVRational video_timebase)
541 {
542         VideoFormat video_format;
543         video_format.width = width;
544         video_format.height = height;
545         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
546                 video_format.stride = width * 4;
547         } else {
548                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
549                 video_format.stride = width;
550         }
551         video_format.frame_rate_nom = video_timebase.den;
552         video_format.frame_rate_den = av_frame_get_pkt_duration(frame) * video_timebase.num;
553         if (video_format.frame_rate_nom == 0 || video_format.frame_rate_den == 0) {
554                 // Invalid frame rate.
555                 video_format.frame_rate_nom = 60;
556                 video_format.frame_rate_den = 1;
557         }
558         video_format.has_signal = true;
559         video_format.is_connected = true;
560         return video_format;
561 }
562
563 FrameAllocator::Frame FFmpegCapture::make_video_frame(const AVFrame *frame, const string &pathname, bool *error)
564 {
565         *error = false;
566
567         FrameAllocator::Frame video_frame = video_frame_allocator->alloc_frame();
568         if (video_frame.data == nullptr) {
569                 return video_frame;
570         }
571
572         if (sws_ctx == nullptr ||
573             sws_last_width != frame->width ||
574             sws_last_height != frame->height ||
575             sws_last_src_format != frame->format) {
576                 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format), pixel_format);
577                 sws_ctx.reset(
578                         sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
579                                 width, height, sws_dst_format,
580                                 SWS_BICUBIC, nullptr, nullptr, nullptr));
581                 sws_last_width = frame->width;
582                 sws_last_height = frame->height;
583                 sws_last_src_format = frame->format;
584         }
585         if (sws_ctx == nullptr) {
586                 fprintf(stderr, "%s: Could not create scaler context\n", pathname.c_str());
587                 *error = true;
588                 return video_frame;
589         }
590
591         uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
592         int linesizes[4] = { 0, 0, 0, 0 };
593         if (pixel_format == bmusb::PixelFormat_8BitBGRA) {
594                 pic_data[0] = video_frame.data;
595                 linesizes[0] = width * 4;
596                 video_frame.len = (width * 4) * height;
597         } else {
598                 assert(pixel_format == bmusb::PixelFormat_8BitYCbCrPlanar);
599                 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
600
601                 int chroma_width = AV_CEIL_RSHIFT(int(width), desc->log2_chroma_w);
602                 int chroma_height = AV_CEIL_RSHIFT(int(height), desc->log2_chroma_h);
603
604                 pic_data[0] = video_frame.data;
605                 linesizes[0] = width;
606
607                 pic_data[1] = pic_data[0] + width * height;
608                 linesizes[1] = chroma_width;
609
610                 pic_data[2] = pic_data[1] + chroma_width * chroma_height;
611                 linesizes[2] = chroma_width;
612
613                 video_frame.len = width * height + 2 * chroma_width * chroma_height;
614
615                 current_frame_ycbcr_format = decode_ycbcr_format(desc, frame);
616         }
617         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
618
619         return video_frame;
620 }