]> git.sesse.net Git - pkanalytics/blob - video_widget.cpp
Fix a threading issue, where we would call into the Qt thread from the video thread.
[pkanalytics] / video_widget.cpp
1 #define GL_GLEXT_PROTOTYPES
2
3 #include "video_widget.h"
4
5 #include <assert.h>
6 #include <pthread.h>
7 #include <stdint.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/stat.h>
12 #include <unistd.h>
13
14 extern "C" {
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>
25 }
26
27 #include <chrono>
28 #include <cstdint>
29 #include <utility>
30 #include <vector>
31 #include <unordered_set>
32
33 #include "post_to_main_thread.h"
34
35 #include <QOpenGLFunctions>
36 #include <QWheelEvent>
37 #include <QMouseEvent>
38
39 using namespace std;
40 using namespace std::chrono;
41
42 namespace {
43
44 bool is_full_range(const AVPixFmtDescriptor *desc)
45 {
46         // This is horrible, but there's no better way that I know of.
47         return (strchr(desc->name, 'j') != nullptr);
48 }
49
50 AVPixelFormat decide_dst_format(AVPixelFormat src_format)
51 {
52         // If this is a non-Y'CbCr format, just convert to 4:4:4 Y'CbCr
53         // and be done with it. It's too strange to spend a lot of time on.
54         // (Let's hope there's no alpha.)
55         const AVPixFmtDescriptor *src_desc = av_pix_fmt_desc_get(src_format);
56         if (src_desc == nullptr ||
57             src_desc->nb_components != 3 ||
58             (src_desc->flags & AV_PIX_FMT_FLAG_RGB)) {
59                 return AV_PIX_FMT_YUV444P;
60         }
61
62         // The best for us would be Cb and Cr together if possible,
63         // but FFmpeg doesn't support that except in the special case of
64         // NV12, so we need to go to planar even for the case of NV12.
65         // Thus, look for the closest (but no worse) 8-bit planar Y'CbCr format
66         // that matches in color range. (This will also include the case of
67         // the source format already being acceptable.)
68         bool src_full_range = is_full_range(src_desc);
69         const char *best_format = "yuv444p";
70         unsigned best_score = numeric_limits<unsigned>::max();
71         for (const AVPixFmtDescriptor *desc = av_pix_fmt_desc_next(nullptr);
72              desc;
73              desc = av_pix_fmt_desc_next(desc)) {
74                 // Find planar Y'CbCr formats only.
75                 if (desc->nb_components != 3) continue;
76                 if (desc->flags & AV_PIX_FMT_FLAG_RGB) continue;
77                 if (!(desc->flags & AV_PIX_FMT_FLAG_PLANAR)) continue;
78                 if (desc->comp[0].plane != 0 ||
79                     desc->comp[1].plane != 1 ||
80                     desc->comp[2].plane != 2) continue;
81
82                 // 8-bit formats only.
83                 if (desc->flags & AV_PIX_FMT_FLAG_BE) continue;
84                 if (desc->comp[0].depth != 8) continue;
85
86                 // Same or better chroma resolution only.
87                 int chroma_w_diff = src_desc->log2_chroma_w - desc->log2_chroma_w;
88                 int chroma_h_diff = src_desc->log2_chroma_h - desc->log2_chroma_h;
89                 if (chroma_w_diff < 0 || chroma_h_diff < 0)
90                         continue;
91
92                 // Matching full/limited range only.
93                 if (is_full_range(desc) != src_full_range)
94                         continue;
95
96                 // Pick something with as little excess chroma resolution as possible.
97                 unsigned score = (1 << (chroma_w_diff)) << chroma_h_diff;
98                 if (score < best_score) {
99                         best_score = score;
100                         best_format = desc->name;
101                 }
102         }
103         return av_get_pix_fmt(best_format);
104 }
105
106 }  // namespace
107
108 bool VideoWidget::process_queued_commands(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx, int video_stream_index, bool *seeked)
109 {
110         // Process any queued commands from other threads.
111         vector<QueuedCommand> commands;
112         {
113                 lock_guard<mutex> lock(queue_mu);
114                 swap(commands, command_queue);
115         }
116
117         for (const QueuedCommand &cmd : commands) {
118                 switch (cmd.command) {
119                 case QueuedCommand::PAUSE:
120                         paused = true;
121                         break;
122                 case QueuedCommand::RESUME:
123                         paused = false;
124                         pts_origin = last_pts;
125                         start = next_frame_start = steady_clock::now();
126                         break;
127                 case QueuedCommand::SEEK:
128                 case QueuedCommand::SEEK_ABSOLUTE:
129                         // Dealt with below.
130                         break;
131                 }
132         }
133
134         // Combine all seeks into one big one. (There are edge cases where this is probably
135         // subtly wrong, but we'll live with it.)
136         int64_t base_pts = last_pts;
137         int64_t relative_seek_ms = 0;
138         int64_t relative_seek_frames = 0;
139         for (const QueuedCommand &cmd : commands) {
140                 if (cmd.command == QueuedCommand::SEEK) {
141                         relative_seek_ms += cmd.relative_seek_ms;
142                         relative_seek_frames += cmd.relative_seek_frames;
143                 } else if (cmd.command == QueuedCommand::SEEK_ABSOLUTE) {
144                         base_pts = av_rescale_q(cmd.seek_ms, AVRational{ 1, 1000 }, video_timebase);
145                         relative_seek_ms = 0;
146                         relative_seek_frames = 0;
147                 }
148         }
149         int64_t relative_seek_pts = av_rescale_q(relative_seek_ms, AVRational{ 1, 1000 }, video_timebase);
150         if (relative_seek_ms != 0 && relative_seek_pts == 0) {
151                 // Just to be sure rounding errors don't move us into nothingness.
152                 relative_seek_pts = (relative_seek_ms > 0) ? 1 : -1;
153         }
154         int64_t goal_pts = base_pts + relative_seek_pts;
155         if (goal_pts != last_pts || relative_seek_frames < 0) {
156                 avcodec_flush_buffers(video_codec_ctx);
157                 queued_frames.clear();
158
159                 // Seek to the last keyframe before this point.
160                 int64_t seek_pts = goal_pts;
161                 if (relative_seek_frames < 0) {
162                         // If we're frame-skipping backwards, add 100 ms of slop for each frame
163                         // so we're fairly certain we are able to see the ones we want.
164                         seek_pts -= av_rescale_q(-relative_seek_frames, AVRational{ 1, 10 }, video_timebase);
165                 }
166                 av_seek_frame(format_ctx, video_stream_index, seek_pts, AVSEEK_FLAG_BACKWARD);
167
168                 // Decode frames until EOF, or until we see something past our seek point.
169                 std::deque<AVFrameWithDeleter> queue;
170                 for ( ;; ) {
171                         bool error = false;
172                         AVFrameWithDeleter frame = decode_frame(format_ctx, video_codec_ctx,
173                                 pathname, video_stream_index, &error);
174                         if (frame == nullptr || error) {
175                                 break;
176                         }
177
178                         int64_t frame_pts = frame->pts;
179                         if (relative_seek_frames < 0) {
180                                 // Buffer this frame; don't display it unless we know it's the Nth-latest.
181                                 queue.push_back(std::move(frame));
182                                 if (queue.size() > uint64_t(-relative_seek_frames) + 1) {
183                                         queue.pop_front();
184                                 }
185                         }
186                         if (frame_pts >= goal_pts) {
187                                 if (relative_seek_frames > 0) {
188                                         --relative_seek_frames;
189                                 } else {
190                                         if (relative_seek_frames < 0) {
191                                                 // Hope we have the right amount.
192                                                 // The rest will remain in the queue for when we play forward again.
193                                                 frame = std::move(queue.front());
194                                                 queue.pop_front();
195                                                 queued_frames = std::move(queue);
196                                         }
197                                         current_frame.reset(new Frame(make_video_frame(frame.get())));
198                                         update();
199                                         store_pts(frame->pts);
200                                         break;
201                                 }
202                         }
203                 }
204
205                 // NOTE: We keep pause status as-is.
206
207                 pts_origin = last_pts;
208                 start = next_frame_start = last_frame = steady_clock::now();
209                 if (seeked) {
210                         *seeked = true;
211                 }
212         } else if (relative_seek_frames > 0) {
213                 // The base PTS is fine, we only need to skip a few frames forwards.
214                 while (relative_seek_frames > 1) {
215                         // Eat a frame (ignore errors).
216                         bool error;
217                         decode_frame(format_ctx, video_codec_ctx, pathname, video_stream_index, &error);
218                         --relative_seek_frames;
219                 }
220
221                 // Display the last one.
222                 bool error;
223                 AVFrameWithDeleter frame = decode_frame(format_ctx, video_codec_ctx,
224                         pathname, video_stream_index, &error);
225                 if (frame == nullptr || error) {
226                         return true;
227                 }
228                 current_frame.reset(new Frame(make_video_frame(frame.get())));
229                 update();
230                 store_pts(frame->pts);
231         }
232         return false;
233 }
234
235 VideoWidget::VideoWidget(QWidget *parent)
236         : QOpenGLWidget(parent) {}
237
238 GLuint compile_shader(const string &shader_src, GLenum type)
239 {
240         GLuint obj = glCreateShader(type);
241         const GLchar* source[] = { shader_src.data() };
242         const GLint length[] = { (GLint)shader_src.size() };
243         glShaderSource(obj, 1, source, length);
244         glCompileShader(obj);
245
246         GLchar info_log[4096];
247         GLsizei log_length = sizeof(info_log) - 1;
248         glGetShaderInfoLog(obj, log_length, &log_length, info_log);
249         info_log[log_length] = 0;
250         if (strlen(info_log) > 0) {
251                 fprintf(stderr, "Shader compile log: %s\n", info_log);
252         }
253
254         GLint status;
255         glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
256         if (status == GL_FALSE) {
257                 // Add some line numbers to easier identify compile errors.
258                 string src_with_lines = "/*   1 */ ";
259                 size_t lineno = 1;
260                 for (char ch : shader_src) {
261                         src_with_lines.push_back(ch);
262                         if (ch == '\n') {
263                                 char buf[32];
264                                 snprintf(buf, sizeof(buf), "/* %3zu */ ", ++lineno);
265                                 src_with_lines += buf;
266                         }
267                 }
268
269                 fprintf(stderr, "Failed to compile shader:\n%s\n", src_with_lines.c_str());
270                 exit(1);
271         }
272
273         return obj;
274 }
275
276 void VideoWidget::initializeGL()
277 {
278         glDisable(GL_BLEND);
279         glDisable(GL_DEPTH_TEST);
280         glDepthMask(GL_FALSE);
281         glCreateTextures(GL_TEXTURE_2D, 3, tex);
282
283         ycbcr_vertex_shader = compile_shader(R"(
284 #version 460 core
285
286 layout(location = 0) in vec2 position;
287 layout(location = 1) in vec2 texcoord;
288 out vec2 tc;
289
290 void main()
291 {
292         // The result of glOrtho(0.0, 1.0, 0.0, 1.0, 0.0, 1.0) is:
293         //
294         //   2.000  0.000  0.000 -1.000
295         //   0.000  2.000  0.000 -1.000
296         //   0.000  0.000 -2.000 -1.000
297         //   0.000  0.000  0.000  1.000
298         gl_Position = vec4(2.0 * position.x - 1.0, 2.0 * position.y - 1.0, -1.0, 1.0);
299         tc = texcoord;
300         tc.y = 1.0f - tc.y;
301 }
302 )", GL_VERTEX_SHADER);
303         ycbcr_fragment_shader = compile_shader(R"(
304 #version 460 core
305
306 layout(location = 0) uniform sampler2D tex_y;
307 layout(location = 1) uniform sampler2D tex_cb;
308 layout(location = 2) uniform sampler2D tex_cr;
309 layout(location = 3) uniform vec2 cbcr_offset;
310
311 in vec2 tc;
312 out vec4 FragColor;
313
314 // Computed statically by Movit, for limited-range BT.709.
315 // (We don't check whether the input could be BT.601 or BT.2020 currently, or full-range)
316 const mat3 inv_ycbcr_matrix = mat3(
317         1.16438f, 1.16438f, 1.16438f,
318         0.0f, -0.21325f, 2.11240f,
319         1.79274f, -0.53291f, 0.0f
320 );
321
322 void main()
323 {
324         if (tc.x < 0.0 || tc.x > 1.0 || tc.y < 0.0 || tc.y > 1.0) {
325                 FragColor.rgba = vec4(0.0f, 0.0f, 0.0f, 1.0f);
326                 return;
327         }
328
329         vec3 ycbcr;
330         ycbcr.r = texture(tex_y, tc).r;
331         ycbcr.g = texture(tex_cb, tc + cbcr_offset).r;
332         ycbcr.b = texture(tex_cr, tc + cbcr_offset).r;
333         ycbcr -= vec3(16.0f / 255.0f, 128.0f / 255.0f, 128.0f / 255.0f);
334         FragColor.rgb = inv_ycbcr_matrix * ycbcr;
335         FragColor.a = 1.0f;
336 }
337 )", GL_FRAGMENT_SHADER);
338         ycbcr_program = glCreateProgram();
339         glAttachShader(ycbcr_program, ycbcr_vertex_shader);
340         glAttachShader(ycbcr_program, ycbcr_fragment_shader);
341         glLinkProgram(ycbcr_program);
342
343         GLint success;
344         glGetProgramiv(ycbcr_program, GL_LINK_STATUS, &success);
345         if (success == GL_FALSE) {
346                 GLchar error_log[1024] = {0};
347                 glGetProgramInfoLog(ycbcr_program, 1024, nullptr, error_log);
348                 fprintf(stderr, "Error linking program: %s\n", error_log);
349                 exit(1);
350         }
351
352         glCreateSamplers(1, &bilinear_sampler);
353         glSamplerParameteri(bilinear_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
354         glSamplerParameteri(bilinear_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
355         glSamplerParameteri(bilinear_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
356         glSamplerParameteri(bilinear_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
357 }
358
359 void VideoWidget::resizeGL(int w, int h)
360 {
361         glViewport(0, 0, w, h);
362         display_aspect = double(w) / h;
363 }
364
365 int num_levels(GLuint width, GLuint height)
366 {
367         int levels = 1;
368         while (width > 1 || height > 1) {
369                 width = max(width / 2, 1u);
370                 height = max(height / 2, 1u);
371                 ++levels;
372         }
373         return levels;
374 }
375
376 void VideoWidget::paintGL()
377 {
378         std::shared_ptr<Frame> frame = current_frame;
379         if (frame == nullptr) {
380                 glClear(GL_COLOR_BUFFER_BIT);
381                 return;
382         }
383
384         glUseProgram(ycbcr_program);
385         if (frame->width != last_width || frame->height != last_height) {
386                 glTextureStorage2D(tex[0], num_levels(frame->width, frame->height), GL_R8, frame->width, frame->height);
387         }
388         if (frame->chroma_width != last_chroma_width || frame->chroma_height != last_chroma_height) {
389                 for (GLuint num : { tex[1], tex[2] }) {
390                         glTextureStorage2D(num, num_levels(frame->chroma_width, frame->chroma_height), GL_R8, frame->chroma_width, frame->chroma_height);
391                 }
392         }
393
394         glTextureSubImage2D(tex[0], 0, 0, 0, frame->width, frame->height, GL_RED, GL_UNSIGNED_BYTE, frame->data.get());
395         glGenerateTextureMipmap(tex[0]);
396
397         glTextureSubImage2D(tex[1], 0, 0, 0, frame->chroma_width, frame->chroma_height, GL_RED, GL_UNSIGNED_BYTE, frame->data.get() + frame->width * frame->height);
398         glGenerateTextureMipmap(tex[1]);
399
400         glTextureSubImage2D(tex[2], 0, 0, 0, frame->chroma_width, frame->chroma_height, GL_RED, GL_UNSIGNED_BYTE, frame->data.get() + frame->width * frame->height + frame->chroma_width * frame->chroma_height);
401         glGenerateTextureMipmap(tex[2]);
402
403         glBindTextureUnit(0, tex[0]);
404         glBindTextureUnit(1, tex[1]);
405         glBindTextureUnit(2, tex[2]);
406         glBindSampler(0, bilinear_sampler);
407         glBindSampler(1, bilinear_sampler);
408         glBindSampler(2, bilinear_sampler);
409         glProgramUniform1i(ycbcr_program, 0, 0);
410         glProgramUniform1i(ycbcr_program, 1, 1);
411         glProgramUniform1i(ycbcr_program, 2, 2);
412         glProgramUniform2f(ycbcr_program, 3, cbcr_offset[0], -cbcr_offset[1]);
413
414         float tx1 = 0.0f;
415         float tx2 = 1.0f;
416         float ty1 = 0.0f;
417         float ty2 = 1.0f;
418
419         double video_aspect = double(frame->width) / frame->height;
420         if (display_aspect > video_aspect) {
421                 double extra_width = frame->height * display_aspect - frame->width;
422                 tx1 = -0.5 * extra_width / frame->width;
423                 tx2 = 1.0 + 0.5 * extra_width / frame->width;
424         } else if (display_aspect < video_aspect) {
425                 double extra_height = frame->width / display_aspect - frame->height;
426                 ty1 = -0.5 * extra_height / frame->height;
427                 ty2 = 1.0 + 0.5 * extra_height / frame->height;
428         }
429
430         glBegin(GL_QUADS);
431
432         // (0,0)
433         glVertexAttrib2f(1, tx1, ty1);
434         glVertex2f(zoom_matrix[2 * 3 + 0], zoom_matrix[2 * 3 + 1]);
435
436         // (0,1)
437         glVertexAttrib2f(1, tx1, ty2);
438         glVertex2f(zoom_matrix[1 * 3 + 0] + zoom_matrix[2 * 3 + 0], zoom_matrix[1 * 3 + 1] + zoom_matrix[2 * 3 + 1]);
439
440         // (1,1)
441         glVertexAttrib2f(1, tx2, ty2);
442         glVertex2f(zoom_matrix[0 * 3 + 0] + zoom_matrix[1 * 3 + 0] + zoom_matrix[2 * 3 + 0],
443                    zoom_matrix[1 * 3 + 0] + zoom_matrix[1 * 3 + 1] + zoom_matrix[2 * 3 + 1]);
444
445         // (1,0)
446         glVertexAttrib2f(1, tx2, ty1);
447         glVertex2f(zoom_matrix[0 * 3 + 0] + zoom_matrix[2 * 3 + 0],
448                    zoom_matrix[1 * 3 + 0] + zoom_matrix[2 * 3 + 1]);
449
450         glEnd();
451 }
452
453 void matmul3x3(const double a[9], const double b[9], double res[9])
454 {
455         for (int i = 0; i < 3; ++i) {
456                 for (int j = 0; j < 3; ++j) {
457                         double sum = 0.0;
458                         for (int k = 0; k < 3; ++k) {
459                                 sum += a[i * 3 + k] * b[k * 3 + j];
460                         }
461                         res[i * 3 + j] = sum;
462                 }
463         }
464 }
465
466 void VideoWidget::wheelEvent(QWheelEvent *event)
467 {
468         int delta = event->angleDelta().y();
469         if (delta == 0) {
470                 return;
471         }
472         double x = event->position().x() / width();
473         double y = 1.0 - event->position().y() / height();
474         double zoom = delta > 0 ? pow(1.005, delta) : pow(1/1.005, -delta);
475
476         const double inv_translation_matrix[9] = {
477                 1.0, 0.0, 0.0,
478                 0.0, 1.0, 0.0,
479                 -x, -y, 1.0
480         };
481         const double scale_matrix[9] = {
482                 zoom, 0.0, 0.0,
483                 0.0, zoom, 0.0,
484                 0.0, 0.0, 1.0
485         };
486         const double translation_matrix[9] = {
487                 1.0, 0.0, 0.0,
488                 0.0, 1.0, 0.0,
489                 x, y, 1.0
490         };
491         double tmp1[9], tmp2[9];
492         matmul3x3(zoom_matrix, inv_translation_matrix, tmp1);
493         matmul3x3(tmp1, scale_matrix, tmp2);
494         matmul3x3(tmp2, translation_matrix, zoom_matrix);
495
496         fixup_zoom_matrix();
497         update();
498 }
499
500 void VideoWidget::mousePressEvent(QMouseEvent *e)
501 {
502         if (e->button() == Qt::BackButton) {
503                 emit mouse_back_clicked();
504         } else if (e->button() == Qt::ForwardButton) {
505                 emit mouse_forward_clicked();
506         } else if (e->button() == Qt::LeftButton) {
507                 dragging = true;
508                 last_drag_x = e->position().x();
509                 last_drag_y = e->position().y();
510         }
511 }
512
513 void VideoWidget::mouseReleaseEvent(QMouseEvent *e)
514 {
515         if (e->button() == Qt::LeftButton) {
516                 dragging = false;
517         }
518 }
519
520 void VideoWidget::mouseMoveEvent(QMouseEvent *e)
521 {
522         if (!dragging) {
523                 return;
524         }
525         float dx = (e->position().x() - last_drag_x) / width();
526         float dy = (e->position().y() - last_drag_y) / height();
527
528         //zoom_matrix[6] += dx * zoom_matrix[0];
529         //zoom_matrix[7] += dy * zoom_matrix[4];
530         zoom_matrix[6] += dx;
531         zoom_matrix[7] -= dy;
532         fixup_zoom_matrix();
533
534         last_drag_x = e->position().x();
535         last_drag_y = e->position().y();
536
537         update();
538 }
539
540 // Normalize the matrix so that we never get skew or similar,
541 // and also never can zoom or pan too far out.
542 void VideoWidget::fixup_zoom_matrix()
543 {
544         // Correct for any numerical errors (we know the matrix must be orthogonal
545         // and have zero rotation).
546         zoom_matrix[4] = zoom_matrix[0];
547         zoom_matrix[1] = zoom_matrix[2] = zoom_matrix[3] = zoom_matrix[5] = 0.0;
548         zoom_matrix[8] = 1.0;
549
550         // We can't zoom further out than 1:1. (Perhaps it would be nice to
551         // reuse the last zoom-in point to do this, but the center will have to do
552         // for now.)
553         if (zoom_matrix[0] < 1.0) {
554                 const double zoom = 1.0 / zoom_matrix[0];
555                 const double inv_translation_matrix[9] = {
556                         1.0, 0.0, 0.0,
557                         0.0, 1.0, 0.0,
558                         -0.5, -0.5, 1.0
559                 };
560                 const double scale_matrix[9] = {
561                         zoom, 0.0, 0.0,
562                         0.0, zoom, 0.0,
563                         0.0, 0.0, 1.0
564                 };
565                 const double translation_matrix[9] = {
566                         1.0, 0.0, 0.0,
567                         0.0, 1.0, 0.0,
568                         0.5, 0.5, 1.0
569                 };
570                 double tmp1[9], tmp2[9];
571                 matmul3x3(zoom_matrix, inv_translation_matrix, tmp1);
572                 matmul3x3(tmp1, scale_matrix, tmp2);
573                 matmul3x3(tmp2, translation_matrix, zoom_matrix);
574         }
575
576         // Looking at the points we'll draw with glVertex2f(), make sure none of them are
577         // inside the square (which would generally mean we've panned ourselves out-of-bounds).
578         // We simply adjust the translation, which is possible because we fixed scaling above.
579         zoom_matrix[6] = min(zoom_matrix[6], 0.0);  // Left side (x=0).
580         zoom_matrix[7] = min(zoom_matrix[7], 0.0);  // Bottom side (y=0).
581         zoom_matrix[6] = std::max(zoom_matrix[6], 1.0 - zoom_matrix[0]);  // Right side (x=1).
582         zoom_matrix[7] = std::max(zoom_matrix[7], 1.0 - zoom_matrix[4]);  // Top side (y=1).
583 }
584
585 void VideoWidget::open(const string &filename)
586 {
587         stop();
588         internal_rewind();
589         pathname = filename;
590         play();
591 }
592
593 void VideoWidget::play()
594 {
595         if (running) {
596                 std::lock_guard<std::mutex> lock(queue_mu);
597                 command_queue.push_back(QueuedCommand { QueuedCommand::RESUME });
598                 producer_thread_should_quit.wakeup();
599                 return;
600         }
601         running = true;
602         producer_thread_should_quit.unquit();
603         producer_thread = std::thread(&VideoWidget::producer_thread_func, this);
604 }
605
606 void VideoWidget::pause()
607 {
608         if (!running) {
609                 return;
610         }
611         std::lock_guard<std::mutex> lock(queue_mu);
612         command_queue.push_back(QueuedCommand { QueuedCommand::PAUSE });
613         producer_thread_should_quit.wakeup();
614 }
615
616 void VideoWidget::seek(int64_t relative_seek_ms)
617 {
618         if (!running) {
619                 return;
620         }
621         std::lock_guard<std::mutex> lock(queue_mu);
622         command_queue.push_back(QueuedCommand { QueuedCommand::SEEK, relative_seek_ms, 0, 0 });
623         producer_thread_should_quit.wakeup();
624 }
625
626 void VideoWidget::seek_frames(int64_t relative_seek_frames)
627 {
628         if (!running) {
629                 return;
630         }
631         std::lock_guard<std::mutex> lock(queue_mu);
632         command_queue.push_back(QueuedCommand { QueuedCommand::SEEK, 0, relative_seek_frames, 0 });
633         producer_thread_should_quit.wakeup();
634 }
635
636 void VideoWidget::seek_absolute(int64_t position_ms)
637 {
638         if (!running) {
639                 return;
640         }
641         std::lock_guard<std::mutex> lock(queue_mu);
642         command_queue.push_back(QueuedCommand { QueuedCommand::SEEK_ABSOLUTE, 0, 0, position_ms });
643         producer_thread_should_quit.wakeup();
644 }
645
646 void VideoWidget::stop()
647 {
648         if (!running) {
649                 return;
650         }
651         running = false;
652         producer_thread_should_quit.quit();
653         producer_thread.join();
654 }
655
656 void VideoWidget::producer_thread_func()
657 {
658         if (!producer_thread_should_quit.should_quit()) {
659                 if (!play_video(pathname)) {
660                         // TODO: Send the error back to the UI somehow.
661                 }
662         }
663 }
664
665 void VideoWidget::internal_rewind()
666 {
667         pts_origin = last_pts = 0;
668         last_position = 0;
669         start = next_frame_start = steady_clock::now();
670 }
671
672 template<AVHWDeviceType type>
673 AVPixelFormat get_hw_format(AVCodecContext *ctx, const AVPixelFormat *fmt)
674 {
675         bool found_config_of_right_type = false;
676         for (int i = 0;; ++i) {  // Termination condition inside loop.
677                 const AVCodecHWConfig *config = avcodec_get_hw_config(ctx->codec, i);
678                 if (config == nullptr) {  // End of list.
679                         break;
680                 }
681                 if (!(config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) ||
682                     config->device_type != type) {
683                         // Not interesting for us.
684                         continue;
685                 }
686
687                 // We have a config of the right type, but does it actually support
688                 // the pixel format we want? (Seemingly, FFmpeg's way of signaling errors
689                 // is to just replace the pixel format with a software-decoded one,
690                 // such as yuv420p.)
691                 found_config_of_right_type = true;
692                 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
693                         if (config->pix_fmt == *fmt_ptr) {
694                                 fprintf(stderr, "Initialized '%s' hardware decoding for codec '%s'.\n",
695                                         av_hwdevice_get_type_name(type), ctx->codec->name);
696                                 if (ctx->profile == FF_PROFILE_H264_BASELINE) {
697                                         fprintf(stderr, "WARNING: Stream claims to be H.264 Baseline, which is generally poorly supported in hardware decoders.\n");
698                                         fprintf(stderr, "         Consider encoding it as Constrained Baseline, Main or High instead.\n");
699                                         fprintf(stderr, "         Decoding might fail and fall back to software.\n");
700                                 }
701                                 return config->pix_fmt;
702                         }
703                 }
704                 fprintf(stderr, "Decoder '%s' supports only these pixel formats:", ctx->codec->name);
705                 unordered_set<AVPixelFormat> seen;
706                 for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
707                         if (!seen.count(*fmt_ptr)) {
708                                 fprintf(stderr, " %s", av_get_pix_fmt_name(*fmt_ptr));
709                                 seen.insert(*fmt_ptr);
710                         }
711                 }
712                 fprintf(stderr, " (wanted %s for hardware acceleration)\n", av_get_pix_fmt_name(config->pix_fmt));
713
714         }
715
716         if (!found_config_of_right_type) {
717                 fprintf(stderr, "Decoder '%s' does not support device type '%s'.\n", ctx->codec->name, av_hwdevice_get_type_name(type));
718         }
719
720         // We found no VA-API formats, so take the first software format.
721         for (const AVPixelFormat *fmt_ptr = fmt; *fmt_ptr != -1; ++fmt_ptr) {
722                 if ((av_pix_fmt_desc_get(*fmt_ptr)->flags & AV_PIX_FMT_FLAG_HWACCEL) == 0) {
723                         fprintf(stderr, "Falling back to software format %s.\n", av_get_pix_fmt_name(*fmt_ptr));
724                         return *fmt_ptr;
725                 }
726         }
727
728         // Fallback: Just return anything. (Should never really happen.)
729         return fmt[0];
730 }
731
732 AVFrameWithDeleter VideoWidget::decode_frame(AVFormatContext *format_ctx, AVCodecContext *video_codec_ctx,
733         const std::string &pathname, int video_stream_index,
734         bool *error)
735 {
736         *error = false;
737
738         if (!queued_frames.empty()) {
739                 AVFrameWithDeleter frame = std::move(queued_frames.front());
740                 queued_frames.pop_front();
741                 return frame;
742         }
743
744         // Read packets until we have a frame or there are none left.
745         bool frame_finished = false;
746         AVFrameWithDeleter video_avframe = av_frame_alloc_unique();
747         bool eof = false;
748         do {
749                 AVPacket *pkt = av_packet_alloc();
750                 unique_ptr<AVPacket, decltype(av_packet_unref)*> pkt_cleanup(
751                         pkt, av_packet_unref);
752                 pkt->data = nullptr;
753                 pkt->size = 0;
754                 if (av_read_frame(format_ctx, pkt) == 0) {
755                         if (pkt->stream_index == video_stream_index) {
756                                 if (avcodec_send_packet(video_codec_ctx, pkt) < 0) {
757                                         fprintf(stderr, "%s: Cannot send packet to video codec.\n", pathname.c_str());
758                                         *error = true;
759                                         return AVFrameWithDeleter(nullptr);
760                                 }
761                         }
762                 } else {
763                         eof = true;  // Or error, but ignore that for the time being.
764                 }
765
766                 // Decode video, if we have a frame.
767                 int err = avcodec_receive_frame(video_codec_ctx, video_avframe.get());
768                 if (err == 0) {
769                         frame_finished = true;
770                         break;
771                 } else if (err != AVERROR(EAGAIN)) {
772                         fprintf(stderr, "%s: Cannot receive frame from video codec.\n", pathname.c_str());
773                         *error = true;
774                         return AVFrameWithDeleter(nullptr);
775                 }
776         } while (!eof);
777
778         if (frame_finished)
779                 return video_avframe;
780         else
781                 return AVFrameWithDeleter(nullptr);
782 }
783
784 int find_stream_index(AVFormatContext *ctx, AVMediaType media_type)
785 {
786         for (unsigned i = 0; i < ctx->nb_streams; ++i) {
787                 if (ctx->streams[i]->codecpar->codec_type == media_type) {
788                         return i;
789                 }
790         }
791         return -1;
792 }
793
794 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)
795 {
796         const duration<double> pts((frame_pts - pts_origin) * double(video_timebase.num) / double(video_timebase.den));
797         return origin + duration_cast<steady_clock::duration>(pts / rate);
798 }
799
800 bool VideoWidget::play_video(const string &pathname)
801 {
802         queued_frames.clear();
803         AVFormatContextWithCloser format_ctx = avformat_open_input_unique(pathname.c_str(), /*fmt=*/nullptr,
804                 /*options=*/nullptr);
805         if (format_ctx == nullptr) {
806                 fprintf(stderr, "%s: Error opening file\n", pathname.c_str());
807                 return false;
808         }
809
810         if (avformat_find_stream_info(format_ctx.get(), nullptr) < 0) {
811                 fprintf(stderr, "%s: Error finding stream info\n", pathname.c_str());
812                 return false;
813         }
814
815         int video_stream_index = find_stream_index(format_ctx.get(), AVMEDIA_TYPE_VIDEO);
816         if (video_stream_index == -1) {
817                 fprintf(stderr, "%s: No video stream found\n", pathname.c_str());
818                 return false;
819         }
820
821         // Open video decoder.
822         const AVCodecParameters *video_codecpar = format_ctx->streams[video_stream_index]->codecpar;
823         const AVCodec *video_codec = avcodec_find_decoder(video_codecpar->codec_id);
824
825         video_timebase = format_ctx->streams[video_stream_index]->time_base;
826         AVCodecContextWithDeleter video_codec_ctx = avcodec_alloc_context3_unique(nullptr);
827         if (avcodec_parameters_to_context(video_codec_ctx.get(), video_codecpar) < 0) {
828                 fprintf(stderr, "%s: Cannot fill video codec parameters\n", pathname.c_str());
829                 return false;
830         }
831         if (video_codec == nullptr) {
832                 fprintf(stderr, "%s: Cannot find video decoder\n", pathname.c_str());
833                 return false;
834         }
835
836         // Seemingly, it's not too easy to make something that just initializes
837         // “whatever goes”, so we don't get CUDA or VULKAN or whatever here
838         // without enumerating through several different types.
839         // VA-API and VDPAU will do for now. We prioritize VDPAU for the
840         // simple reason that there's a VA-API-via-VDPAU emulation for NVidia
841         // cards that seems to work, but just hangs when trying to transfer the frame.
842         //
843         // Note that we don't actually check codec support beforehand,
844         // so if you have a low-end VDPAU device but a high-end VA-API device,
845         // you lose out on the extra codec support from the latter.
846         AVBufferRef *hw_device_ctx = nullptr;
847         if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VDPAU, nullptr, nullptr, 0) >= 0) {
848                 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
849                 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VDPAU>;
850         } else if (av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, nullptr, nullptr, 0) >= 0) {
851                 video_codec_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
852                 video_codec_ctx->get_format = get_hw_format<AV_HWDEVICE_TYPE_VAAPI>;
853         } else {
854                 fprintf(stderr, "Failed to initialize VA-API or VDPAU for FFmpeg acceleration. Decoding video in software.\n");
855         }
856
857         if (avcodec_open2(video_codec_ctx.get(), video_codec, nullptr) < 0) {
858                 fprintf(stderr, "%s: Cannot open video decoder\n", pathname.c_str());
859                 return false;
860         }
861         unique_ptr<AVCodecContext, decltype(avcodec_close)*> video_codec_ctx_cleanup(
862                 video_codec_ctx.get(), avcodec_close);
863
864         internal_rewind();
865
866         // Main loop.
867         int consecutive_errors = 0;
868         double rate = 1.0;
869         while (!producer_thread_should_quit.should_quit()) {
870                 if (process_queued_commands(format_ctx.get(), video_codec_ctx.get(), video_stream_index, /*seeked=*/nullptr)) {
871                         return true;
872                 }
873                 if (paused) {
874                         producer_thread_should_quit.sleep_for(hours(1));
875                         continue;
876                 }
877
878                 bool error;
879                 AVFrameWithDeleter frame = decode_frame(format_ctx.get(), video_codec_ctx.get(),
880                         pathname, video_stream_index, &error);
881                 if (error) {
882                         if (++consecutive_errors >= 100) {
883                                 fprintf(stderr, "More than 100 consecutive video frames, aborting playback.\n");
884                                 return false;
885                         } else {
886                                 continue;
887                         }
888                 } else {
889                         consecutive_errors = 0;
890                 }
891                 if (frame == nullptr) {
892                         // EOF.
893                         return false;
894                 }
895
896                 // Sleep until it's time to present this frame.
897                 for ( ;; ) {
898                         if (last_pts == 0 && pts_origin == 0) {
899                                 pts_origin = frame->pts;
900                         }
901                         steady_clock::time_point now = steady_clock::now();
902                         next_frame_start = compute_frame_start(frame->pts, pts_origin, video_timebase, start, rate);
903
904                         if (duration<double>(now - next_frame_start).count() >= 0.1) {
905                                 // If we don't have enough CPU to keep up, or if we have a live stream
906                                 // where the initial origin was somehow wrong, we could be behind indefinitely.
907                                 fprintf(stderr, "%s: Playback %.0f ms behind, resetting time scale\n",
908                                         pathname.c_str(),
909                                         1e3 * duration<double>(now - next_frame_start).count());
910                                 pts_origin = frame->pts;
911                                 start = next_frame_start = now;
912                         }
913                         bool finished_wakeup;
914                         finished_wakeup = producer_thread_should_quit.sleep_until(next_frame_start);
915                         if (finished_wakeup) {
916                                 current_frame.reset(new Frame(make_video_frame(frame.get())));
917                                 last_frame = steady_clock::now();
918                                 update();
919                                 break;
920                         } else {
921                                 if (producer_thread_should_quit.should_quit()) break;
922
923                                 bool seeked = false;
924                                 if (process_queued_commands(format_ctx.get(), video_codec_ctx.get(), video_stream_index, &seeked)) {
925                                         return true;
926                                 }
927
928                                 if (paused) {
929                                         // Just paused, so present the frame immediately and then go into deep sleep.
930                                         current_frame.reset(new Frame(make_video_frame(frame.get())));
931                                         last_frame = steady_clock::now();
932                                         update();
933                                         break;
934                                 }
935
936                                 // If we just seeked, drop this frame on the floor and be done.
937                                 if (seeked) {
938                                         break;
939                                 }
940                         }
941                 }
942                 store_pts(frame->pts);
943         }
944         return true;
945 }
946
947 void VideoWidget::store_pts(int64_t pts)
948 {
949         last_pts = pts;
950         last_position = lrint(pts * double(video_timebase.num) / double(video_timebase.den) * 1000);
951         post_to_main_thread([this, last_position{last_position.load()}] {
952                 emit position_changed(last_position);
953         });
954 }
955
956 // Taken from Movit (see the comment there for explanation)
957 float compute_chroma_offset(float pos, unsigned subsampling_factor, unsigned resolution)
958 {
959         float local_chroma_pos = (0.5 + pos * (subsampling_factor - 1)) / subsampling_factor;
960         if (fabs(local_chroma_pos - 0.5) < 1e-10) {
961                 // x + (-0) can be optimized away freely, as opposed to x + 0.
962                 return -0.0;
963         } else {
964                 return (0.5 - local_chroma_pos) / resolution;
965         }
966 }
967
968 VideoWidget::Frame VideoWidget::make_video_frame(const AVFrame *frame)
969 {
970         Frame video_frame;
971         AVFrameWithDeleter sw_frame;
972
973         if (frame->format == AV_PIX_FMT_VAAPI ||
974             frame->format == AV_PIX_FMT_VDPAU) {
975                 // Get the frame down to the CPU. (TODO: See if we can keep it
976                 // on the GPU all the way, since it will be going up again later.
977                 // However, this only works if the OpenGL GPU is the same one.)
978                 sw_frame = av_frame_alloc_unique();
979                 int err = av_hwframe_transfer_data(sw_frame.get(), frame, 0);
980                 if (err != 0) {
981                         fprintf(stderr, "%s: Cannot transfer hardware video frame to software.\n", pathname.c_str());
982                 } else {
983                         sw_frame->pts = frame->pts;
984                         sw_frame->pkt_duration = frame->pkt_duration;
985                         frame = sw_frame.get();
986                 }
987         }
988
989         if (sws_ctx == nullptr ||
990             sws_last_width != frame->width ||
991             sws_last_height != frame->height ||
992             sws_last_src_format != frame->format) {
993                 sws_dst_format = decide_dst_format(AVPixelFormat(frame->format));
994                 sws_ctx.reset(
995                         sws_getContext(frame->width, frame->height, AVPixelFormat(frame->format),
996                                 frame->width, frame->height, sws_dst_format,
997                                 SWS_BICUBIC, nullptr, nullptr, nullptr));
998                 sws_last_width = frame->width;
999                 sws_last_height = frame->height;
1000                 sws_last_src_format = frame->format;
1001         }
1002         if (sws_ctx == nullptr) {
1003                 fprintf(stderr, "Could not create scaler context\n");
1004                 abort();
1005         }
1006
1007         uint8_t *pic_data[4] = { nullptr, nullptr, nullptr, nullptr };
1008         int linesizes[4] = { 0, 0, 0, 0 };
1009         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(sws_dst_format);
1010
1011         video_frame.width = frame->width;
1012         video_frame.height = frame->height;
1013         video_frame.chroma_width = AV_CEIL_RSHIFT(int(frame->width), desc->log2_chroma_w);
1014         video_frame.chroma_height = AV_CEIL_RSHIFT(int(frame->height), desc->log2_chroma_h);
1015
1016         // We always assume left chroma placement for now.
1017         cbcr_offset[0] = compute_chroma_offset(0.0f, 1 << desc->log2_chroma_w, video_frame.chroma_width);
1018         cbcr_offset[1] = compute_chroma_offset(0.5f, 1 << desc->log2_chroma_h, video_frame.chroma_height);
1019
1020         size_t len = frame->width * frame->height + 2 * video_frame.chroma_width * video_frame.chroma_height;
1021         video_frame.data.reset(new uint8_t[len]);
1022
1023         pic_data[0] = video_frame.data.get();
1024         linesizes[0] = frame->width;
1025
1026         pic_data[1] = pic_data[0] + frame->width * frame->height;
1027         linesizes[1] = video_frame.chroma_width;
1028
1029         pic_data[2] = pic_data[1] + video_frame.chroma_width * video_frame.chroma_height;
1030         linesizes[2] = video_frame.chroma_width;
1031
1032         sws_scale(sws_ctx.get(), frame->data, frame->linesize, 0, frame->height, pic_data, linesizes);
1033
1034         return video_frame;
1035 }
1036