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