]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
Support exporting interpolated singletrack video. Probably tickles leaks in Player...
[nageru] / futatabi / player.cpp
1 #include "player.h"
2
3 #include "clip_list.h"
4 #include "shared/context.h"
5 #include "defs.h"
6 #include "shared/ffmpeg_raii.h"
7 #include "flags.h"
8 #include "frame_on_disk.h"
9 #include "shared/httpd.h"
10 #include "jpeg_frame_view.h"
11 #include "shared/mux.h"
12 #include "shared/timebase.h"
13 #include "video_stream.h"
14
15 #include <algorithm>
16 #include <chrono>
17 #include <condition_variable>
18 #include <movit/util.h>
19 #include <mutex>
20 #include <stdio.h>
21 #include <thread>
22 #include <vector>
23
24 using namespace std;
25 using namespace std::chrono;
26
27 extern HTTPD *global_httpd;
28
29 void Player::thread_func(Player::StreamOutput stream_output, AVFormatContext *file_avctx)
30 {
31         pthread_setname_np(pthread_self(), "Player");
32
33         QSurface *surface = create_surface();
34         QOpenGLContext *context = create_context(surface);
35         if (!make_current(context, surface)) {
36                 printf("oops\n");
37                 exit(1);
38         }
39
40         check_error();
41
42         // Create the VideoStream object, now that we have an OpenGL context.
43         if (stream_output != NO_STREAM_OUTPUT) {
44                 video_stream.reset(new VideoStream(file_avctx));
45                 video_stream->start();
46         }
47
48         check_error();
49
50         constexpr double output_framerate = 60000.0 / 1001.0;  // FIXME: make configurable
51         int64_t pts = 0;
52         Clip next_clip;
53         size_t next_clip_idx = size_t(-1);
54         bool got_next_clip = false;
55         double next_clip_fade_time = -1.0;
56
57         while (!should_quit) {
58 wait_for_clip:
59                 bool clip_ready;
60                 steady_clock::time_point before_sleep = steady_clock::now();
61
62                 // Wait until we're supposed to play something.
63                 {
64                         unique_lock<mutex> lock(queue_state_mu);
65                         clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
66                                 return should_quit || (new_clip_ready && current_clip.pts_in != -1);
67                         });
68                         if (should_quit) {
69                                 return;
70                         }
71                         new_clip_ready = false;
72                         playing = true;
73                 }
74
75                 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
76                 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
77
78                 if (!clip_ready) {
79                         if (video_stream != nullptr) {
80                                 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
81                         }
82                         continue;
83                 }
84
85                 Clip clip;
86                 size_t clip_idx;
87                 unsigned stream_idx;
88                 {
89                         lock_guard<mutex> lock(mu);
90                         clip = current_clip;
91                         clip_idx = current_clip_idx;
92                         stream_idx = current_stream_idx;
93                 }
94                 steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
95                 int64_t in_pts_origin = clip.pts_in;
96 got_clip:
97                 int64_t out_pts_origin = pts;
98
99                 // Start playing exactly at a frame.
100                 // TODO: Snap secondary (fade-to) clips in the same fashion
101                 // so that we don't get jank here).
102                 {
103                         lock_guard<mutex> lock(frame_mu);
104
105                         // Find the first frame such that frame.pts <= in_pts.
106                         auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
107                         if (it != frames[stream_idx].end()) {
108                                 in_pts_origin = it->pts;
109                         }
110                 }
111
112                 // TODO: Lock to a rational multiple of the frame rate if possible.
113                 double speed = 0.5;
114
115                 int64_t in_pts_start_next_clip = -1;
116                 steady_clock::time_point next_frame_start;
117                 for (int frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
118                         double out_pts = out_pts_origin + TIMEBASE * frameno / output_framerate;
119                         next_frame_start =
120                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
121                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * speed / output_framerate);
122                         pts = lrint(out_pts);
123
124                         if (in_pts >= clip.pts_out) {
125                                 break;
126                         }
127
128                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
129                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
130                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
131                                         lrint(1e3 * duration<double>(time_behind).count()));
132                                 continue;
133                         }
134
135                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / speed;
136                         if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
137                                 // Find the next clip so that we can begin a fade.
138                                 tie(next_clip, next_clip_idx) = next_clip_callback();
139                                 if (next_clip.pts_in != -1) {
140                                         got_next_clip = true;
141
142                                         double duration_next_clip = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
143                                         next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
144                                         in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * speed);
145                                 }
146                         }
147
148                         // pts not affected by the swapping below.
149                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
150
151                         int primary_stream_idx = stream_idx;
152                         FrameOnDisk secondary_frame;
153                         int secondary_stream_idx = -1;
154                         float fade_alpha = 0.0f;
155                         if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
156                                 secondary_stream_idx = next_clip.stream_idx;
157                                 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * speed);
158                                 in_pts_secondary_for_progress = in_pts_secondary;
159                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
160
161                                 // If more than half-way through the fade, interpolate the next clip
162                                 // instead of the current one, since it's more visible.
163                                 if (fade_alpha >= 0.5f) {
164                                         swap(primary_stream_idx, secondary_stream_idx);
165                                         swap(in_pts, in_pts_secondary);
166                                         fade_alpha = 1.0f - fade_alpha;
167                                 }
168
169                                 FrameOnDisk frame_lower, frame_upper;
170                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
171                                 if (ok) {
172                                         secondary_frame = frame_lower;
173                                 }
174                         }
175
176                         if (progress_callback != nullptr) {
177                                 // NOTE: None of this will take into account any snapping done below.
178                                 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / speed;
179                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / speed;
180                                 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
181
182                                 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
183                                         double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / speed;
184                                         double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
185                                         progress[next_clip_idx] = played_next_clip / total_next_length;
186                                 }
187                                 progress_callback(progress);
188                         }
189
190                         FrameOnDisk frame_lower, frame_upper;
191                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
192                         if (!ok) {
193                                 break;
194                         }
195
196                         {
197                                 unique_lock<mutex> lock(queue_state_mu);
198                                 if (video_stream == nullptr) {
199                                         // No queue, just wait until the right time and then show the frame.
200                                         new_clip_changed.wait_until(lock, next_frame_start, [this]{
201                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
202                                         });
203                                 if (should_quit) {
204                                         return;
205                                 }
206                                 } else {
207                                         // If the queue is full (which is really the state we'd like to be in),
208                                         // wait until there's room for one more frame (ie., one was output from
209                                         // VideoStream), or until or until there's a new clip we're supposed to play.
210                                         //
211                                         // In this case, we don't sleep until next_frame_start; the displaying is
212                                         // done by the queue.
213                                         new_clip_changed.wait(lock, [this]{
214                                                 if (num_queued_frames < max_queued_frames) {
215                                                         return true;
216                                                 }
217                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
218                                         });
219                                 }
220                                 if (should_quit) {
221                                         return;
222                                 }
223                                 if (new_clip_ready) {
224                                         if (video_stream != nullptr) {
225                                                 lock.unlock();  // Urg.
226                                                 video_stream->clear_queue();
227                                                 lock.lock();
228                                         }
229                                         got_next_clip = false;
230                                         goto wait_for_clip;
231                                 }
232                                 if (override_stream_idx != -1) {
233                                         stream_idx = override_stream_idx;
234                                         override_stream_idx = -1;
235                                         continue;
236                                 }
237                         }
238
239                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
240                                 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
241                                         if (destination != nullptr) {
242                                                 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
243                                         }
244                                 };
245                                 if (video_stream == nullptr) {
246                                         display_func();
247                                 } else {
248                                         if (secondary_stream_idx == -1) {
249                                                 video_stream->schedule_original_frame(
250                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
251                                                         frame_lower);
252                                         } else {
253                                                 assert(secondary_frame.pts != -1);
254                                                 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
255                                                         QueueSpotHolder(this), frame_lower,
256                                                         secondary_frame, fade_alpha);
257                                         }
258                                 }
259                                 continue;
260                         }
261
262                         // Snap to input frame: If we can do so with less than 1% jitter
263                         // (ie., move less than 1% of an _output_ frame), do so.
264                         // TODO: Snap secondary (fade-to) clips in the same fashion.
265                         bool snapped = false;
266                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
267                                 double snap_pts_as_frameno = (snap_frame.pts - in_pts_origin) * output_framerate / TIMEBASE / speed;
268                                 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
269                                         auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
270                                                 if (destination != nullptr) {
271                                                         destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
272                                                 }
273                                         };
274                                         if (video_stream == nullptr) {
275                                                 display_func();
276                                         } else {
277                                                 if (secondary_stream_idx == -1) {
278                                                         video_stream->schedule_original_frame(
279                                                                 next_frame_start, pts, display_func,
280                                                                 QueueSpotHolder(this), snap_frame);
281                                                 } else {
282                                                         assert(secondary_frame.pts != -1);
283                                                         video_stream->schedule_faded_frame(
284                                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
285                                                                 snap_frame, secondary_frame, fade_alpha);
286                                                 }
287                                         }
288                                         in_pts_origin += snap_frame.pts - in_pts;
289                                         snapped = true;
290                                         break;
291                                 }
292                         }
293                         if (snapped) {
294                                 continue;
295                         }
296
297                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
298                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
299                                         lrint(1e3 * duration<double>(time_behind).count()));
300                                 continue;
301                         }
302
303                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
304
305                         if (video_stream == nullptr) {
306                                 // Previews don't do any interpolation.
307                                 assert(secondary_stream_idx == -1);
308                                 if (destination != nullptr) {
309                                         destination->setFrame(primary_stream_idx, frame_lower);
310                                 }
311                         } else {
312                                 auto display_func = [this](shared_ptr<Frame> frame) {
313                                         if (destination != nullptr) {
314                                                 destination->setFrame(frame);
315                                         }
316                                 };
317                                 video_stream->schedule_interpolated_frame(
318                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
319                                         frame_lower, frame_upper, alpha,
320                                         secondary_frame, fade_alpha);
321                         }
322                 }
323
324                 if (should_quit) {
325                         return;
326                 }
327
328                 // The clip ended.
329
330                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
331                 if (!got_next_clip && next_clip_callback != nullptr) {
332                         tie(next_clip, next_clip_idx) = next_clip_callback();
333                         if (next_clip.pts_in != -1) {
334                                 got_next_clip = true;
335                                 in_pts_start_next_clip = next_clip.pts_in;
336                         }
337                 }
338
339                 // Switch to next clip if we got it.
340                 if (got_next_clip) {
341                         clip = next_clip;
342                         clip_idx = next_clip_idx;
343                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
344                         if (done_callback != nullptr) {
345                                 done_callback();
346                         }
347                         got_next_clip = false;
348
349                         // Start the next clip from the point where the fade went out.
350                         origin = next_frame_start;
351                         in_pts_origin = in_pts_start_next_clip;
352                         goto got_clip;
353                 }
354
355                 {
356                         unique_lock<mutex> lock(queue_state_mu);
357                         playing = false;
358                 }
359                 if (done_callback != nullptr) {
360                         done_callback();
361                 }
362         }
363 }
364
365 // Find the frame immediately before and after this point.
366 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
367 {
368         lock_guard<mutex> lock(frame_mu);
369
370         // Find the first frame such that frame.pts >= pts.
371         auto it = find_last_frame_before(frames[stream_idx], pts);
372         if (it == frames[stream_idx].end()) {
373                 return false;
374         }
375         *frame_upper = *it;
376
377         // Find the last frame such that in_pts <= frame.pts (if any).
378         if (it == frames[stream_idx].begin()) {
379                 *frame_lower = *it;
380         } else {
381                 *frame_lower = *(it - 1);
382         }
383         assert(pts >= frame_lower->pts);
384         assert(pts <= frame_upper->pts);
385         return true;
386 }
387
388 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
389         : destination(destination)
390 {
391         player_thread = thread(&Player::thread_func, this, stream_output, file_avctx);
392 }
393
394 Player::~Player()
395 {
396         should_quit = true;
397         if (video_stream != nullptr) {
398                 video_stream->stop();
399         }
400         new_clip_changed.notify_all();
401         player_thread.join();
402 }
403
404 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
405 {
406         {
407                 lock_guard<mutex> lock(mu);
408                 current_clip = clip;
409                 current_stream_idx = stream_idx;
410                 current_clip_idx = clip_idx;
411         }
412
413         {
414                 lock_guard<mutex> lock(queue_state_mu);
415                 new_clip_ready = true;
416                 override_stream_idx = -1;
417                 new_clip_changed.notify_all();
418         }
419 }
420
421 void Player::override_angle(unsigned stream_idx)
422 {
423         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
424         {
425                 unique_lock<mutex> lock(queue_state_mu);
426                 if (new_clip_ready) {
427                         lock_guard<mutex> lock2(mu);
428                         current_stream_idx = stream_idx;
429                         return;
430                 }
431         }
432
433         // If we are playing a clip, set override_stream_idx, and the player thread will
434         // pick it up and change its internal index.
435         {
436                 unique_lock<mutex> lock(queue_state_mu);
437                 if (playing) {
438                         override_stream_idx = stream_idx;
439                         new_clip_changed.notify_all();
440                 }
441         }
442
443         // OK, so we're standing still, presumably at the end of a clip.
444         // Look at the current pts_out (if it exists), and show the closest
445         // thing we've got.
446         int64_t pts_out;
447         {
448                 lock_guard<mutex> lock(mu);
449                 if (current_clip.pts_out < 0) {
450                         return;
451                 }
452                 pts_out = current_clip.pts_out;
453         }
454
455         lock_guard<mutex> lock(frame_mu);
456         auto it = find_first_frame_at_or_after(frames[stream_idx], pts_out);
457         if (it == frames[stream_idx].end()) {
458                 return;
459         }
460         destination->setFrame(stream_idx, *it);
461 }
462
463 void Player::take_queue_spot()
464 {
465         unique_lock<mutex> lock(queue_state_mu);
466         ++num_queued_frames;
467 }
468
469 void Player::release_queue_spot()
470 {
471         unique_lock<mutex> lock(queue_state_mu);
472         assert(num_queued_frames > 0);
473         --num_queued_frames;
474         new_clip_changed.notify_all();
475 }