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"
18 #include <condition_variable>
19 #include <movit/util.h>
26 using namespace std::chrono;
28 extern HTTPD *global_httpd;
30 void Player::thread_func(AVFormatContext *file_avctx)
32 pthread_setname_np(pthread_self(), "Player");
34 QSurface *surface = create_surface();
35 QOpenGLContext *context = create_context(surface);
36 if (!make_current(context, surface)) {
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();
51 while (!should_quit) {
58 double calc_progress(const Clip &clip, int64_t pts)
60 return double(pts - clip.pts_in) / (clip.pts_out - clip.pts_in);
63 void do_splice(const vector<ClipWithID> &new_list, size_t playing_index1, ssize_t playing_index2, vector<ClipWithID> *old_list)
65 assert(playing_index2 == -1 || size_t(playing_index2) == playing_index1 + 1);
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;
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.
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);
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;
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.
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());
109 // Keeps track of the various timelines (wall clock time, output pts,
110 // position in the clip we are playing). Generally we keep an origin
111 // and assume we increase linearly from there; the intention is to
112 // avoid getting compounded accuracy errors, although with double,
113 // that is perhaps overkill. (Whenever we break the linear assumption,
114 // we need to reset said origin.)
115 class TimelineTracker
119 steady_clock::time_point wallclock_time;
125 TimelineTracker(double master_speed, int64_t out_pts_origin)
126 : master_speed(master_speed), last_out_pts(out_pts_origin) {
127 origin.out_pts = out_pts_origin;
128 master_speed_ease_target = master_speed; // Keeps GCC happy.
131 void new_clip(steady_clock::time_point wallclock_origin, const Clip *clip, int64_t start_pts_offset)
134 origin.wallclock_time = wallclock_origin;
135 origin.in_pts = clip->pts_in + start_pts_offset;
136 origin.out_pts = last_out_pts;
140 // Returns the current time for said frame.
141 Instant advance_to_frame(int64_t frameno);
143 int64_t get_in_pts_origin() const { return origin.in_pts; }
144 bool playing_at_normal_speed() const {
145 if (in_easing) return false;
147 const double effective_speed = clip->speed * master_speed;
148 return effective_speed >= 0.999 && effective_speed <= 1.001;
151 void snap_by(int64_t offset) {
153 // Easing will normally aim for a snap at the very end,
154 // so don't disturb it by jittering during the ease.
157 origin.in_pts += offset;
160 void change_master_speed(double new_master_speed, Instant now);
162 float in_master_speed(float speed) const {
163 return (!in_easing && fabs(master_speed - speed) < 1e-6);
166 // Instead of changing the speed instantly, change it over the course of
167 // about 200 ms. This is a simple linear ramp; I tried various forms of
168 // Bézier curves for more elegant/dramatic changing, but it seemed linear
169 // looked just as good in practical video.
170 void start_easing(double new_master_speed, int64_t length_out_pts, Instant now);
172 int64_t find_easing_length(double master_speed_target, int64_t length_out_pts, const vector<FrameOnDisk> &frames, Instant now);
175 // Find out how far we are into the easing curve (0..1).
176 // We use this to adjust the input pts.
177 double find_ease_t(double out_pts) const;
178 double easing_out_pts_adjustment(double out_pts) const;
181 const Clip *clip = nullptr;
183 int64_t last_out_pts;
185 // If easing between new and old master speeds.
186 bool in_easing = false;
187 int64_t ease_started_pts = 0;
188 double master_speed_ease_target;
189 int64_t ease_length_out_pts = 0;
192 TimelineTracker::Instant TimelineTracker::advance_to_frame(int64_t frameno)
195 double in_pts_double = origin.in_pts + TIMEBASE * clip->speed * (frameno - origin.frameno) * master_speed / global_flags.output_framerate;
196 double out_pts_double = origin.out_pts + TIMEBASE * (frameno - origin.frameno) / global_flags.output_framerate;
199 double in_pts_adjustment = easing_out_pts_adjustment(out_pts_double) * clip->speed;
200 in_pts_double += in_pts_adjustment;
203 ret.in_pts = lrint(in_pts_double);
204 ret.out_pts = lrint(out_pts_double);
205 ret.wallclock_time = origin.wallclock_time + microseconds(lrint((out_pts_double - origin.out_pts) * 1e6 / TIMEBASE));
206 ret.frameno = frameno;
208 last_out_pts = ret.out_pts;
210 if (in_easing && ret.out_pts >= ease_started_pts + ease_length_out_pts) {
211 // We have ended easing. Add what we need for the entire easing period,
212 // then _actually_ change the speed as we go back into normal mode.
213 origin.out_pts += easing_out_pts_adjustment(out_pts_double);
214 change_master_speed(master_speed_ease_target, ret);
221 void TimelineTracker::change_master_speed(double new_master_speed, Instant now)
223 master_speed = new_master_speed;
225 // Reset the origins, since the calculations depend on linear interpolation
226 // based on the master speed.
230 void TimelineTracker::start_easing(double new_master_speed, int64_t length_out_pts, Instant now)
233 // Apply whatever we managed to complete of the previous easing.
234 origin.out_pts += easing_out_pts_adjustment(now.out_pts);
235 double reached_speed = master_speed + (master_speed_ease_target - master_speed) * find_ease_t(now.out_pts);
236 change_master_speed(reached_speed, now);
239 ease_started_pts = now.out_pts;
240 master_speed_ease_target = new_master_speed;
241 ease_length_out_pts = length_out_pts;
244 double TimelineTracker::find_ease_t(double out_pts) const
246 return (out_pts - ease_started_pts) / double(ease_length_out_pts);
249 double TimelineTracker::easing_out_pts_adjustment(double out_pts) const
251 double t = find_ease_t(out_pts);
252 double area_factor = (master_speed_ease_target - master_speed) * ease_length_out_pts;
253 double val = 0.5 * min(t, 1.0) * min(t, 1.0) * area_factor;
255 val += area_factor * (t - 1.0);
260 int64_t TimelineTracker::find_easing_length(double master_speed_target, int64_t desired_length_out_pts, const vector<FrameOnDisk> &frames, Instant now)
262 // Find out what frame we would have hit (approximately) with the given ease length.
263 double in_pts_length = 0.5 * (master_speed_target + master_speed) * desired_length_out_pts * clip->speed;
264 const int input_frame_num = distance(
266 find_first_frame_at_or_after(frames, lrint(now.in_pts + in_pts_length)));
268 // Round length_out_pts to the nearest amount of whole frames.
269 const double frame_length = TIMEBASE / global_flags.output_framerate;
270 const int length_out_frames = lrint(desired_length_out_pts / frame_length);
272 // Time the easing so that we aim at 200 ms (or whatever length_out_pts
273 // was), but adjust it so that we hit exactly on a frame. Unless we are
274 // somehow unlucky and run in the middle of a bad fade, this should
275 // lock us nicely into a cadence where we hit original frames (of course
276 // assuming the new speed is a reasonable ratio).
278 // Assume for a moment that we are easing into a slowdown, and that
279 // we're slightly too late to hit the frame we want to. This means that
280 // we can shorten the ease a bit; this chops some of the total integrated
281 // velocity and arrive at the frame a bit sooner. Solve for the time
282 // we want to shorten the ease by (let's call it x, where the original
283 // length of the ease is called len) such that we hit exactly the in
284 // pts at the right time:
286 // 0.5 * (mst + ms) * (len - x) * cs + mst * x * cs = desired_len_in_pts
290 // x = (2 * desired_len_in_pts / cs - (mst + ms) * len) / (mst - ms)
292 // Conveniently, this holds even if we are too early; a negative x
293 // (surprisingly!) gives a lenghtening such that we don't hit the desired
294 // frame, but hit one slightly later. (x larger than len means that
295 // it's impossible to hit the desired frame, even if we dropped the ease
296 // altogether and just changed speeds instantly.) We also have sign invariance,
297 // so that these properties hold even if we are speeding up, not slowing
298 // down. Together, these two properties mean that we can cast a fairly
299 // wide net, trying various input and output frames and seeing which ones
300 // can be matched up with a minimal change to easing time. (This lets us
301 // e.g. end the ease close to the midpoint between two endpoint frames
302 // even if we don't know the frame rate, or deal fairly robustly with
303 // dropped input frames.) Many of these will give us the same answer,
304 // but that's fine, because the ease length is the only output.
305 int64_t best_length_out_pts = TIMEBASE * 10; // Infinite.
306 for (int output_frame_offset = -2; output_frame_offset <= 2; ++output_frame_offset) {
307 int64_t aim_length_out_pts = lrint((length_out_frames + output_frame_offset) * frame_length);
308 if (aim_length_out_pts < 0) {
312 for (int input_frame_offset = -2; input_frame_offset <= 2; ++input_frame_offset) {
313 if (input_frame_num + input_frame_offset < 0 ||
314 input_frame_num + input_frame_offset >= int(frames.size())) {
317 const int64_t in_pts = frames[input_frame_num + input_frame_offset].pts;
318 double shorten_by_out_pts = (2.0 * (in_pts - now.in_pts) / clip->speed - (master_speed_target + master_speed) * aim_length_out_pts) / (master_speed_target - master_speed);
319 int64_t length_out_pts = lrint(aim_length_out_pts - shorten_by_out_pts);
321 if (length_out_pts >= 0 &&
322 abs(length_out_pts - desired_length_out_pts) < abs(best_length_out_pts - desired_length_out_pts)) {
323 best_length_out_pts = length_out_pts;
328 // If we need more than two seconds of easing, we give up --
329 // this can happen if we're e.g. going from 101% to 100%.
330 // If so, it would be better to let other mechanisms, such as the switch
331 // to the next clip, deal with getting us back into sync.
332 if (best_length_out_pts > TIMEBASE * 2) {
333 return desired_length_out_pts;
335 return best_length_out_pts;
341 void Player::play_playlist_once()
343 vector<ClipWithID> clip_list;
345 steady_clock::time_point before_sleep = steady_clock::now();
348 // Wait until we're supposed to play something.
350 unique_lock<mutex> lock(queue_state_mu);
352 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
353 return should_quit || new_clip_ready;
359 new_clip_ready = false;
361 clip_list = move(queued_clip_list);
362 queued_clip_list.clear();
363 assert(!clip_list.empty());
364 assert(!splice_ready); // This corner case should have been handled in splice_play().
366 pause_status = this->pause_status;
370 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
371 int64_t slept_pts = duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
373 if (video_stream != nullptr) {
374 // Add silence for the time we're waiting.
375 video_stream->schedule_silence(steady_clock::now(), pts, slept_pts, QueueSpotHolder());
381 if (video_stream != nullptr) {
382 ++metric_refresh_frame;
383 string subtitle = "Futatabi " NAGERU_VERSION ";PAUSED;0.000;" + pause_status;
384 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder(),
390 should_skip_to_next = false; // To make sure we don't have a lingering click from before play.
391 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
392 TimelineTracker timeline(start_master_speed, pts);
393 timeline.new_clip(origin, &clip_list[0].clip, /*pts_offset=*/0);
394 for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
395 const Clip *clip = &clip_list[clip_idx].clip;
396 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
398 double next_clip_fade_time = -1.0;
399 if (next_clip != nullptr) {
400 double duration_this_clip = double(clip->pts_out - timeline.get_in_pts_origin()) / TIMEBASE / clip->speed;
401 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
402 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
405 int stream_idx = clip->stream_idx;
407 // Start playing exactly at a frame.
408 // TODO: Snap secondary (fade-to) clips in the same fashion
409 // so that we don't get jank here).
411 lock_guard<mutex> lock(frame_mu);
413 // Find the first frame such that frame.pts <= in_pts.
414 auto it = find_last_frame_before(frames[stream_idx], timeline.get_in_pts_origin());
415 if (it != frames[stream_idx].end()) {
416 timeline.snap_by(it->pts - timeline.get_in_pts_origin());
420 steady_clock::time_point next_frame_start;
421 for (int64_t frameno = 0; !should_quit; ++frameno) { // Ends when the clip ends.
422 TimelineTracker::Instant instant = timeline.advance_to_frame(frameno);
423 int64_t in_pts = instant.in_pts;
424 pts = instant.out_pts;
425 next_frame_start = instant.wallclock_time;
427 float new_master_speed = change_master_speed.exchange(0.0f / 0.0f);
428 if (!std::isnan(new_master_speed) && !timeline.in_master_speed(new_master_speed)) {
429 int64_t ease_length_out_pts = TIMEBASE / 5; // 200 ms.
430 int64_t recommended_pts_length = timeline.find_easing_length(new_master_speed, ease_length_out_pts, frames[clip->stream_idx], instant);
431 timeline.start_easing(new_master_speed, recommended_pts_length, instant);
434 if (should_skip_to_next.exchange(false)) { // Test and clear.
435 Clip *clip = &clip_list[clip_idx].clip; // Get a non-const pointer.
436 clip->pts_out = std::min<int64_t>(clip->pts_out, llrint(in_pts + clip->fade_time_seconds * clip->speed * TIMEBASE));
439 if (in_pts >= clip->pts_out) {
443 // Only play audio if we're within 0.1% of normal speed. We could do
444 // stretching or pitch shift later if it becomes needed.
445 const bool play_audio = timeline.playing_at_normal_speed();
448 lock_guard<mutex> lock(queue_state_mu);
450 if (next_clip == nullptr) {
451 do_splice(to_splice_clip_list, clip_idx, -1, &clip_list);
453 do_splice(to_splice_clip_list, clip_idx, clip_idx + 1, &clip_list);
455 to_splice_clip_list.clear();
456 splice_ready = false;
458 // Refresh the clip pointer, since the clip list may have been reallocated.
459 clip = &clip_list[clip_idx].clip;
461 // Recompute next_clip and any needed fade times, since the next clip may have changed
462 // (or we may have gone from no new clip to having one, or the other way).
463 next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
464 if (next_clip != nullptr) {
465 double duration_this_clip = double(clip->pts_out - timeline.get_in_pts_origin()) / TIMEBASE / clip->speed;
466 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
467 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
472 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
473 metric_player_ahead_seconds.count_event(-duration<double>(time_behind).count());
474 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
475 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
476 lrint(1e3 * duration<double>(time_behind).count()));
477 ++metric_dropped_unconditional_frame;
481 // pts not affected by the swapping below.
482 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
484 int primary_stream_idx = stream_idx;
485 FrameOnDisk secondary_frame;
486 int secondary_stream_idx = -1;
487 float fade_alpha = 0.0f;
488 double time_left_this_clip = double(clip->pts_out - in_pts) / TIMEBASE / clip->speed;
489 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
490 // We're in a fade to the next clip->
491 secondary_stream_idx = next_clip->stream_idx;
492 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip->speed);
493 in_pts_secondary_for_progress = in_pts_secondary;
494 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
496 // If more than half-way through the fade, interpolate the next clip
497 // instead of the current one, since it's more visible.
498 if (fade_alpha >= 0.5f) {
499 swap(primary_stream_idx, secondary_stream_idx);
500 swap(in_pts, in_pts_secondary);
501 fade_alpha = 1.0f - fade_alpha;
504 FrameOnDisk frame_lower, frame_upper;
505 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
508 secondary_frame = frame_lower;
510 secondary_stream_idx = -1;
514 // NOTE: None of this will take into account any snapping done below.
515 double clip_progress = calc_progress(*clip, in_pts_for_progress);
516 map<uint64_t, double> progress{ { clip_list[clip_idx].id, clip_progress } };
517 TimeRemaining time_remaining;
518 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
519 double next_clip_progress = calc_progress(*next_clip, in_pts_secondary_for_progress);
520 progress[clip_list[clip_idx + 1].id] = next_clip_progress;
521 time_remaining = compute_time_left(clip_list, clip_idx + 1, next_clip_progress);
523 time_remaining = compute_time_left(clip_list, clip_idx, clip_progress);
525 if (progress_callback != nullptr) {
526 progress_callback(progress, time_remaining);
529 FrameOnDisk frame_lower, frame_upper;
530 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
535 // Wait until we should, or (given buffering) can, output the frame.
537 unique_lock<mutex> lock(queue_state_mu);
538 if (video_stream == nullptr) {
539 // No queue, just wait until the right time and then show the frame.
540 new_clip_changed.wait_until(lock, next_frame_start, [this] {
541 return should_quit || new_clip_ready || override_stream_idx != -1;
547 // If the queue is full (which is really the state we'd like to be in),
548 // wait until there's room for one more frame (ie., one was output from
549 // VideoStream), or until or until there's a new clip we're supposed to play.
551 // In this case, we don't sleep until next_frame_start; the displaying is
552 // done by the queue.
553 new_clip_changed.wait(lock, [this] {
554 if (num_queued_frames < max_queued_frames) {
557 return should_quit || new_clip_ready || override_stream_idx != -1;
563 if (new_clip_ready) {
564 if (video_stream != nullptr) {
565 lock.unlock(); // Urg.
566 video_stream->clear_queue();
571 // Honor if we got an override request for the camera.
572 if (override_stream_idx != -1) {
573 stream_idx = override_stream_idx;
574 override_stream_idx = -1;
582 ss.imbue(locale("C"));
584 ss << "Futatabi " NAGERU_VERSION ";PLAYING;";
585 ss << fixed << (time_remaining.num_infinite * 86400.0 + time_remaining.t);
586 ss << ";" << format_duration(time_remaining) << " left";
590 // Snap to input frame: If we can do so with less than 1% jitter
591 // (ie., move less than 1% of an _output_ frame), do so.
592 // TODO: Snap secondary (fade-to) clips in the same fashion.
593 double pts_snap_tolerance = 0.01 * double(TIMEBASE) * clip->speed / global_flags.output_framerate;
594 bool snapped = false;
595 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
596 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
597 display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
598 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true,
599 subtitle, play_audio);
600 timeline.snap_by(snap_frame.pts - in_pts);
609 // If there's nothing to interpolate between, or if interpolation is turned off,
610 // or we're a preview, then just display the frame.
611 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
612 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
613 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false,
614 subtitle, play_audio);
618 // The snapping above makes us lock to the input framerate, even in the presence
619 // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
620 // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
621 // get a snap very rarely (in the given case, once every 24 output frames), and by
622 // that time, we'd have drifted out. We could have solved this by changing the overall
623 // speed ever so slightly, but it requires that we know the actual frame rate (which
624 // is difficult in the presence of jitter and missed frames), or at least do some kind
625 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
626 // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
627 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
628 // in-between frame. Of course, we will still need to interpolate, but we get a lot
629 // closer when we actually get close to an original frame. In other words: Snap more
630 // often, but snap less each time. Unless the input and output frame rates are completely
631 // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
632 // really never see in practice).
633 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
634 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
635 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
636 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
637 timeline.snap_by(lrint(subsnap_pts) - in_pts);
638 in_pts = lrint(subsnap_pts);
643 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
644 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
645 lrint(1e3 * duration<double>(time_behind).count()));
646 ++metric_dropped_interpolated_frame;
650 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
651 auto display_func = [this](shared_ptr<Frame> frame) {
652 if (destination != nullptr) {
653 destination->setFrame(frame);
656 if (secondary_stream_idx == -1) {
657 ++metric_interpolated_frame;
659 ++metric_interpolated_faded_frame;
661 video_stream->schedule_interpolated_frame(
662 next_frame_start, pts, display_func, QueueSpotHolder(this),
663 frame_lower, frame_upper, alpha,
664 secondary_frame, fade_alpha, subtitle, play_audio);
665 last_pts_played = in_pts; // Not really needed; only previews use last_pts_played.
673 // Start the next clip from the point where the fade went out.
674 if (next_clip != nullptr) {
675 timeline.new_clip(next_frame_start, next_clip, /*pts_start_offset=*/lrint(next_clip_fade_time * TIMEBASE * clip->speed));
679 if (done_callback != nullptr) {
684 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)
686 auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha] {
687 if (destination != nullptr) {
688 destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
691 if (video_stream == nullptr) {
694 if (secondary_stream_idx == -1) {
695 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
697 ++metric_original_snapped_frame;
699 ++metric_original_frame;
701 video_stream->schedule_original_frame(
702 frame_start, pts, display_func, QueueSpotHolder(this),
703 primary_frame, subtitle, play_audio);
705 assert(secondary_frame.pts != -1);
706 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
708 ++metric_faded_snapped_frame;
710 ++metric_faded_frame;
712 video_stream->schedule_faded_frame(frame_start, pts, display_func,
713 QueueSpotHolder(this), primary_frame,
714 secondary_frame, fade_alpha, subtitle);
717 last_pts_played = primary_frame.pts;
720 // Find the frame immediately before and after this point.
721 // If we have an exact match, return it immediately.
722 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
724 lock_guard<mutex> lock(frame_mu);
726 // Find the first frame such that frame.pts >= pts.
727 auto it = find_last_frame_before(frames[stream_idx], pts);
728 if (it == frames[stream_idx].end()) {
733 // If we have an exact match, return it immediately.
734 if (frame_upper->pts == pts) {
739 // Find the last frame such that in_pts <= frame.pts (if any).
740 if (it == frames[stream_idx].begin()) {
743 *frame_lower = *(it - 1);
745 assert(pts >= frame_lower->pts);
746 assert(pts <= frame_upper->pts);
750 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
751 : destination(destination), stream_output(stream_output)
753 player_thread = thread(&Player::thread_func, this, file_avctx);
755 if (stream_output == HTTPD_STREAM_OUTPUT) {
756 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_original_frame);
757 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_faded_frame);
758 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "snapped" } }, &metric_original_snapped_frame);
759 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "snapped" } }, &metric_faded_snapped_frame);
760 global_metrics.add("http_output_frames", { { "type", "interpolated" } }, &metric_interpolated_frame);
761 global_metrics.add("http_output_frames", { { "type", "interpolated_faded" } }, &metric_interpolated_faded_frame);
762 global_metrics.add("http_output_frames", { { "type", "refresh" } }, &metric_refresh_frame);
763 global_metrics.add("http_dropped_frames", { { "type", "interpolated" } }, &metric_dropped_interpolated_frame);
764 global_metrics.add("http_dropped_frames", { { "type", "unconditional" } }, &metric_dropped_unconditional_frame);
766 vector<double> quantiles{ 0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99 };
767 metric_player_ahead_seconds.init(quantiles, 60.0);
768 global_metrics.add("player_ahead_seconds", &metric_player_ahead_seconds);
775 new_clip_changed.notify_all();
776 player_thread.join();
778 if (video_stream != nullptr) {
779 video_stream->stop();
783 void Player::play(const vector<ClipWithID> &clips)
785 lock_guard<mutex> lock(queue_state_mu);
786 new_clip_ready = true;
787 queued_clip_list = clips;
788 splice_ready = false;
789 override_stream_idx = -1;
790 new_clip_changed.notify_all();
793 void Player::splice_play(const vector<ClipWithID> &clips)
795 lock_guard<mutex> lock(queue_state_mu);
796 if (new_clip_ready) {
797 queued_clip_list = clips;
798 assert(!splice_ready);
803 to_splice_clip_list = clips; // Overwrite any queued but not executed splice.
806 void Player::override_angle(unsigned stream_idx)
810 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
812 lock_guard<mutex> lock(queue_state_mu);
813 if (new_clip_ready) {
814 assert(queued_clip_list.size() == 1);
815 queued_clip_list[0].clip.stream_idx = stream_idx;
819 // If we are playing a clip, set override_stream_idx, and the player thread will
820 // pick it up and change its internal index.
822 override_stream_idx = stream_idx;
823 new_clip_changed.notify_all();
827 // OK, so we're standing still, presumably at the end of a clip.
828 // Look at the last frame played (if it exists), and show the closest
830 if (last_pts_played < 0) {
833 last_pts = last_pts_played;
836 lock_guard<mutex> lock(frame_mu);
837 auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
838 if (it == frames[stream_idx].end()) {
841 destination->setFrame(stream_idx, *it);
844 void Player::take_queue_spot()
846 lock_guard<mutex> lock(queue_state_mu);
850 void Player::release_queue_spot()
852 lock_guard<mutex> lock(queue_state_mu);
853 assert(num_queued_frames > 0);
855 new_clip_changed.notify_all();
858 TimeRemaining compute_time_left(const vector<ClipWithID> &clips, size_t currently_playing_idx, double progress_currently_playing)
860 // Look at the last clip and then start counting from there.
861 TimeRemaining remaining { 0, 0.0 };
862 double last_fade_time_seconds = 0.0;
863 for (size_t row = currently_playing_idx; row < clips.size(); ++row) {
864 const Clip &clip = clips[row].clip;
865 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
866 if (clip_length >= 86400.0 || clip.pts_out == -1) { // More than one day.
867 ++remaining.num_infinite;
869 if (row == currently_playing_idx) {
870 // A clip we're playing: Subtract the part we've already played.
871 remaining.t = clip_length * (1.0 - progress_currently_playing);
873 // A clip we haven't played yet: Subtract the part that's overlapping
874 // with a previous clip (due to fade).
875 remaining.t += max(clip_length - last_fade_time_seconds, 0.0);
878 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
883 string format_duration(TimeRemaining t)
885 int t_ms = lrint(t.t * 1e3);
887 int ms = t_ms % 1000;
894 if (t.num_infinite > 1 && t.t > 0.0) {
895 snprintf(buf, sizeof(buf), "%zu clips + %d:%02d.%03d", t.num_infinite, m, s, ms);
896 } else if (t.num_infinite > 1) {
897 snprintf(buf, sizeof(buf), "%zu clips", t.num_infinite);
898 } else if (t.num_infinite == 1 && t.t > 0.0) {
899 snprintf(buf, sizeof(buf), "%zu clip + %d:%02d.%03d", t.num_infinite, m, s, ms);
900 } else if (t.num_infinite == 1) {
901 snprintf(buf, sizeof(buf), "%zu clip", t.num_infinite);
903 snprintf(buf, sizeof(buf), "%d:%02d.%03d", m, s, ms);