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