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