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