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