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