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