1 #define GL_GLEXT_PROTOTYPES
3 #include "video_widget.h"
15 #include <libavcodec/avcodec.h>
16 #include <libavformat/avformat.h>
17 #include <libavutil/avutil.h>
18 #include <libavutil/error.h>
19 #include <libavutil/frame.h>
20 #include <libavutil/imgutils.h>
21 #include <libavutil/mem.h>
22 #include <libavutil/pixfmt.h>
23 #include <libavutil/opt.h>
24 #include <libswscale/swscale.h>
31 #include <unordered_set>
33 #include "post_to_main_thread.h"
35 #include <QOpenGLFunctions>
36 #include <QWheelEvent>
37 #include <QMouseEvent>
39 #define BUFFER_OFFSET(i) ((char *)nullptr + (i))
42 using namespace std::chrono;
46 bool is_full_range(const AVPixFmtDescriptor *desc)
48 // This is horrible, but there's no better way that I know of.
49 return (strchr(desc->name, 'j') != nullptr);
52 AVPixelFormat decide_dst_format(AVPixelFormat src_format)
54 // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
55 // and be done with it. It's too strange to spend a lot of time on.
56 // (Let's hope there's no alpha.)
57 const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
58 if (src_desc == nullptr ||
59 src_desc->nb_components != 3 ||
60 (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
61 return AV_PIX_FMT_YUV444P;
64 // The best for us would be Cb and Cr together if possible,
65 // but FFmpeg doesn't support that except in the special case of
66 // NV12, so we need to go to planar even for the case of NV12.
67 // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
68 // that matches in color range. (This will also include the case of
69 // the source format already being acceptable.)
70 bool src_full_range = is_full_range(src_desc);
71 const char *best_format = "yuv444p";
72 unsigned best_score = numeric_limits<unsigned>::max();
73 for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
75 desc = av_pix_fmt_desc_next(desc)) {
76 // Find planar Y'CbCr formats only.
77 if (desc->nb_components != 3) continue;
78 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
79 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
80 if (desc->comp[0].plane != 0 ||
81 desc->comp[1].plane != 1 ||
82 desc->comp[2].plane != 2) continue;
84 // 8-bit formats only.
85 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
86 if (desc->comp[0].depth != 8) continue;
88 // Same or better chroma resolution only.
89 int chroma_w_diff = src_desc->log2_chroma_w - desc->log2_chroma_w;
90 int chroma_h_diff = src_desc->log2_chroma_h - desc->log2_chroma_h;
91 if (chroma_w_diff < 0 || chroma_h_diff < 0)
94 // Matching full/limited range only.
95 if (is_full_range(desc) != src_full_range)
98 // Pick something with as little excess chroma resolution as possible.
99 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
100 if (score < best_score) {
102 best_format = desc->name;
105 return av_get_pix_fmt(best_format);
110 bool VideoWidget::process_queued_commands(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, int video_stream_index, bool *seeked)
112 // Process any queued commands from other threads.
113 vector<QueuedCommand> commands;
115 lock_guard<mutex> lock(queue_mu);
116 swap(commands, command_queue);
119 for (const QueuedCommand &cmd : commands) {
120 switch (cmd.command) {
121 case QueuedCommand::PAUSE:
124 case QueuedCommand::RESUME:
126 pts_origin = last_pts;
127 start = next_frame_start = steady_clock::now();
129 case QueuedCommand::SEEK:
130 case QueuedCommand::SEEK_ABSOLUTE:
136 // Combine all seeks into one big one. (There are edge cases where this is probably
137 // subtly wrong, but we'll live with it.)
138 int64_t base_pts = last_pts;
139 int64_t relative_seek_ms = 0;
140 int64_t relative_seek_frames = 0;
141 for (const QueuedCommand &cmd : commands) {
142 if (cmd.command == QueuedCommand::SEEK) {
143 relative_seek_ms += cmd.relative_seek_ms;
144 relative_seek_frames += cmd.relative_seek_frames;
145 } else if (cmd.command == QueuedCommand::SEEK_ABSOLUTE) {
146 base_pts = av_rescale_q(cmd.seek_ms, AVRational{ 1, 1000 }, video_timebase);
147 relative_seek_ms = 0;
148 relative_seek_frames = 0;
151 int64_t relative_seek_pts = av_rescale_q(relative_seek_ms, AVRational{ 1, 1000 }, video_timebase);
152 if (relative_seek_ms != 0 && relative_seek_pts == 0) {
153 // Just to be sure rounding errors don't move us into nothingness.
154 relative_seek_pts = (relative_seek_ms > 0) ? 1 : -1;
156 int64_t goal_pts = base_pts + relative_seek_pts;
157 if (goal_pts != last_pts || relative_seek_frames < 0) {
158 avcodec_flush_buffers(video_codec_ctx);
159 queued_frames.clear();
161 // Seek to the last keyframe before this point.
162 int64_t seek_pts = goal_pts;
163 if (relative_seek_frames < 0) {
164 // If we're frame-skipping backwards, add 100 ms of slop for each frame
165 // so we're fairly certain we are able to see the ones we want.
166 seek_pts -= av_rescale_q(-relative_seek_frames, AVRational{ 1, 10 }, video_timebase);
168 av_seek_frame(format_ctx, video_stream_index, seek_pts, AVSEEK_FLAG_BACKWARD);
170 // Decode frames until EOF, or until we see something past our seek point.
171 std::deque<AVFrameWithDeleter> queue;
174 AVFrameWithDeleter frame = decode_frame(format_ctx, video_codec_ctx,
175 pathname, video_stream_index, &error);
176 if (frame == nullptr || error) {
180 int64_t frame_pts = frame->pts;
181 if (relative_seek_frames < 0) {
182 // Buffer this frame; don't display it unless we know it's the Nth-latest.
183 queue.push_back(std::move(frame));
184 if (queue.size() > uint64_t(-relative_seek_frames) + 1) {
188 if (frame_pts >= goal_pts) {
189 if (relative_seek_frames > 0) {
190 --relative_seek_frames;
192 if (relative_seek_frames < 0) {
193 // Hope we have the right amount.
194 // The rest will remain in the queue for when we play forward again.
195 frame = std::move(queue.front());
197 queued_frames = std::move(queue);
199 shared_ptr<Frame> new_frame = make_video_frame(frame.get());
201 lock_guard lock(current_frame_mu);
202 current_frame = std::move(new_frame);
205 store_pts(frame->pts);
211 // NOTE: We keep pause status as-is.
213 pts_origin = last_pts;
214 start = next_frame_start = last_frame = steady_clock::now();
218 } else if (relative_seek_frames > 0) {
219 // The base PTS is fine, we only need to skip a few frames forwards.
220 while (relative_seek_frames > 1) {
221 // Eat a frame (ignore errors).
223 decode_frame(format_ctx, video_codec_ctx, pathname, video_stream_index, &error);
224 --relative_seek_frames;
227 // Display the last one.
229 AVFrameWithDeleter frame = decode_frame(format_ctx, video_codec_ctx,
230 pathname, video_stream_index, &error);
231 if (frame == nullptr || error) {
234 shared_ptr<Frame> new_frame = make_video_frame(frame.get());
236 lock_guard lock(current_frame_mu);
237 current_frame = std::move(new_frame);
240 store_pts(frame->pts);
245 VideoWidget::VideoWidget(QWidget *parent)
246 : QOpenGLWidget(parent) {}
248 GLuint compile_shader(const string &shader_src, GLenum type)
250 GLuint obj = glCreateShader(type);
251 const GLchar* source[] = { shader_src.data() };
252 const GLint length[] = { (GLint)shader_src.size() };
253 glShaderSource(obj, 1, source, length);
254 glCompileShader(obj);
256 GLchar info_log[4096];
257 GLsizei log_length = sizeof(info_log) - 1;
258 glGetShaderInfoLog(obj, log_length, &log_length, info_log);
259 info_log[log_length] = 0;
260 if (strlen(info_log) > 0) {
261 fprintf(stderr, "Shader compile log: %s\n", info_log);
265 glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
266 if (status == GL_FALSE) {
267 // Add some line numbers to easier identify compile errors.
268 string src_with_lines = "/* 1 */ ";
270 for (char ch : shader_src) {
271 src_with_lines.push_back(ch);
274 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
275 src_with_lines += buf;
279 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
286 void VideoWidget::initializeGL()
289 glDisable(GL_DEPTH_TEST);
290 glDepthMask(GL_FALSE);
291 glCreateTextures(GL_TEXTURE_2D, 3, tex);
293 ycbcr_vertex_shader = compile_shader(R"(
296 layout(location = 0) in vec2 position;
297 layout(location = 1) in vec2 texcoord;
302 // The result of glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0) is:
304 // 2.000 0.000 0.000 -1.000
305 // 0.000 2.000 0.000 -1.000
306 // 0.000 0.000 -2.000 -1.000
307 // 0.000 0.000 0.000 1.000
308 gl_Position = vec4(2.0 * position.x - 1.0, 2.0 * position.y - 1.0, -1.0, 1.0);
312 )", GL_VERTEX_SHADER);
313 ycbcr_fragment_shader = compile_shader(R"(
316 layout(location = 0) uniform sampler2D tex_y;
317 layout(location = 1) uniform sampler2D tex_cb;
318 layout(location = 2) uniform sampler2D tex_cr;
319 layout(location = 3) uniform vec2 cbcr_offset;
324 // Computed statically by Movit, for limited-range BT.709.
325 // (We don't check whether the input could be BT.601 or BT.2020 currently, or full-range)
326 const mat3 inv_ycbcr_matrix = mat3(
327 1.16438f, 1.16438f, 1.16438f,
328 0.0f, -0.21325f, 2.11240f,
329 1.79274f, -0.53291f, 0.0f
334 if (tc.x < 0.0 || tc.x > 1.0 || tc.y < 0.0 || tc.y > 1.0) {
335 FragColor.rgba = vec4(0.0f, 0.0f, 0.0f, 1.0f);
340 ycbcr.r = texture(tex_y, tc).r;
341 ycbcr.g = texture(tex_cb, tc + cbcr_offset).r;
342 ycbcr.b = texture(tex_cr, tc + cbcr_offset).r;
343 ycbcr -= vec3(16.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f);
344 FragColor.rgb = inv_ycbcr_matrix * ycbcr;
347 )", GL_FRAGMENT_SHADER);
348 ycbcr_program = glCreateProgram();
349 glAttachShader(ycbcr_program, ycbcr_vertex_shader);
350 glAttachShader(ycbcr_program, ycbcr_fragment_shader);
351 glLinkProgram(ycbcr_program);
354 glGetProgramiv(ycbcr_program, GL_LINK_STATUS, &success);
355 if (success == GL_FALSE) {
356 GLchar error_log[1024] = {0};
357 glGetProgramInfoLog(ycbcr_program, 1024, nullptr, error_log);
358 fprintf(stderr, "Error linking program: %s\n", error_log);
362 glCreateSamplers(1, &bilinear_sampler);
363 glSamplerParameteri(bilinear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
364 glSamplerParameteri(bilinear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
365 glSamplerParameteri(bilinear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
366 glSamplerParameteri(bilinear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
369 void VideoWidget::resizeGL(int w, int h)
371 glViewport(0, 0, w, h);
372 display_aspect = double(w) / h;
375 int num_levels(GLuint width, GLuint height)
378 while (width > 1 || height > 1) {
379 width = max(width / 2, 1u);
380 height = max(height / 2, 1u);
386 void VideoWidget::paintGL()
388 std::shared_ptr<Frame> frame;
390 lock_guard lock(current_frame_mu);
391 frame = current_frame;
393 if (frame == nullptr) {
394 glClear(GL_COLOR_BUFFER_BIT);
398 glUseProgram(ycbcr_program);
399 if (frame->width != last_width || frame->height != last_height) {
400 glTextureStorage2D(tex[0], num_levels(frame->width, frame->height), GL_R8, frame->width, frame->height);
402 if (frame->chroma_width != last_chroma_width || frame->chroma_height != last_chroma_height) {
403 for (GLuint num : { tex[1], tex[2] }) {
404 glTextureStorage2D(num, num_levels(frame->chroma_width, frame->chroma_height), GL_R8, frame->chroma_width, frame->chroma_height);
408 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, frame->pbo);
410 if (frame->need_flush_len > 0) {
411 glFlushMappedNamedBufferRange(frame->pbo, 0, frame->need_flush_len);
412 frame->need_flush_len = 0;
415 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
416 glTextureSubImage2D(tex[0], 0, 0, 0, frame->width, frame->height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
417 glGenerateTextureMipmap(tex[0]);
419 glTextureSubImage2D(tex[1], 0, 0, 0, frame->chroma_width, frame->chroma_height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(frame->width * frame->height));
420 glGenerateTextureMipmap(tex[1]);
422 glTextureSubImage2D(tex[2], 0, 0, 0, frame->chroma_width, frame->chroma_height, GL_RED, GL_UNSIGNED_BYTE, BUFFER_OFFSET(frame->width * frame->height + frame->chroma_width * frame->chroma_height));
423 glGenerateTextureMipmap(tex[2]);
425 glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
427 glBindTextureUnit(0, tex[0]);
428 glBindTextureUnit(1, tex[1]);
429 glBindTextureUnit(2, tex[2]);
430 glBindSampler(0, bilinear_sampler);
431 glBindSampler(1, bilinear_sampler);
432 glBindSampler(2, bilinear_sampler);
433 glProgramUniform1i(ycbcr_program, 0, 0);
434 glProgramUniform1i(ycbcr_program, 1, 1);
435 glProgramUniform1i(ycbcr_program, 2, 2);
436 glProgramUniform2f(ycbcr_program, 3, cbcr_offset[0], -cbcr_offset[1]);
443 double video_aspect = double(frame->width) / frame->height;
444 if (display_aspect > video_aspect) {
445 double extra_width = frame->height * display_aspect - frame->width;
446 tx1 = -0.5 * extra_width / frame->width;
447 tx2 = 1.0 + 0.5 * extra_width / frame->width;
448 } else if (display_aspect < video_aspect) {
449 double extra_height = frame->width / display_aspect - frame->height;
450 ty1 = -0.5 * extra_height / frame->height;
451 ty2 = 1.0 + 0.5 * extra_height / frame->height;
457 glVertexAttrib2f(1, tx1, ty1);
458 glVertex2f(zoom_matrix[2 * 3 + 0], zoom_matrix[2 * 3 + 1]);
461 glVertexAttrib2f(1, tx1, ty2);
462 glVertex2f(zoom_matrix[1 * 3 + 0] + zoom_matrix[2 * 3 + 0], zoom_matrix[1 * 3 + 1] + zoom_matrix[2 * 3 + 1]);
465 glVertexAttrib2f(1, tx2, ty2);
466 glVertex2f(zoom_matrix[0 * 3 + 0] + zoom_matrix[1 * 3 + 0] + zoom_matrix[2 * 3 + 0],
467 zoom_matrix[1 * 3 + 0] + zoom_matrix[1 * 3 + 1] + zoom_matrix[2 * 3 + 1]);
470 glVertexAttrib2f(1, tx2, ty1);
471 glVertex2f(zoom_matrix[0 * 3 + 0] + zoom_matrix[2 * 3 + 0],
472 zoom_matrix[1 * 3 + 0] + zoom_matrix[2 * 3 + 1]);
477 void matmul3x3(const double a[9], const double b[9], double res[9])
479 for (int i = 0; i < 3; ++i) {
480 for (int j = 0; j < 3; ++j) {
482 for (int k = 0; k < 3; ++k) {
483 sum += a[i * 3 + k] * b[k * 3 + j];
485 res[i * 3 + j] = sum;
490 void VideoWidget::wheelEvent(QWheelEvent *event)
492 int delta = event->angleDelta().y();
496 double x = event->position().x() / width();
497 double y = 1.0 - event->position().y() / height();
498 double zoom = delta > 0 ? pow(1.005, delta) : pow(1/1.005, -delta);
500 const double inv_translation_matrix[9] = {
505 const double scale_matrix[9] = {
510 const double translation_matrix[9] = {
515 double tmp1[9], tmp2[9];
516 matmul3x3(zoom_matrix, inv_translation_matrix, tmp1);
517 matmul3x3(tmp1, scale_matrix, tmp2);
518 matmul3x3(tmp2, translation_matrix, zoom_matrix);
524 void VideoWidget::mousePressEvent(QMouseEvent *e)
526 if (e->button() == Qt::BackButton) {
527 emit mouse_back_clicked();
528 } else if (e->button() == Qt::ForwardButton) {
529 emit mouse_forward_clicked();
530 } else if (e->button() == Qt::LeftButton) {
532 last_drag_x = e->position().x();
533 last_drag_y = e->position().y();
537 void VideoWidget::mouseReleaseEvent(QMouseEvent *e)
539 if (e->button() == Qt::LeftButton) {
544 void VideoWidget::mouseMoveEvent(QMouseEvent *e)
549 float dx = (e->position().x() - last_drag_x) / width();
550 float dy = (e->position().y() - last_drag_y) / height();
552 //zoom_matrix[6] += dx * zoom_matrix[0];
553 //zoom_matrix[7] += dy * zoom_matrix[4];
554 zoom_matrix[6] += dx;
555 zoom_matrix[7] -= dy;
558 last_drag_x = e->position().x();
559 last_drag_y = e->position().y();
564 // Normalize the matrix so that we never get skew or similar,
565 // and also never can zoom or pan too far out.
566 void VideoWidget::fixup_zoom_matrix()
568 // Correct for any numerical errors (we know the matrix must be orthogonal
569 // and have zero rotation).
570 zoom_matrix[4] = zoom_matrix[0];
571 zoom_matrix[1] = zoom_matrix[2] = zoom_matrix[3] = zoom_matrix[5] = 0.0;
572 zoom_matrix[8] = 1.0;
574 // We can't zoom further out than 1:1. (Perhaps it would be nice to
575 // reuse the last zoom-in point to do this, but the center will have to do
577 if (zoom_matrix[0] < 1.0) {
578 const double zoom = 1.0 / zoom_matrix[0];
579 const double inv_translation_matrix[9] = {
584 const double scale_matrix[9] = {
589 const double translation_matrix[9] = {
594 double tmp1[9], tmp2[9];
595 matmul3x3(zoom_matrix, inv_translation_matrix, tmp1);
596 matmul3x3(tmp1, scale_matrix, tmp2);
597 matmul3x3(tmp2, translation_matrix, zoom_matrix);
600 // Looking at the points we'll draw with glVertex2f(), make sure none of them are
601 // inside the square (which would generally mean we've panned ourselves out-of-bounds).
602 // We simply adjust the translation, which is possible because we fixed scaling above.
603 zoom_matrix[6] = min(zoom_matrix[6], 0.0); // Left side (x=0).
604 zoom_matrix[7] = min(zoom_matrix[7], 0.0); // Bottom side (y=0).
605 zoom_matrix[6] = std::max(zoom_matrix[6], 1.0 - zoom_matrix[0]); // Right side (x=1).
606 zoom_matrix[7] = std::max(zoom_matrix[7], 1.0 - zoom_matrix[4]); // Top side (y=1).
609 bool VideoWidget::open(const string &filename)
616 while (running == STARTING) {
617 // Poor man's condition variable...
621 return (running != VIDEO_FILE_ERROR);
624 void VideoWidget::play()
626 if (running != NOT_RUNNING && running != VIDEO_FILE_ERROR) {
627 std::lock_guard<std::mutex> lock(queue_mu);
628 command_queue.push_back(QueuedCommand { QueuedCommand::RESUME });
629 producer_thread_should_quit.wakeup();
633 producer_thread_should_quit.unquit();
634 if (producer_thread.joinable()) {
635 producer_thread.join();
637 producer_thread = std::thread(&VideoWidget::producer_thread_func, this);
640 void VideoWidget::pause()
642 if (running == NOT_RUNNING || running == VIDEO_FILE_ERROR) {
645 std::lock_guard<std::mutex> lock(queue_mu);
646 command_queue.push_back(QueuedCommand { QueuedCommand::PAUSE });
647 producer_thread_should_quit.wakeup();
650 void VideoWidget::seek(int64_t relative_seek_ms)
652 if (running == NOT_RUNNING || running == VIDEO_FILE_ERROR) {
655 std::lock_guard<std::mutex> lock(queue_mu);
656 command_queue.push_back(QueuedCommand { QueuedCommand::SEEK, relative_seek_ms, 0, 0 });
657 producer_thread_should_quit.wakeup();
660 void VideoWidget::seek_frames(int64_t relative_seek_frames)
662 if (running == NOT_RUNNING || running == VIDEO_FILE_ERROR) {
665 std::lock_guard<std::mutex> lock(queue_mu);
666 command_queue.push_back(QueuedCommand { QueuedCommand::SEEK, 0, relative_seek_frames, 0 });
667 producer_thread_should_quit.wakeup();
670 void VideoWidget::seek_absolute(int64_t position_ms)
672 if (running == NOT_RUNNING || running == VIDEO_FILE_ERROR) {
675 std::lock_guard<std::mutex> lock(queue_mu);
676 command_queue.push_back(QueuedCommand { QueuedCommand::SEEK_ABSOLUTE, 0, 0, position_ms });
677 producer_thread_should_quit.wakeup();
680 void VideoWidget::stop()
682 if (running == NOT_RUNNING || running == VIDEO_FILE_ERROR) {
685 producer_thread_should_quit.quit();
686 producer_thread.join();
689 void VideoWidget::producer_thread_func()
691 if (!producer_thread_should_quit.should_quit()) {
692 if (!play_video(pathname)) {
693 running = VIDEO_FILE_ERROR;
695 running = NOT_RUNNING;
700 void VideoWidget::internal_rewind()
702 pts_origin = last_pts = 0;
704 start = next_frame_start = steady_clock::now();
707 template<AVHWDeviceType type>
708 AVPixelFormat get_hw_format(AVCodecContext *ctx, const AVPixelFormat *fmt)
710 bool found_config_of_right_type = false;
711 for (int i = 0;; ++i) { // Termination condition inside loop.
712 const AVCodecHWConfig *config = avcodec_get_hw_config(ctx->codec, i);
713 if (config == nullptr) { // End of list.
716 if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) ||
717 config->device_type != type) {
718 // Not interesting for us.
722 // We have a config of the right type, but does it actually support
723 // the pixel format we want? (Seemingly, FFmpeg's way of signaling errors
724 // is to just replace the pixel format with a software-decoded one,
726 found_config_of_right_type = true;
727 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
728 if (config->pix_fmt == *fmt_ptr) {
729 fprintf(stderr, "Initialized '%s' hardware decoding for codec '%s'.\n",
730 av_hwdevice_get_type_name(type), ctx->codec->name);
731 if (ctx->profile == FF_PROFILE_H264_BASELINE) {
732 fprintf(stderr, "WARNING: Stream claims to be H.264 Baseline, which is generally poorly supported in hardware decoders.\n");
733 fprintf(stderr, " Consider encoding it as Constrained Baseline, Main or High instead.\n");
734 fprintf(stderr, " Decoding might fail and fall back to software.\n");
736 return config->pix_fmt;
739 fprintf(stderr, "Decoder '%s' supports only these pixel formats:", ctx->codec->name);
740 unordered_set<AVPixelFormat> seen;
741 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
742 if (!seen.count(*fmt_ptr)) {
743 fprintf(stderr, " %s", av_get_pix_fmt_name(*fmt_ptr));
744 seen.insert(*fmt_ptr);
747 fprintf(stderr, " (wanted %s for hardware acceleration)\n", av_get_pix_fmt_name(config->pix_fmt));
751 if (!found_config_of_right_type) {
752 fprintf(stderr, "Decoder '%s' does not support device type '%s'.\n", ctx->codec->name, av_hwdevice_get_type_name(type));
755 // We found no VA-API formats, so take the first software format.
756 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
757 if ((av_pix_fmt_desc_get(*fmt_ptr)->flags & AV_PIX_FMT_FLAG_HWACCEL) == 0) {
758 fprintf(stderr, "Falling back to software format %s.\n", av_get_pix_fmt_name(*fmt_ptr));
763 // Fallback: Just return anything. (Should never really happen.)
767 AVFrameWithDeleter VideoWidget::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx,
768 const std::string &pathname, int video_stream_index,
773 if (!queued_frames.empty()) {
774 AVFrameWithDeleter frame = std::move(queued_frames.front());
775 queued_frames.pop_front();
779 // Read packets until we have a frame or there are none left.
780 bool frame_finished = false;
781 AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
784 AVPacket *pkt = av_packet_alloc();
785 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
786 pkt, av_packet_unref);
789 if (av_read_frame(format_ctx, pkt) == 0) {
790 if (pkt->stream_index == video_stream_index) {
791 if (avcodec_send_packet(video_codec_ctx, pkt) < 0) {
792 fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
794 return AVFrameWithDeleter(nullptr);
798 eof = true; // Or error, but ignore that for the time being.
801 // Decode video, if we have a frame.
802 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
804 frame_finished = true;
806 } else if (err != AVERROR(EAGAIN)) {
807 fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
809 return AVFrameWithDeleter(nullptr);
814 return video_avframe;
816 return AVFrameWithDeleter(nullptr);
819 int find_stream_index(AVFormatContext *ctx, AVMediaType media_type)
821 for (unsigned i = 0; i < ctx->nb_streams; ++i) {
822 if (ctx->streams[i]->codecpar->codec_type == media_type) {
829 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)
831 const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
832 return origin + duration_cast<steady_clock::duration>(pts / rate);
835 bool VideoWidget::play_video(const string &pathname)
837 queued_frames.clear();
838 AVFormatContextWithCloser format_ctx = avformat_open_input_unique(pathname.c_str(), /*fmt=*/nullptr,
839 /*options=*/nullptr);
840 if (format_ctx == nullptr) {
841 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
845 if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
846 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
850 int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
851 if (video_stream_index == -1) {
852 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
856 // Open video decoder.
857 const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
858 const AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
860 video_timebase = format_ctx->streams[video_stream_index]->time_base;
861 AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
862 if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
863 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
866 if (video_codec == nullptr) {
867 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
871 // Seemingly, it's not too easy to make something that just initializes
872 // “whatever goes”, so we don't get CUDA or VULKAN or whatever here
873 // without enumerating through several different types.
874 // VA-API and VDPAU will do for now. We prioritize VDPAU for the
875 // simple reason that there's a VA-API-via-VDPAU emulation for NVidia
876 // cards that seems to work, but just hangs when trying to transfer the frame.
878 // Note that we don't actually check codec support beforehand,
879 // so if you have a low-end VDPAU device but a high-end VA-API device,
880 // you lose out on the extra codec support from the latter.
881 AVBufferRef *hw_device_ctx = nullptr;
882 if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VDPAU, nullptr, nullptr, 0) >= 0) {
883 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
884 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VDPAU>;
885 } else if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, nullptr, nullptr, 0) >= 0) {
886 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
887 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VAAPI>;
889 fprintf(stderr, "Failed to initialize VA-API or VDPAU for FFmpeg acceleration. Decoding video in software.\n");
892 if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
893 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
896 unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
897 video_codec_ctx.get(), avcodec_close);
904 int consecutive_errors = 0;
906 while (!producer_thread_should_quit.should_quit()) {
907 if (process_queued_commands(format_ctx.get(), video_codec_ctx.get(), video_stream_index, /*seeked=*/nullptr)) {
911 producer_thread_should_quit.sleep_for(hours(1));
916 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(),
917 pathname, video_stream_index, &error);
919 if (++consecutive_errors >= 100) {
920 fprintf(stderr, "More than 100 consecutive video frames, aborting playback.\n");
926 consecutive_errors = 0;
928 if (frame == nullptr) {
933 // Sleep until it's time to present this frame.
935 if (last_pts == 0 && pts_origin == 0) {
936 pts_origin = frame->pts;
938 steady_clock::time_point now = steady_clock::now();
939 next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
941 if (duration<double>(now - next_frame_start).count() >= 0.1) {
942 // If we don't have enough CPU to keep up, or if we have a live stream
943 // where the initial origin was somehow wrong, we could be behind indefinitely.
944 fprintf(stderr, "%s: Playback %.0f ms behind, resetting time scale\n",
946 1e3 * duration<double>(now - next_frame_start).count());
947 pts_origin = frame->pts;
948 start = next_frame_start = now;
950 bool finished_wakeup;
951 finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
952 if (finished_wakeup) {
953 shared_ptr<Frame> new_frame = make_video_frame(frame.get());
955 lock_guard lock(current_frame_mu);
956 current_frame = std::move(new_frame);
958 last_frame = steady_clock::now();
962 if (producer_thread_should_quit.should_quit()) break;
965 if (process_queued_commands(format_ctx.get(), video_codec_ctx.get(), video_stream_index, &seeked)) {
970 // Just paused, so present the frame immediately and then go into deep sleep.
971 shared_ptr<Frame> new_frame = make_video_frame(frame.get());
973 lock_guard lock(current_frame_mu);
974 current_frame = std::move(new_frame);
976 last_frame = steady_clock::now();
981 // If we just seeked, drop this frame on the floor and be done.
987 store_pts(frame->pts);
992 void VideoWidget::store_pts(int64_t pts)
995 last_position = lrint(pts * double(video_timebase.num) / double(video_timebase.den) * 1000);
996 post_to_main_thread([this, last_position{last_position.load()}] {
997 emit position_changed(last_position);
1001 // Taken from Movit (see the comment there for explanation)
1002 float compute_chroma_offset(float pos, unsigned subsampling_factor, unsigned resolution)
1004 float local_chroma_pos = (0.5 + pos * (subsampling_factor - 1)) / subsampling_factor;
1005 if (fabs(local_chroma_pos - 0.5) < 1e-10) {
1006 // x + (-0) can be optimized away freely, as opposed to x + 0.
1009 return (0.5 - local_chroma_pos) / resolution;
1013 shared_ptr<VideoWidget::Frame> VideoWidget::alloc_frame(unsigned width, unsigned height, unsigned chroma_width, unsigned chroma_height)
1015 lock_guard lock(freelist_mu);
1016 for (auto it = frame_freelist.begin(); it != frame_freelist.end(); ++it) {
1017 if ((*it)->width == width &&
1018 (*it)->height == height &&
1019 (*it)->chroma_width == chroma_width &&
1020 (*it)->chroma_height == chroma_height) {
1022 frame_freelist.erase(it);
1023 return shared_ptr<Frame>{frame, free_frame};
1027 Frame *frame = new Frame;
1028 frame->owner = this;
1029 frame->width = width;
1030 frame->height = height;
1031 frame->chroma_width = chroma_width;
1032 frame->chroma_height = chroma_height;
1034 size_t len = frame->width * frame->height + 2 * frame->chroma_width * frame->chroma_height;
1038 condition_variable done_cv;
1041 post_to_main_thread([this, &frame, len, &done, &mu, &done_cv]{
1043 glCreateBuffers(1, &frame->pbo);
1044 glNamedBufferStorage(frame->pbo, len, nullptr, GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT);
1045 frame->data = (uint8_t *)glMapNamedBufferRange(frame->pbo, 0, len, GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT | GL_MAP_PERSISTENT_BIT);
1048 lock_guard lock(mu);
1050 done_cv.notify_all();
1053 unique_lock lock(mu);
1054 done_cv.wait(lock, [&done]{ return done; });
1057 return shared_ptr<Frame>{frame, free_frame};
1060 void VideoWidget::free_frame(VideoWidget::Frame *frame)
1062 VideoWidget *self = frame->owner;
1063 lock_guard lock(self->freelist_mu);
1064 if (self->frame_freelist.size() >= 16) {
1065 GLuint pbo = frame->pbo;
1066 post_to_main_thread([self, pbo]{
1067 self->makeCurrent();
1068 glUnmapNamedBuffer(pbo);
1069 glDeleteBuffers(1, &pbo);
1070 self->doneCurrent();
1072 delete self->frame_freelist.front();
1073 self->frame_freelist.pop_front();
1075 self->frame_freelist.push_back(frame);
1078 shared_ptr<VideoWidget::Frame> VideoWidget::make_video_frame(const AVFrame *frame)
1080 AVFrameWithDeleter sw_frame;
1082 if (frame->format == AV_PIX_FMT_VAAPI ||
1083 frame->format == AV_PIX_FMT_VDPAU) {
1084 // Get the frame down to the CPU. (TODO: See if we can keep it
1085 // on the GPU all the way, since it will be going up again later.
1086 // However, this only works if the OpenGL GPU is the same one.)
1087 sw_frame = av_frame_alloc_unique();
1088 int err = av_hwframe_transfer_data(sw_frame.get(), frame, 0);
1090 fprintf(stderr, "%s: Cannot transfer hardware video frame to software.\n", pathname.c_str());
1092 sw_frame->pts = frame->pts;
1093 sw_frame->pkt_duration = frame->pkt_duration;
1094 frame = sw_frame.get();
1098 if (sws_ctx == nullptr ||
1099 sws_last_width != frame->width ||
1100 sws_last_height != frame->height ||
1101 sws_last_src_format != frame->format) {
1102 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format));
1104 sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
1105 frame->width, frame->height, sws_dst_format,
1106 SWS_BICUBIC, nullptr, nullptr, nullptr));
1107 sws_last_width = frame->width;
1108 sws_last_height = frame->height;
1109 sws_last_src_format = frame->format;
1111 if (sws_ctx == nullptr) {
1112 fprintf(stderr, "Could not create scaler context\n");
1116 uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
1117 int linesizes[4] = { 0, 0, 0, 0 };
1118 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
1120 shared_ptr<Frame> video_frame = alloc_frame(
1123 AV_CEIL_RSHIFT(int(frame->width), desc->log2_chroma_w),
1124 AV_CEIL_RSHIFT(int(frame->height), desc->log2_chroma_h));
1126 // We always assume left chroma placement for now.
1127 cbcr_offset[0] = compute_chroma_offset(0.0f, 1 << desc->log2_chroma_w, video_frame->chroma_width);
1128 cbcr_offset[1] = compute_chroma_offset(0.5f, 1 << desc->log2_chroma_h, video_frame->chroma_height);
1130 pic_data[0] = video_frame->data;
1131 linesizes[0] = frame->width;
1133 pic_data[1] = pic_data[0] + frame->width * frame->height;
1134 linesizes[1] = video_frame->chroma_width;
1136 pic_data[2] = pic_data[1] + video_frame->chroma_width * video_frame->chroma_height;
1137 linesizes[2] = video_frame->chroma_width;
1139 sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
1141 video_frame->need_flush_len = video_frame->width * video_frame->height + 2 * video_frame->chroma_width * video_frame->chroma_height;