]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
c5581b40a9a6f9462380cac98ac1243b496ff2b1
[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                 origin.in_pts += offset;
153         }
154
155         void change_master_speed(double new_master_speed, Instant now);
156
157         float in_master_speed(float speed) const {
158                 return (!in_easing && fabs(master_speed - speed) < 1e-6);
159         }
160
161         // Instead of changing the speed instantly, change it over the course of
162         // about 200 ms. This is a simple linear ramp; I tried various forms of
163         // Bézier curves for more elegant/dramatic changing, but it seemed linear
164         // looked just as good in practical video.
165         void start_easing(double new_master_speed, Instant now);
166
167 private:
168         // Find out how far we are into the easing curve (0..1).
169         // We use this to adjust the input pts.
170         double find_ease_t(double out_pts) const;
171         double easing_out_pts_adjustment(double out_pts) const;
172
173         double master_speed;
174         const Clip *clip = nullptr;
175         Instant origin;
176         int64_t last_out_pts;
177
178         // If easing between new and old master speeds.
179         bool in_easing = false;
180         int64_t ease_started_pts = 0;
181         double master_speed_ease_target;
182         static constexpr int64_t ease_length_out_pts = TIMEBASE / 5;  // 200 ms.
183 };
184
185 TimelineTracker::Instant TimelineTracker::advance_to_frame(int64_t frameno)
186 {
187         Instant ret;
188         double in_pts_double = origin.in_pts + TIMEBASE * clip->speed * (frameno - origin.frameno) * master_speed / global_flags.output_framerate;
189         double out_pts_double = origin.out_pts + TIMEBASE * (frameno - origin.frameno) / global_flags.output_framerate;
190
191         if (in_easing) {
192                 double in_pts_adjustment = easing_out_pts_adjustment(out_pts_double) * clip->speed;
193                 in_pts_double += in_pts_adjustment;
194         }
195
196         ret.in_pts = lrint(in_pts_double);
197         ret.out_pts = lrint(out_pts_double);
198         ret.wallclock_time = origin.wallclock_time + microseconds(lrint((out_pts_double - origin.out_pts) * 1e6 / TIMEBASE));
199         ret.frameno = frameno;
200
201         last_out_pts = ret.out_pts;
202
203         if (in_easing && ret.out_pts >= ease_started_pts + ease_length_out_pts) {
204                 // We have ended easing. Add what we need for the entire easing period,
205                 // then _actually_ change the speed as we go back into normal mode.
206                 origin.out_pts += easing_out_pts_adjustment(out_pts_double);
207                 change_master_speed(master_speed_ease_target, ret);
208                 in_easing = false;
209         }
210
211         return ret;
212 }
213
214 void TimelineTracker::change_master_speed(double new_master_speed, Instant now)
215 {
216         master_speed = new_master_speed;
217
218         // Reset the origins, since the calculations depend on linear interpolation
219         // based on the master speed.
220         origin = now;
221 }
222
223 void TimelineTracker::start_easing(double new_master_speed, Instant now)
224 {
225         if (in_easing) {
226                 // Apply whatever we managed to complete of the previous easing.
227                 origin.out_pts += easing_out_pts_adjustment(now.out_pts);
228                 double reached_speed = master_speed + (master_speed_ease_target - master_speed) * find_ease_t(now.out_pts);
229                 change_master_speed(reached_speed, now);
230         }
231         in_easing = true;
232         ease_started_pts = now.out_pts;
233         master_speed_ease_target = new_master_speed;
234 }
235
236 double TimelineTracker::find_ease_t(double out_pts) const
237 {
238         return (out_pts - ease_started_pts) / double(ease_length_out_pts);
239 }
240
241 double TimelineTracker::easing_out_pts_adjustment(double out_pts) const
242 {
243         double t = find_ease_t(out_pts);
244         double area_factor = (master_speed_ease_target - master_speed) * ease_length_out_pts;
245         double val = 0.5 * min(t, 1.0) * min(t, 1.0) * area_factor;
246         if (t > 1.0) {
247                 val += area_factor * (t - 1.0);
248         }
249         return val;
250 }
251
252 }  // namespace
253
254 void Player::play_playlist_once()
255 {
256         vector<ClipWithID> clip_list;
257         bool clip_ready;
258         steady_clock::time_point before_sleep = steady_clock::now();
259         string pause_status;
260
261         // Wait until we're supposed to play something.
262         {
263                 unique_lock<mutex> lock(queue_state_mu);
264                 playing = false;
265                 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
266                         return should_quit || new_clip_ready;
267                 });
268                 if (should_quit) {
269                         return;
270                 }
271                 if (clip_ready) {
272                         new_clip_ready = false;
273                         playing = true;
274                         clip_list = move(queued_clip_list);
275                         queued_clip_list.clear();
276                         assert(!clip_list.empty());
277                         assert(!splice_ready);  // This corner case should have been handled in splice_play().
278                 } else {
279                         pause_status = this->pause_status;
280                 }
281         }
282
283         steady_clock::duration time_slept = steady_clock::now() - before_sleep;
284         int64_t slept_pts = duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
285         if (slept_pts > 0) {
286                 if (video_stream != nullptr) {
287                         // Add silence for the time we're waiting.
288                         video_stream->schedule_silence(steady_clock::now(), pts, slept_pts, QueueSpotHolder());
289                 }
290                 pts += slept_pts;
291         }
292
293         if (!clip_ready) {
294                 if (video_stream != nullptr) {
295                         ++metric_refresh_frame;
296                         string subtitle = "Futatabi " NAGERU_VERSION ";PAUSED;0.000;" + pause_status;
297                         video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder(),
298                                 subtitle);
299                 }
300                 return;
301         }
302
303         should_skip_to_next = false;  // To make sure we don't have a lingering click from before play.
304         steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
305         TimelineTracker timeline(start_master_speed, pts);
306         timeline.new_clip(origin, &clip_list[0].clip, /*pts_offset=*/0);
307         for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
308                 const Clip *clip = &clip_list[clip_idx].clip;
309                 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
310
311                 double next_clip_fade_time = -1.0;
312                 if (next_clip != nullptr) {
313                         double duration_this_clip = double(clip->pts_out - timeline.get_in_pts_origin()) / TIMEBASE / clip->speed;
314                         double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
315                         next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
316                 }
317
318                 int stream_idx = clip->stream_idx;
319
320                 // Start playing exactly at a frame.
321                 // TODO: Snap secondary (fade-to) clips in the same fashion
322                 // so that we don't get jank here).
323                 {
324                         lock_guard<mutex> lock(frame_mu);
325
326                         // Find the first frame such that frame.pts <= in_pts.
327                         auto it = find_last_frame_before(frames[stream_idx], timeline.get_in_pts_origin());
328                         if (it != frames[stream_idx].end()) {
329                                 timeline.snap_by(it->pts - timeline.get_in_pts_origin());
330                         }
331                 }
332
333                 steady_clock::time_point next_frame_start;
334                 for (int64_t frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
335                         TimelineTracker::Instant instant = timeline.advance_to_frame(frameno);
336                         int64_t in_pts = instant.in_pts;
337                         pts = instant.out_pts;
338                         next_frame_start = instant.wallclock_time;
339
340                         float new_master_speed = change_master_speed.exchange(0.0f / 0.0f);
341                         if (!std::isnan(new_master_speed) && !timeline.in_master_speed(new_master_speed)) {
342                                 timeline.start_easing(new_master_speed, instant);
343                         }
344
345                         if (should_skip_to_next.exchange(false)) {  // Test and clear.
346                                 Clip *clip = &clip_list[clip_idx].clip;  // Get a non-const pointer.
347                                 clip->pts_out = std::min<int64_t>(clip->pts_out, llrint(in_pts + clip->fade_time_seconds * clip->speed * TIMEBASE));
348                         }
349
350                         if (in_pts >= clip->pts_out) {
351                                 break;
352                         }
353
354                         // Only play audio if we're within 0.1% of normal speed. We could do
355                         // stretching or pitch shift later if it becomes needed.
356                         const bool play_audio = timeline.playing_at_normal_speed();
357
358                         {
359                                 lock_guard<mutex> lock(queue_state_mu);
360                                 if (splice_ready) {
361                                         if (next_clip == nullptr) {
362                                                 do_splice(to_splice_clip_list, clip_idx, -1, &clip_list);
363                                         } else {
364                                                 do_splice(to_splice_clip_list, clip_idx, clip_idx + 1, &clip_list);
365                                         }
366                                         to_splice_clip_list.clear();
367                                         splice_ready = false;
368
369                                         // Refresh the clip pointer, since the clip list may have been reallocated.
370                                         clip = &clip_list[clip_idx].clip;
371
372                                         // Recompute next_clip and any needed fade times, since the next clip may have changed
373                                         // (or we may have gone from no new clip to having one, or the other way).
374                                         next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
375                                         if (next_clip != nullptr) {
376                                                 double duration_this_clip = double(clip->pts_out - timeline.get_in_pts_origin()) / TIMEBASE / clip->speed;
377                                                 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
378                                                 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
379                                         }
380                                 }
381                         }
382
383                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
384                         metric_player_ahead_seconds.count_event(-duration<double>(time_behind).count());
385                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
386                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
387                                         lrint(1e3 * duration<double>(time_behind).count()));
388                                 ++metric_dropped_unconditional_frame;
389                                 continue;
390                         }
391
392                         // pts not affected by the swapping below.
393                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
394
395                         int primary_stream_idx = stream_idx;
396                         FrameOnDisk secondary_frame;
397                         int secondary_stream_idx = -1;
398                         float fade_alpha = 0.0f;
399                         double time_left_this_clip = double(clip->pts_out - in_pts) / TIMEBASE / clip->speed;
400                         if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
401                                 // We're in a fade to the next clip->
402                                 secondary_stream_idx = next_clip->stream_idx;
403                                 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip->speed);
404                                 in_pts_secondary_for_progress = in_pts_secondary;
405                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
406
407                                 // If more than half-way through the fade, interpolate the next clip
408                                 // instead of the current one, since it's more visible.
409                                 if (fade_alpha >= 0.5f) {
410                                         swap(primary_stream_idx, secondary_stream_idx);
411                                         swap(in_pts, in_pts_secondary);
412                                         fade_alpha = 1.0f - fade_alpha;
413                                 }
414
415                                 FrameOnDisk frame_lower, frame_upper;
416                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
417
418                                 if (ok) {
419                                         secondary_frame = frame_lower;
420                                 } else {
421                                         secondary_stream_idx = -1;
422                                 }
423                         }
424
425                         // NOTE: None of this will take into account any snapping done below.
426                         double clip_progress = calc_progress(*clip, in_pts_for_progress);
427                         map<uint64_t, double> progress{ { clip_list[clip_idx].id, clip_progress } };
428                         TimeRemaining time_remaining;
429                         if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
430                                 double next_clip_progress = calc_progress(*next_clip, in_pts_secondary_for_progress);
431                                 progress[clip_list[clip_idx + 1].id] = next_clip_progress;
432                                 time_remaining = compute_time_left(clip_list, clip_idx + 1, next_clip_progress);
433                         } else {
434                                 time_remaining = compute_time_left(clip_list, clip_idx, clip_progress);
435                         }
436                         if (progress_callback != nullptr) {
437                                 progress_callback(progress, time_remaining);
438                         }
439
440                         FrameOnDisk frame_lower, frame_upper;
441                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
442                         if (!ok) {
443                                 break;
444                         }
445
446                         // Wait until we should, or (given buffering) can, output the frame.
447                         {
448                                 unique_lock<mutex> lock(queue_state_mu);
449                                 if (video_stream == nullptr) {
450                                         // No queue, just wait until the right time and then show the frame.
451                                         new_clip_changed.wait_until(lock, next_frame_start, [this] {
452                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
453                                         });
454                                         if (should_quit) {
455                                                 return;
456                                         }
457                                 } else {
458                                         // If the queue is full (which is really the state we'd like to be in),
459                                         // wait until there's room for one more frame (ie., one was output from
460                                         // VideoStream), or until or until there's a new clip we're supposed to play.
461                                         //
462                                         // In this case, we don't sleep until next_frame_start; the displaying is
463                                         // done by the queue.
464                                         new_clip_changed.wait(lock, [this] {
465                                                 if (num_queued_frames < max_queued_frames) {
466                                                         return true;
467                                                 }
468                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
469                                         });
470                                 }
471                                 if (should_quit) {
472                                         return;
473                                 }
474                                 if (new_clip_ready) {
475                                         if (video_stream != nullptr) {
476                                                 lock.unlock();  // Urg.
477                                                 video_stream->clear_queue();
478                                                 lock.lock();
479                                         }
480                                         return;
481                                 }
482                                 // Honor if we got an override request for the camera.
483                                 if (override_stream_idx != -1) {
484                                         stream_idx = override_stream_idx;
485                                         override_stream_idx = -1;
486                                         continue;
487                                 }
488                         }
489
490                         string subtitle;
491                         {
492                                 stringstream ss;
493                                 ss.imbue(locale("C"));
494                                 ss.precision(3);
495                                 ss << "Futatabi " NAGERU_VERSION ";PLAYING;";
496                                 ss << fixed << (time_remaining.num_infinite * 86400.0 + time_remaining.t);
497                                 ss << ";" << format_duration(time_remaining) << " left";
498                                 subtitle = ss.str();
499                         }
500
501                         // Snap to input frame: If we can do so with less than 1% jitter
502                         // (ie., move less than 1% of an _output_ frame), do so.
503                         // TODO: Snap secondary (fade-to) clips in the same fashion.
504                         double pts_snap_tolerance = 0.01 * double(TIMEBASE) * clip->speed / global_flags.output_framerate;
505                         bool snapped = false;
506                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
507                                 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
508                                         display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
509                                                              secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true,
510                                                              subtitle, play_audio);
511                                         timeline.snap_by(snap_frame.pts - in_pts);
512                                         snapped = true;
513                                         break;
514                                 }
515                         }
516                         if (snapped) {
517                                 continue;
518                         }
519
520                         // If there's nothing to interpolate between, or if interpolation is turned off,
521                         // or we're a preview, then just display the frame.
522                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
523                                 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
524                                                      secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false,
525                                                      subtitle, play_audio);
526                                 continue;
527                         }
528
529                         // The snapping above makes us lock to the input framerate, even in the presence
530                         // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
531                         // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
532                         // get a snap very rarely (in the given case, once every 24 output frames), and by
533                         // that time, we'd have drifted out. We could have solved this by changing the overall
534                         // speed ever so slightly, but it requires that we know the actual frame rate (which
535                         // is difficult in the presence of jitter and missed frames), or at least do some kind
536                         // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
537                         // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
538                         // an original frame every other frame; we would also snap to exactly alpha=0.5 every
539                         // in-between frame. Of course, we will still need to interpolate, but we get a lot
540                         // closer when we actually get close to an original frame. In other words: Snap more
541                         // often, but snap less each time. Unless the input and output frame rates are completely
542                         // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
543                         // really never see in practice).
544                         for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
545                                                  1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
546                                 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
547                                 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
548                                         timeline.snap_by(lrint(subsnap_pts) - in_pts);
549                                         in_pts = lrint(subsnap_pts);
550                                         break;
551                                 }
552                         }
553
554                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
555                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
556                                         lrint(1e3 * duration<double>(time_behind).count()));
557                                 ++metric_dropped_interpolated_frame;
558                                 continue;
559                         }
560
561                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
562                         auto display_func = [this](shared_ptr<Frame> frame) {
563                                 if (destination != nullptr) {
564                                         destination->setFrame(frame);
565                                 }
566                         };
567                         if (secondary_stream_idx == -1) {
568                                 ++metric_interpolated_frame;
569                         } else {
570                                 ++metric_interpolated_faded_frame;
571                         }
572                         video_stream->schedule_interpolated_frame(
573                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
574                                 frame_lower, frame_upper, alpha,
575                                 secondary_frame, fade_alpha, subtitle, play_audio);
576                         last_pts_played = in_pts;  // Not really needed; only previews use last_pts_played.
577                 }
578
579                 // The clip ended.
580                 if (should_quit) {
581                         return;
582                 }
583
584                 // Start the next clip from the point where the fade went out.
585                 if (next_clip != nullptr) {
586                         timeline.new_clip(next_frame_start, next_clip, /*pts_start_offset=*/lrint(next_clip_fade_time * TIMEBASE * clip->speed));
587                 }
588         }
589
590         if (done_callback != nullptr) {
591                 done_callback();
592         }
593 }
594
595 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)
596 {
597         auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha] {
598                 if (destination != nullptr) {
599                         destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
600                 }
601         };
602         if (video_stream == nullptr) {
603                 display_func();
604         } else {
605                 if (secondary_stream_idx == -1) {
606                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
607                         if (snapped) {
608                                 ++metric_original_snapped_frame;
609                         } else {
610                                 ++metric_original_frame;
611                         }
612                         video_stream->schedule_original_frame(
613                                 frame_start, pts, display_func, QueueSpotHolder(this),
614                                 primary_frame, subtitle, play_audio);
615                 } else {
616                         assert(secondary_frame.pts != -1);
617                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
618                         if (snapped) {
619                                 ++metric_faded_snapped_frame;
620                         } else {
621                                 ++metric_faded_frame;
622                         }
623                         video_stream->schedule_faded_frame(frame_start, pts, display_func,
624                                                            QueueSpotHolder(this), primary_frame,
625                                                            secondary_frame, fade_alpha, subtitle);
626                 }
627         }
628         last_pts_played = primary_frame.pts;
629 }
630
631 // Find the frame immediately before and after this point.
632 // If we have an exact match, return it immediately.
633 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
634 {
635         lock_guard<mutex> lock(frame_mu);
636
637         // Find the first frame such that frame.pts >= pts.
638         auto it = find_last_frame_before(frames[stream_idx], pts);
639         if (it == frames[stream_idx].end()) {
640                 return false;
641         }
642         *frame_upper = *it;
643
644         // If we have an exact match, return it immediately.
645         if (frame_upper->pts == pts) {
646                 *frame_lower = *it;
647                 return true;
648         }
649
650         // Find the last frame such that in_pts <= frame.pts (if any).
651         if (it == frames[stream_idx].begin()) {
652                 *frame_lower = *it;
653         } else {
654                 *frame_lower = *(it - 1);
655         }
656         assert(pts >= frame_lower->pts);
657         assert(pts <= frame_upper->pts);
658         return true;
659 }
660
661 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
662         : destination(destination), stream_output(stream_output)
663 {
664         player_thread = thread(&Player::thread_func, this, file_avctx);
665
666         if (stream_output == HTTPD_STREAM_OUTPUT) {
667                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_original_frame);
668                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_faded_frame);
669                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "snapped" } }, &metric_original_snapped_frame);
670                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "snapped" } }, &metric_faded_snapped_frame);
671                 global_metrics.add("http_output_frames", { { "type", "interpolated" } }, &metric_interpolated_frame);
672                 global_metrics.add("http_output_frames", { { "type", "interpolated_faded" } }, &metric_interpolated_faded_frame);
673                 global_metrics.add("http_output_frames", { { "type", "refresh" } }, &metric_refresh_frame);
674                 global_metrics.add("http_dropped_frames", { { "type", "interpolated" } }, &metric_dropped_interpolated_frame);
675                 global_metrics.add("http_dropped_frames", { { "type", "unconditional" } }, &metric_dropped_unconditional_frame);
676
677                 vector<double> quantiles{ 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99 };
678                 metric_player_ahead_seconds.init(quantiles, 60.0);
679                 global_metrics.add("player_ahead_seconds", &metric_player_ahead_seconds);
680         }
681 }
682
683 Player::~Player()
684 {
685         should_quit = true;
686         new_clip_changed.notify_all();
687         player_thread.join();
688
689         if (video_stream != nullptr) {
690                 video_stream->stop();
691         }
692 }
693
694 void Player::play(const vector<ClipWithID> &clips)
695 {
696         lock_guard<mutex> lock(queue_state_mu);
697         new_clip_ready = true;
698         queued_clip_list = clips;
699         splice_ready = false;
700         override_stream_idx = -1;
701         new_clip_changed.notify_all();
702 }
703
704 void Player::splice_play(const vector<ClipWithID> &clips)
705 {
706         lock_guard<mutex> lock(queue_state_mu);
707         if (new_clip_ready) {
708                 queued_clip_list = clips;
709                 assert(!splice_ready);
710                 return;
711         }
712
713         splice_ready = true;
714         to_splice_clip_list = clips;  // Overwrite any queued but not executed splice.
715 }
716
717 void Player::override_angle(unsigned stream_idx)
718 {
719         int64_t last_pts;
720
721         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
722         {
723                 lock_guard<mutex> lock(queue_state_mu);
724                 if (new_clip_ready) {
725                         assert(queued_clip_list.size() == 1);
726                         queued_clip_list[0].clip.stream_idx = stream_idx;
727                         return;
728                 }
729
730                 // If we are playing a clip, set override_stream_idx, and the player thread will
731                 // pick it up and change its internal index.
732                 if (playing) {
733                         override_stream_idx = stream_idx;
734                         new_clip_changed.notify_all();
735                         return;
736                 }
737
738                 // OK, so we're standing still, presumably at the end of a clip.
739                 // Look at the last frame played (if it exists), and show the closest
740                 // thing we've got.
741                 if (last_pts_played < 0) {
742                         return;
743                 }
744                 last_pts = last_pts_played;
745         }
746
747         lock_guard<mutex> lock(frame_mu);
748         auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
749         if (it == frames[stream_idx].end()) {
750                 return;
751         }
752         destination->setFrame(stream_idx, *it);
753 }
754
755 void Player::take_queue_spot()
756 {
757         lock_guard<mutex> lock(queue_state_mu);
758         ++num_queued_frames;
759 }
760
761 void Player::release_queue_spot()
762 {
763         lock_guard<mutex> lock(queue_state_mu);
764         assert(num_queued_frames > 0);
765         --num_queued_frames;
766         new_clip_changed.notify_all();
767 }
768
769 TimeRemaining compute_time_left(const vector<ClipWithID> &clips, size_t currently_playing_idx, double progress_currently_playing)
770 {
771         // Look at the last clip and then start counting from there.
772         TimeRemaining remaining { 0, 0.0 };
773         double last_fade_time_seconds = 0.0;
774         for (size_t row = currently_playing_idx; row < clips.size(); ++row) {
775                 const Clip &clip = clips[row].clip;
776                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
777                 if (clip_length >= 86400.0 || clip.pts_out == -1) {  // More than one day.
778                         ++remaining.num_infinite;
779                 } else {
780                         if (row == currently_playing_idx) {
781                                 // A clip we're playing: Subtract the part we've already played.
782                                 remaining.t = clip_length * (1.0 - progress_currently_playing);
783                         } else {
784                                 // A clip we haven't played yet: Subtract the part that's overlapping
785                                 // with a previous clip (due to fade).
786                                 remaining.t += max(clip_length - last_fade_time_seconds, 0.0);
787                         }
788                 }
789                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
790         }
791         return remaining;
792 }
793
794 string format_duration(TimeRemaining t)
795 {
796         int t_ms = lrint(t.t * 1e3);
797
798         int ms = t_ms % 1000;
799         t_ms /= 1000;
800         int s = t_ms % 60;
801         t_ms /= 60;
802         int m = t_ms;
803
804         char buf[256];
805         if (t.num_infinite > 1 && t.t > 0.0) {
806                 snprintf(buf, sizeof(buf), "%zu clips + %d:%02d.%03d", t.num_infinite, m, s, ms);
807         } else if (t.num_infinite > 1) {
808                 snprintf(buf, sizeof(buf), "%zu clips", t.num_infinite);
809         } else if (t.num_infinite == 1 && t.t > 0.0) {
810                 snprintf(buf, sizeof(buf), "%zu clip + %d:%02d.%03d", t.num_infinite, m, s, ms);
811         } else if (t.num_infinite == 1) {
812                 snprintf(buf, sizeof(buf), "%zu clip", t.num_infinite);
813         } else {
814                 snprintf(buf, sizeof(buf), "%d:%02d.%03d", m, s, ms);
815         }
816         return buf;
817 }