]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
Reintroduce faster DeckLink shutdown; now with a fix for the UI switcher.
[nageru] / futatabi / player.cpp
1 #include "player.h"
2
3 #include "clip_list.h"
4 #include "defs.h"
5 #include "flags.h"
6 #include "frame_on_disk.h"
7 #include "jpeg_frame_view.h"
8 #include "shared/context.h"
9 #include "shared/ffmpeg_raii.h"
10 #include "shared/httpd.h"
11 #include "shared/metrics.h"
12 #include "shared/mux.h"
13 #include "shared/timebase.h"
14 #include "video_stream.h"
15
16 #include <algorithm>
17 #include <chrono>
18 #include <condition_variable>
19 #include <movit/util.h>
20 #include <mutex>
21 #include <stdio.h>
22 #include <thread>
23 #include <vector>
24
25 using namespace std;
26 using namespace std::chrono;
27
28 extern HTTPD *global_httpd;
29
30 void Player::thread_func(AVFormatContext *file_avctx)
31 {
32         pthread_setname_np(pthread_self(), "Player");
33
34         QSurface *surface = create_surface();
35         QOpenGLContext *context = create_context(surface);
36         if (!make_current(context, surface)) {
37                 printf("oops\n");
38                 abort();
39         }
40
41         check_error();
42
43         // Create the VideoStream object, now that we have an OpenGL context.
44         if (stream_output != NO_STREAM_OUTPUT) {
45                 video_stream.reset(new VideoStream(file_avctx));
46                 video_stream->start();
47         }
48
49         check_error();
50
51         while (!should_quit) {
52                 play_playlist_once();
53         }
54 }
55
56 namespace {
57
58 double calc_progress(const Clip &clip, int64_t pts)
59 {
60         return double(pts - clip.pts_in) / (clip.pts_out - clip.pts_in);
61 }
62
63 void do_splice(const vector<ClipWithID> &new_list, size_t playing_index1, ssize_t playing_index2, vector<ClipWithID> *old_list)
64 {
65         assert(playing_index2 == -1 || size_t(playing_index2) == playing_index1 + 1);
66
67         // First see if we can do the simple thing; find an element in the new
68         // list that we are already playing, which will serve as our splice point.
69         int splice_start_new_list = -1;
70         for (size_t clip_idx = 0; clip_idx < new_list.size(); ++clip_idx) {
71                 if (new_list[clip_idx].id == (*old_list)[playing_index1].id) {
72                         splice_start_new_list = clip_idx + 1;
73                 } else if (playing_index2 != -1 && new_list[clip_idx].id == (*old_list)[playing_index2].id) {
74                         splice_start_new_list = clip_idx + 1;
75                 }
76         }
77         if (splice_start_new_list == -1) {
78                 // OK, so the playing items are no longer in the new list. Most likely,
79                 // that means we deleted some range that included them. But the ones
80                 // before should stay put -- and we don't want to play them. So find
81                 // the ones that we've already played, and ignore them. Hopefully,
82                 // they're contiguous; the last one that's not seen will be our cut point.
83                 //
84                 // Keeping track of the playlist range explicitly in the UI would remove
85                 // the need for these heuristics, but it would probably also mean we'd
86                 // have to lock the playing clip, which sounds annoying.
87                 unordered_map<uint64_t, size_t> played_ids;
88                 for (size_t clip_idx = 0; clip_idx < playing_index1; ++old_list) {
89                         played_ids.emplace((*old_list)[clip_idx].id, clip_idx);
90                 }
91                 for (size_t clip_idx = 0; clip_idx < new_list.size(); ++clip_idx) {
92                         if (played_ids.count(new_list[clip_idx].id)) {
93                                 splice_start_new_list = clip_idx + 1;
94                         }
95                 }
96
97                 if (splice_start_new_list == -1) {
98                         // OK, we didn't find any matches; the lists are totally distinct.
99                         // So probably the entire thing was deleted; leave it alone.
100                         return;
101                 }
102         }
103
104         size_t splice_start_old_list = ((playing_index2 == -1) ? playing_index1 : playing_index2) + 1;
105         old_list->erase(old_list->begin() + splice_start_old_list, old_list->end());
106         old_list->insert(old_list->end(), new_list.begin() + splice_start_new_list, new_list.end());
107 }
108
109 // Keeps track of the various timelines (wall clock time, output pts,
110 // position in the clip we are playing). Generally we keep an origin
111 // and assume we increase linearly from there; the intention is to
112 // avoid getting compounded accuracy errors, although with double,
113 // that is perhaps overkill. (Whenever we break the linear assumption,
114 // we need to reset said origin.)
115 class TimelineTracker
116 {
117 public:
118         struct Instant {
119                 steady_clock::time_point wallclock_time;
120                 int64_t in_pts;
121                 int64_t out_pts;
122                 int64_t frameno;
123         };
124
125         TimelineTracker(double master_speed, int64_t out_pts_origin)
126                 : master_speed(master_speed), last_out_pts(out_pts_origin) {
127                 origin.out_pts = out_pts_origin;
128                 master_speed_ease_target = master_speed;  // Keeps GCC happy.
129         }
130
131         void new_clip(steady_clock::time_point wallclock_origin, const Clip *clip, int64_t start_pts_offset)
132         {
133                 this->clip = clip;
134                 origin.wallclock_time = wallclock_origin;
135                 origin.in_pts = clip->pts_in + start_pts_offset;
136                 origin.out_pts = last_out_pts;
137                 origin.frameno = 0;
138         }
139
140         // Returns the current time for said frame.
141         Instant advance_to_frame(int64_t frameno);
142
143         int64_t get_in_pts_origin() const { return origin.in_pts; }
144         bool playing_at_normal_speed() const {
145                 if (in_easing) return false;
146
147                 const double effective_speed = clip->speed * master_speed;
148                 return effective_speed >= 0.999 && effective_speed <= 1.001;
149         }
150
151         void snap_by(int64_t offset) {
152                 if (in_easing) {
153                         // Easing will normally aim for a snap at the very end,
154                         // so don't disturb it by jittering during the ease.
155                         return;
156                 }
157                 origin.in_pts += offset;
158         }
159
160         void change_master_speed(double new_master_speed, Instant now);
161
162         float in_master_speed(float speed) const {
163                 return (!in_easing && fabs(master_speed - speed) < 1e-6);
164         }
165
166         // Instead of changing the speed instantly, change it over the course of
167         // about 200 ms. This is a simple linear ramp; I tried various forms of
168         // Bézier curves for more elegant/dramatic changing, but it seemed linear
169         // looked just as good in practical video.
170         void start_easing(double new_master_speed, int64_t length_out_pts, Instant now);
171
172         int64_t find_easing_length(double master_speed_target, int64_t length_out_pts, const vector<FrameOnDisk> &frames, Instant now);
173
174 private:
175         // Find out how far we are into the easing curve (0..1).
176         // We use this to adjust the input pts.
177         double find_ease_t(double out_pts) const;
178         double easing_out_pts_adjustment(double out_pts) const;
179
180         double master_speed;
181         const Clip *clip = nullptr;
182         Instant origin;
183         int64_t last_out_pts;
184
185         // If easing between new and old master speeds.
186         bool in_easing = false;
187         int64_t ease_started_pts = 0;
188         double master_speed_ease_target;
189         int64_t ease_length_out_pts = 0;
190 };
191
192 TimelineTracker::Instant TimelineTracker::advance_to_frame(int64_t frameno)
193 {
194         Instant ret;
195         double in_pts_double = origin.in_pts + TIMEBASE * clip->speed * (frameno - origin.frameno) * master_speed / global_flags.output_framerate;
196         double out_pts_double = origin.out_pts + TIMEBASE * (frameno - origin.frameno) / global_flags.output_framerate;
197
198         if (in_easing) {
199                 double in_pts_adjustment = easing_out_pts_adjustment(out_pts_double) * clip->speed;
200                 in_pts_double += in_pts_adjustment;
201         }
202
203         ret.in_pts = lrint(in_pts_double);
204         ret.out_pts = lrint(out_pts_double);
205         ret.wallclock_time = origin.wallclock_time + microseconds(lrint((out_pts_double - origin.out_pts) * 1e6 / TIMEBASE));
206         ret.frameno = frameno;
207
208         last_out_pts = ret.out_pts;
209
210         if (in_easing && ret.out_pts >= ease_started_pts + ease_length_out_pts) {
211                 // We have ended easing. Add what we need for the entire easing period,
212                 // then _actually_ change the speed as we go back into normal mode.
213                 origin.out_pts += easing_out_pts_adjustment(out_pts_double);
214                 change_master_speed(master_speed_ease_target, ret);
215                 in_easing = false;
216         }
217
218         return ret;
219 }
220
221 void TimelineTracker::change_master_speed(double new_master_speed, Instant now)
222 {
223         master_speed = new_master_speed;
224
225         // Reset the origins, since the calculations depend on linear interpolation
226         // based on the master speed.
227         origin = now;
228 }
229
230 void TimelineTracker::start_easing(double new_master_speed, int64_t length_out_pts, Instant now)
231 {
232         if (in_easing) {
233                 // Apply whatever we managed to complete of the previous easing.
234                 origin.out_pts += easing_out_pts_adjustment(now.out_pts);
235                 double reached_speed = master_speed + (master_speed_ease_target - master_speed) * find_ease_t(now.out_pts);
236                 change_master_speed(reached_speed, now);
237         }
238         in_easing = true;
239         ease_started_pts = now.out_pts;
240         master_speed_ease_target = new_master_speed;
241         ease_length_out_pts = length_out_pts;
242 }
243
244 double TimelineTracker::find_ease_t(double out_pts) const
245 {
246         return (out_pts - ease_started_pts) / double(ease_length_out_pts);
247 }
248
249 double TimelineTracker::easing_out_pts_adjustment(double out_pts) const
250 {
251         double t = find_ease_t(out_pts);
252         double area_factor = (master_speed_ease_target - master_speed) * ease_length_out_pts;
253         double val = 0.5 * min(t, 1.0) * min(t, 1.0) * area_factor;
254         if (t > 1.0) {
255                 val += area_factor * (t - 1.0);
256         }
257         return val;
258 }
259
260 int64_t TimelineTracker::find_easing_length(double master_speed_target, int64_t desired_length_out_pts, const vector<FrameOnDisk> &frames, Instant now)
261 {
262         // Find out what frame we would have hit (approximately) with the given ease length.
263         double in_pts_length = 0.5 * (master_speed_target + master_speed) * desired_length_out_pts * clip->speed;
264         const int input_frame_num = distance(
265                 frames.begin(),
266                 find_first_frame_at_or_after(frames, lrint(now.in_pts + in_pts_length)));
267
268         // Round length_out_pts to the nearest amount of whole frames.
269         const double frame_length = TIMEBASE / global_flags.output_framerate;
270         const int length_out_frames = lrint(desired_length_out_pts / frame_length);
271
272         // Time the easing so that we aim at 200 ms (or whatever length_out_pts
273         // was), but adjust it so that we hit exactly on a frame. Unless we are
274         // somehow unlucky and run in the middle of a bad fade, this should
275         // lock us nicely into a cadence where we hit original frames (of course
276         // assuming the new speed is a reasonable ratio).
277         //
278         // Assume for a moment that we are easing into a slowdown, and that
279         // we're slightly too late to hit the frame we want to. This means that
280         // we can shorten the ease a bit; this chops some of the total integrated
281         // velocity and arrive at the frame a bit sooner. Solve for the time
282         // we want to shorten the ease by (let's call it x, where the original
283         // length of the ease is called len) such that we hit exactly the in
284         // pts at the right time:
285         //
286         //   0.5 * (mst + ms) * (len - x) * cs + mst * x * cs = desired_len_in_pts
287         //
288         // gives
289         //
290         //   x = (2 * desired_len_in_pts / cs - (mst + ms) * len) / (mst - ms)
291         //
292         // Conveniently, this holds even if we are too early; a negative x
293         // (surprisingly!) gives a lenghtening such that we don't hit the desired
294         // frame, but hit one slightly later. (x larger than len means that
295         // it's impossible to hit the desired frame, even if we dropped the ease
296         // altogether and just changed speeds instantly.) We also have sign invariance,
297         // so that these properties hold even if we are speeding up, not slowing
298         // down. Together, these two properties mean that we can cast a fairly
299         // wide net, trying various input and output frames and seeing which ones
300         // can be matched up with a minimal change to easing time. (This lets us
301         // e.g. end the ease close to the midpoint between two endpoint frames
302         // even if we don't know the frame rate, or deal fairly robustly with
303         // dropped input frames.) Many of these will give us the same answer,
304         // but that's fine, because the ease length is the only output.
305         int64_t best_length_out_pts = TIMEBASE * 10;  // Infinite.
306         for (int output_frame_offset = -2; output_frame_offset <= 2; ++output_frame_offset) {
307                 int64_t aim_length_out_pts = lrint((length_out_frames + output_frame_offset) * frame_length);
308                 if (aim_length_out_pts < 0) {
309                         continue;
310                 }
311
312                 for (int input_frame_offset = -2; input_frame_offset <= 2; ++input_frame_offset) {
313                         if (input_frame_num + input_frame_offset < 0 ||
314                             input_frame_num + input_frame_offset >= int(frames.size())) {
315                                 continue;
316                         }
317                         const int64_t in_pts = frames[input_frame_num + input_frame_offset].pts;
318                         double shorten_by_out_pts = (2.0 * (in_pts - now.in_pts) / clip->speed - (master_speed_target + master_speed) * aim_length_out_pts) / (master_speed_target - master_speed);
319                         int64_t length_out_pts = lrint(aim_length_out_pts - shorten_by_out_pts);
320
321                         if (length_out_pts >= 0 &&
322                             abs(length_out_pts - desired_length_out_pts) < abs(best_length_out_pts - desired_length_out_pts)) {
323                                 best_length_out_pts = length_out_pts;
324                         }
325                 }
326         }
327
328         // If we need more than two seconds of easing, we give up --
329         // this can happen if we're e.g. going from 101% to 100%.
330         // If so, it would be better to let other mechanisms, such as the switch
331         // to the next clip, deal with getting us back into sync.
332         if (best_length_out_pts > TIMEBASE * 2) {
333                 return desired_length_out_pts;
334         } else {
335                 return best_length_out_pts;
336         }
337 }
338
339 }  // namespace
340
341 void Player::play_playlist_once()
342 {
343         vector<ClipWithID> clip_list;
344         bool clip_ready;
345         steady_clock::time_point before_sleep = steady_clock::now();
346         string pause_status;
347
348         // Wait until we're supposed to play something.
349         {
350                 unique_lock<mutex> lock(queue_state_mu);
351                 playing = false;
352                 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
353                         return should_quit || new_clip_ready;
354                 });
355                 if (should_quit) {
356                         return;
357                 }
358                 if (clip_ready) {
359                         new_clip_ready = false;
360                         playing = true;
361                         clip_list = move(queued_clip_list);
362                         queued_clip_list.clear();
363                         assert(!clip_list.empty());
364                         assert(!splice_ready);  // This corner case should have been handled in splice_play().
365                 } else {
366                         pause_status = this->pause_status;
367                 }
368         }
369
370         steady_clock::duration time_slept = steady_clock::now() - before_sleep;
371         int64_t slept_pts = duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
372         if (slept_pts > 0) {
373                 if (video_stream != nullptr) {
374                         // Add silence for the time we're waiting.
375                         video_stream->schedule_silence(steady_clock::now(), pts, slept_pts, QueueSpotHolder());
376                 }
377                 pts += slept_pts;
378         }
379
380         if (!clip_ready) {
381                 if (video_stream != nullptr) {
382                         ++metric_refresh_frame;
383                         string subtitle = "Futatabi " NAGERU_VERSION ";PAUSED;0.000;" + pause_status;
384                         video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder(),
385                                 subtitle);
386                 }
387                 return;
388         }
389
390         should_skip_to_next = false;  // To make sure we don't have a lingering click from before play.
391         steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
392         TimelineTracker timeline(start_master_speed, pts);
393         timeline.new_clip(origin, &clip_list[0].clip, /*pts_offset=*/0);
394         for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
395                 const Clip *clip = &clip_list[clip_idx].clip;
396                 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
397
398                 double next_clip_fade_time = -1.0;
399                 if (next_clip != nullptr) {
400                         double duration_this_clip = double(clip->pts_out - timeline.get_in_pts_origin()) / TIMEBASE / clip->speed;
401                         double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
402                         next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
403                 }
404
405                 int stream_idx = clip->stream_idx;
406
407                 // Start playing exactly at a frame.
408                 // TODO: Snap secondary (fade-to) clips in the same fashion
409                 // so that we don't get jank here).
410                 {
411                         lock_guard<mutex> lock(frame_mu);
412
413                         // Find the first frame such that frame.pts <= in_pts.
414                         auto it = find_last_frame_before(frames[stream_idx], timeline.get_in_pts_origin());
415                         if (it != frames[stream_idx].end()) {
416                                 timeline.snap_by(it->pts - timeline.get_in_pts_origin());
417                         }
418                 }
419
420                 steady_clock::time_point next_frame_start;
421                 for (int64_t frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
422                         TimelineTracker::Instant instant = timeline.advance_to_frame(frameno);
423                         int64_t in_pts = instant.in_pts;
424                         pts = instant.out_pts;
425                         next_frame_start = instant.wallclock_time;
426
427                         float new_master_speed = change_master_speed.exchange(0.0f / 0.0f);
428                         if (!std::isnan(new_master_speed) && !timeline.in_master_speed(new_master_speed)) {
429                                 int64_t ease_length_out_pts = TIMEBASE / 5;  // 200 ms.
430                                 int64_t recommended_pts_length = timeline.find_easing_length(new_master_speed, ease_length_out_pts, frames[clip->stream_idx], instant);
431                                 timeline.start_easing(new_master_speed, recommended_pts_length, instant);
432                         }
433
434                         if (should_skip_to_next.exchange(false)) {  // Test and clear.
435                                 Clip *clip = &clip_list[clip_idx].clip;  // Get a non-const pointer.
436                                 clip->pts_out = std::min<int64_t>(clip->pts_out, llrint(in_pts + clip->fade_time_seconds * clip->speed * TIMEBASE));
437                         }
438
439                         if (in_pts >= clip->pts_out) {
440                                 break;
441                         }
442
443                         // Only play audio if we're within 0.1% of normal speed. We could do
444                         // stretching or pitch shift later if it becomes needed.
445                         const bool play_audio = timeline.playing_at_normal_speed();
446
447                         {
448                                 lock_guard<mutex> lock(queue_state_mu);
449                                 if (splice_ready) {
450                                         if (next_clip == nullptr) {
451                                                 do_splice(to_splice_clip_list, clip_idx, -1, &clip_list);
452                                         } else {
453                                                 do_splice(to_splice_clip_list, clip_idx, clip_idx + 1, &clip_list);
454                                         }
455                                         to_splice_clip_list.clear();
456                                         splice_ready = false;
457
458                                         // Refresh the clip pointer, since the clip list may have been reallocated.
459                                         clip = &clip_list[clip_idx].clip;
460
461                                         // Recompute next_clip and any needed fade times, since the next clip may have changed
462                                         // (or we may have gone from no new clip to having one, or the other way).
463                                         next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
464                                         if (next_clip != nullptr) {
465                                                 double duration_this_clip = double(clip->pts_out - timeline.get_in_pts_origin()) / TIMEBASE / clip->speed;
466                                                 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
467                                                 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
468                                         }
469                                 }
470                         }
471
472                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
473                         metric_player_ahead_seconds.count_event(-duration<double>(time_behind).count());
474                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
475                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
476                                         lrint(1e3 * duration<double>(time_behind).count()));
477                                 ++metric_dropped_unconditional_frame;
478                                 continue;
479                         }
480
481                         // pts not affected by the swapping below.
482                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
483
484                         int primary_stream_idx = stream_idx;
485                         FrameOnDisk secondary_frame;
486                         int secondary_stream_idx = -1;
487                         float fade_alpha = 0.0f;
488                         double time_left_this_clip = double(clip->pts_out - in_pts) / TIMEBASE / clip->speed;
489                         if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
490                                 // We're in a fade to the next clip->
491                                 secondary_stream_idx = next_clip->stream_idx;
492                                 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip->speed);
493                                 in_pts_secondary_for_progress = in_pts_secondary;
494                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
495
496                                 // If more than half-way through the fade, interpolate the next clip
497                                 // instead of the current one, since it's more visible.
498                                 if (fade_alpha >= 0.5f) {
499                                         swap(primary_stream_idx, secondary_stream_idx);
500                                         swap(in_pts, in_pts_secondary);
501                                         fade_alpha = 1.0f - fade_alpha;
502                                 }
503
504                                 FrameOnDisk frame_lower, frame_upper;
505                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
506
507                                 if (ok) {
508                                         secondary_frame = frame_lower;
509                                 } else {
510                                         secondary_stream_idx = -1;
511                                 }
512                         }
513
514                         // NOTE: None of this will take into account any snapping done below.
515                         double clip_progress = calc_progress(*clip, in_pts_for_progress);
516                         map<uint64_t, double> progress{ { clip_list[clip_idx].id, clip_progress } };
517                         TimeRemaining time_remaining;
518                         if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
519                                 double next_clip_progress = calc_progress(*next_clip, in_pts_secondary_for_progress);
520                                 progress[clip_list[clip_idx + 1].id] = next_clip_progress;
521                                 time_remaining = compute_time_left(clip_list, clip_idx + 1, next_clip_progress);
522                         } else {
523                                 time_remaining = compute_time_left(clip_list, clip_idx, clip_progress);
524                         }
525                         if (progress_callback != nullptr) {
526                                 progress_callback(progress, time_remaining);
527                         }
528
529                         FrameOnDisk frame_lower, frame_upper;
530                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
531                         if (!ok) {
532                                 break;
533                         }
534
535                         // Wait until we should, or (given buffering) can, output the frame.
536                         {
537                                 unique_lock<mutex> lock(queue_state_mu);
538                                 if (video_stream == nullptr) {
539                                         // No queue, just wait until the right time and then show the frame.
540                                         new_clip_changed.wait_until(lock, next_frame_start, [this] {
541                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
542                                         });
543                                         if (should_quit) {
544                                                 return;
545                                         }
546                                 } else {
547                                         // If the queue is full (which is really the state we'd like to be in),
548                                         // wait until there's room for one more frame (ie., one was output from
549                                         // VideoStream), or until or until there's a new clip we're supposed to play.
550                                         //
551                                         // In this case, we don't sleep until next_frame_start; the displaying is
552                                         // done by the queue.
553                                         new_clip_changed.wait(lock, [this] {
554                                                 if (num_queued_frames < max_queued_frames) {
555                                                         return true;
556                                                 }
557                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
558                                         });
559                                 }
560                                 if (should_quit) {
561                                         return;
562                                 }
563                                 if (new_clip_ready) {
564                                         if (video_stream != nullptr) {
565                                                 lock.unlock();  // Urg.
566                                                 video_stream->clear_queue();
567                                                 lock.lock();
568                                         }
569                                         return;
570                                 }
571                                 // Honor if we got an override request for the camera.
572                                 if (override_stream_idx != -1) {
573                                         stream_idx = override_stream_idx;
574                                         override_stream_idx = -1;
575                                         continue;
576                                 }
577                         }
578
579                         string subtitle;
580                         {
581                                 stringstream ss;
582                                 ss.imbue(locale("C"));
583                                 ss.precision(3);
584                                 ss << "Futatabi " NAGERU_VERSION ";PLAYING;";
585                                 ss << fixed << (time_remaining.num_infinite * 86400.0 + time_remaining.t);
586                                 ss << ";" << format_duration(time_remaining) << " left";
587                                 subtitle = ss.str();
588                         }
589
590                         // Snap to input frame: If we can do so with less than 1% jitter
591                         // (ie., move less than 1% of an _output_ frame), do so.
592                         // TODO: Snap secondary (fade-to) clips in the same fashion.
593                         double pts_snap_tolerance = 0.01 * double(TIMEBASE) * clip->speed / global_flags.output_framerate;
594                         bool snapped = false;
595                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
596                                 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
597                                         display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
598                                                              secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true,
599                                                              subtitle, play_audio);
600                                         timeline.snap_by(snap_frame.pts - in_pts);
601                                         snapped = true;
602                                         break;
603                                 }
604                         }
605                         if (snapped) {
606                                 continue;
607                         }
608
609                         // If there's nothing to interpolate between, or if interpolation is turned off,
610                         // or we're a preview, then just display the frame.
611                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
612                                 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
613                                                      secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false,
614                                                      subtitle, play_audio);
615                                 continue;
616                         }
617
618                         // The snapping above makes us lock to the input framerate, even in the presence
619                         // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
620                         // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
621                         // get a snap very rarely (in the given case, once every 24 output frames), and by
622                         // that time, we'd have drifted out. We could have solved this by changing the overall
623                         // speed ever so slightly, but it requires that we know the actual frame rate (which
624                         // is difficult in the presence of jitter and missed frames), or at least do some kind
625                         // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
626                         // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
627                         // an original frame every other frame; we would also snap to exactly alpha=0.5 every
628                         // in-between frame. Of course, we will still need to interpolate, but we get a lot
629                         // closer when we actually get close to an original frame. In other words: Snap more
630                         // often, but snap less each time. Unless the input and output frame rates are completely
631                         // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
632                         // really never see in practice).
633                         for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
634                                                  1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
635                                 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
636                                 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
637                                         timeline.snap_by(lrint(subsnap_pts) - in_pts);
638                                         in_pts = lrint(subsnap_pts);
639                                         break;
640                                 }
641                         }
642
643                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
644                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
645                                         lrint(1e3 * duration<double>(time_behind).count()));
646                                 ++metric_dropped_interpolated_frame;
647                                 continue;
648                         }
649
650                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
651                         auto display_func = [this](shared_ptr<Frame> frame) {
652                                 if (destination != nullptr) {
653                                         destination->setFrame(frame);
654                                 }
655                         };
656                         if (secondary_stream_idx == -1) {
657                                 ++metric_interpolated_frame;
658                         } else {
659                                 ++metric_interpolated_faded_frame;
660                         }
661                         video_stream->schedule_interpolated_frame(
662                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
663                                 frame_lower, frame_upper, alpha,
664                                 secondary_frame, fade_alpha, subtitle, play_audio);
665                         last_pts_played = in_pts;  // Not really needed; only previews use last_pts_played.
666                 }
667
668                 // The clip ended.
669                 if (should_quit) {
670                         return;
671                 }
672
673                 // Start the next clip from the point where the fade went out.
674                 if (next_clip != nullptr) {
675                         timeline.new_clip(next_frame_start, next_clip, /*pts_start_offset=*/lrint(next_clip_fade_time * TIMEBASE * clip->speed));
676                 }
677         }
678
679         if (done_callback != nullptr) {
680                 done_callback();
681         }
682 }
683
684 void Player::display_single_frame(int primary_stream_idx, const FrameOnDisk &primary_frame, int secondary_stream_idx, const FrameOnDisk &secondary_frame, double fade_alpha, steady_clock::time_point frame_start, bool snapped, const std::string &subtitle, bool play_audio)
685 {
686         auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha] {
687                 if (destination != nullptr) {
688                         destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
689                 }
690         };
691         if (video_stream == nullptr) {
692                 display_func();
693         } else {
694                 if (secondary_stream_idx == -1) {
695                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
696                         if (snapped) {
697                                 ++metric_original_snapped_frame;
698                         } else {
699                                 ++metric_original_frame;
700                         }
701                         video_stream->schedule_original_frame(
702                                 frame_start, pts, display_func, QueueSpotHolder(this),
703                                 primary_frame, subtitle, play_audio);
704                 } else {
705                         assert(secondary_frame.pts != -1);
706                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
707                         if (snapped) {
708                                 ++metric_faded_snapped_frame;
709                         } else {
710                                 ++metric_faded_frame;
711                         }
712                         video_stream->schedule_faded_frame(frame_start, pts, display_func,
713                                                            QueueSpotHolder(this), primary_frame,
714                                                            secondary_frame, fade_alpha, subtitle);
715                 }
716         }
717         last_pts_played = primary_frame.pts;
718 }
719
720 // Find the frame immediately before and after this point.
721 // If we have an exact match, return it immediately.
722 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
723 {
724         lock_guard<mutex> lock(frame_mu);
725
726         // Find the first frame such that frame.pts >= pts.
727         auto it = find_last_frame_before(frames[stream_idx], pts);
728         if (it == frames[stream_idx].end()) {
729                 return false;
730         }
731         *frame_upper = *it;
732
733         // If we have an exact match, return it immediately.
734         if (frame_upper->pts == pts) {
735                 *frame_lower = *it;
736                 return true;
737         }
738
739         // Find the last frame such that in_pts <= frame.pts (if any).
740         if (it == frames[stream_idx].begin()) {
741                 *frame_lower = *it;
742         } else {
743                 *frame_lower = *(it - 1);
744         }
745         assert(pts >= frame_lower->pts);
746         assert(pts <= frame_upper->pts);
747         return true;
748 }
749
750 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
751         : destination(destination), stream_output(stream_output)
752 {
753         player_thread = thread(&Player::thread_func, this, file_avctx);
754
755         if (stream_output == HTTPD_STREAM_OUTPUT) {
756                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_original_frame);
757                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_faded_frame);
758                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "snapped" } }, &metric_original_snapped_frame);
759                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "snapped" } }, &metric_faded_snapped_frame);
760                 global_metrics.add("http_output_frames", { { "type", "interpolated" } }, &metric_interpolated_frame);
761                 global_metrics.add("http_output_frames", { { "type", "interpolated_faded" } }, &metric_interpolated_faded_frame);
762                 global_metrics.add("http_output_frames", { { "type", "refresh" } }, &metric_refresh_frame);
763                 global_metrics.add("http_dropped_frames", { { "type", "interpolated" } }, &metric_dropped_interpolated_frame);
764                 global_metrics.add("http_dropped_frames", { { "type", "unconditional" } }, &metric_dropped_unconditional_frame);
765
766                 vector<double> quantiles{ 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99 };
767                 metric_player_ahead_seconds.init(quantiles, 60.0);
768                 global_metrics.add("player_ahead_seconds", &metric_player_ahead_seconds);
769         }
770 }
771
772 Player::~Player()
773 {
774         should_quit = true;
775         new_clip_changed.notify_all();
776         player_thread.join();
777
778         if (video_stream != nullptr) {
779                 video_stream->stop();
780         }
781 }
782
783 void Player::play(const vector<ClipWithID> &clips)
784 {
785         lock_guard<mutex> lock(queue_state_mu);
786         new_clip_ready = true;
787         queued_clip_list = clips;
788         splice_ready = false;
789         override_stream_idx = -1;
790         new_clip_changed.notify_all();
791 }
792
793 void Player::splice_play(const vector<ClipWithID> &clips)
794 {
795         lock_guard<mutex> lock(queue_state_mu);
796         if (new_clip_ready) {
797                 queued_clip_list = clips;
798                 assert(!splice_ready);
799                 return;
800         }
801
802         splice_ready = true;
803         to_splice_clip_list = clips;  // Overwrite any queued but not executed splice.
804 }
805
806 void Player::override_angle(unsigned stream_idx)
807 {
808         int64_t last_pts;
809
810         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
811         {
812                 lock_guard<mutex> lock(queue_state_mu);
813                 if (new_clip_ready) {
814                         assert(queued_clip_list.size() == 1);
815                         queued_clip_list[0].clip.stream_idx = stream_idx;
816                         return;
817                 }
818
819                 // If we are playing a clip, set override_stream_idx, and the player thread will
820                 // pick it up and change its internal index.
821                 if (playing) {
822                         override_stream_idx = stream_idx;
823                         new_clip_changed.notify_all();
824                         return;
825                 }
826
827                 // OK, so we're standing still, presumably at the end of a clip.
828                 // Look at the last frame played (if it exists), and show the closest
829                 // thing we've got.
830                 if (last_pts_played < 0) {
831                         return;
832                 }
833                 last_pts = last_pts_played;
834         }
835
836         lock_guard<mutex> lock(frame_mu);
837         auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
838         if (it == frames[stream_idx].end()) {
839                 return;
840         }
841         destination->setFrame(stream_idx, *it);
842 }
843
844 void Player::take_queue_spot()
845 {
846         lock_guard<mutex> lock(queue_state_mu);
847         ++num_queued_frames;
848 }
849
850 void Player::release_queue_spot()
851 {
852         lock_guard<mutex> lock(queue_state_mu);
853         assert(num_queued_frames > 0);
854         --num_queued_frames;
855         new_clip_changed.notify_all();
856 }
857
858 TimeRemaining compute_time_left(const vector<ClipWithID> &clips, size_t currently_playing_idx, double progress_currently_playing)
859 {
860         // Look at the last clip and then start counting from there.
861         TimeRemaining remaining { 0, 0.0 };
862         double last_fade_time_seconds = 0.0;
863         for (size_t row = currently_playing_idx; row < clips.size(); ++row) {
864                 const Clip &clip = clips[row].clip;
865                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
866                 if (clip_length >= 86400.0 || clip.pts_out == -1) {  // More than one day.
867                         ++remaining.num_infinite;
868                 } else {
869                         if (row == currently_playing_idx) {
870                                 // A clip we're playing: Subtract the part we've already played.
871                                 remaining.t = clip_length * (1.0 - progress_currently_playing);
872                         } else {
873                                 // A clip we haven't played yet: Subtract the part that's overlapping
874                                 // with a previous clip (due to fade).
875                                 remaining.t += max(clip_length - last_fade_time_seconds, 0.0);
876                         }
877                 }
878                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
879         }
880         return remaining;
881 }
882
883 string format_duration(TimeRemaining t)
884 {
885         int t_ms = lrint(t.t * 1e3);
886
887         int ms = t_ms % 1000;
888         t_ms /= 1000;
889         int s = t_ms % 60;
890         t_ms /= 60;
891         int m = t_ms;
892
893         char buf[256];
894         if (t.num_infinite > 1 && t.t > 0.0) {
895                 snprintf(buf, sizeof(buf), "%zu clips + %d:%02d.%03d", t.num_infinite, m, s, ms);
896         } else if (t.num_infinite > 1) {
897                 snprintf(buf, sizeof(buf), "%zu clips", t.num_infinite);
898         } else if (t.num_infinite == 1 && t.t > 0.0) {
899                 snprintf(buf, sizeof(buf), "%zu clip + %d:%02d.%03d", t.num_infinite, m, s, ms);
900         } else if (t.num_infinite == 1) {
901                 snprintf(buf, sizeof(buf), "%zu clip", t.num_infinite);
902         } else {
903                 snprintf(buf, sizeof(buf), "%d:%02d.%03d", m, s, ms);
904         }
905         return buf;
906 }