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