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());
111 void Player::play_playlist_once()
113 vector<ClipWithID> clip_list;
115 steady_clock::time_point before_sleep = steady_clock::now();
117 float master_speed = 1.0f;
119 // Wait until we're supposed to play something.
121 unique_lock<mutex> lock(queue_state_mu);
123 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
124 return should_quit || new_clip_ready;
130 new_clip_ready = false;
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().
137 pause_status = this->pause_status;
141 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
142 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
145 if (video_stream != nullptr) {
146 ++metric_refresh_frame;
147 string subtitle = "Futatabi " NAGERU_VERSION ";PAUSED;0.000;" + pause_status;
148 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder(),
154 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
155 int64_t in_pts_origin = clip_list[0].clip.pts_in;
156 for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
157 const Clip *clip = &clip_list[clip_idx].clip;
158 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
159 int64_t out_pts_origin = pts;
161 double next_clip_fade_time = -1.0;
162 if (next_clip != nullptr) {
163 double duration_this_clip = double(clip->pts_out - in_pts_origin) / TIMEBASE / clip->speed;
164 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
165 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
168 int stream_idx = clip->stream_idx;
170 // Start playing exactly at a frame.
171 // TODO: Snap secondary (fade-to) clips in the same fashion
172 // so that we don't get jank here).
174 lock_guard<mutex> lock(frame_mu);
176 // Find the first frame such that frame.pts <= in_pts.
177 auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
178 if (it != frames[stream_idx].end()) {
179 in_pts_origin = it->pts;
183 steady_clock::time_point next_frame_start;
184 for (int frameno = 0; !should_quit; ++frameno) { // Ends when the clip ends.
185 double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
187 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
188 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip->speed * master_speed / global_flags.output_framerate);
189 pts = lrint(out_pts);
191 float new_master_speed = change_master_speed.exchange(0.0f / 0.0f);
192 if (!std::isnan(new_master_speed)) {
193 master_speed = new_master_speed;
194 in_pts_origin = in_pts - TIMEBASE * frameno * clip->speed * master_speed / global_flags.output_framerate;
195 out_pts_origin = out_pts - TIMEBASE * frameno / global_flags.output_framerate;
198 if (in_pts >= clip->pts_out) {
203 lock_guard<mutex> lock(queue_state_mu);
205 if (next_clip == nullptr) {
206 do_splice(to_splice_clip_list, clip_idx, -1, &clip_list);
208 do_splice(to_splice_clip_list, clip_idx, clip_idx + 1, &clip_list);
210 to_splice_clip_list.clear();
211 splice_ready = false;
213 // Refresh the clip pointer, since the clip list may have been reallocated.
214 clip = &clip_list[clip_idx].clip;
216 // Recompute next_clip and any needed fade times, since the next clip may have changed
217 // (or we may have gone from no new clip to having one, or the other way).
218 next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
219 if (next_clip != nullptr) {
220 double duration_this_clip = double(clip->pts_out - in_pts) / TIMEBASE / clip->speed;
221 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip->speed;
222 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip->fade_time_seconds);
227 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
228 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
229 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
230 lrint(1e3 * duration<double>(time_behind).count()));
231 ++metric_dropped_unconditional_frame;
235 // pts not affected by the swapping below.
236 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
238 int primary_stream_idx = stream_idx;
239 FrameOnDisk secondary_frame;
240 int secondary_stream_idx = -1;
241 float fade_alpha = 0.0f;
242 double time_left_this_clip = double(clip->pts_out - in_pts) / TIMEBASE / clip->speed;
243 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
244 // We're in a fade to the next clip->
245 secondary_stream_idx = next_clip->stream_idx;
246 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip->speed);
247 in_pts_secondary_for_progress = in_pts_secondary;
248 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
250 // If more than half-way through the fade, interpolate the next clip
251 // instead of the current one, since it's more visible.
252 if (fade_alpha >= 0.5f) {
253 swap(primary_stream_idx, secondary_stream_idx);
254 swap(in_pts, in_pts_secondary);
255 fade_alpha = 1.0f - fade_alpha;
258 FrameOnDisk frame_lower, frame_upper;
259 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
261 secondary_frame = frame_lower;
265 // NOTE: None of this will take into account any snapping done below.
266 double clip_progress = calc_progress(*clip, in_pts_for_progress);
267 map<uint64_t, double> progress{ { clip_list[clip_idx].id, clip_progress } };
268 double time_remaining;
269 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
270 double next_clip_progress = calc_progress(*next_clip, in_pts_secondary_for_progress);
271 progress[clip_list[clip_idx + 1].id] = next_clip_progress;
272 time_remaining = compute_time_left(clip_list, clip_idx + 1, next_clip_progress);
274 time_remaining = compute_time_left(clip_list, clip_idx, clip_progress);
276 if (progress_callback != nullptr) {
277 progress_callback(progress, time_remaining);
280 FrameOnDisk frame_lower, frame_upper;
281 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
286 // Wait until we should, or (given buffering) can, output the frame.
288 unique_lock<mutex> lock(queue_state_mu);
289 if (video_stream == nullptr) {
290 // No queue, just wait until the right time and then show the frame.
291 new_clip_changed.wait_until(lock, next_frame_start, [this] {
292 return should_quit || new_clip_ready || override_stream_idx != -1;
298 // If the queue is full (which is really the state we'd like to be in),
299 // wait until there's room for one more frame (ie., one was output from
300 // VideoStream), or until or until there's a new clip we're supposed to play.
302 // In this case, we don't sleep until next_frame_start; the displaying is
303 // done by the queue.
304 new_clip_changed.wait(lock, [this] {
305 if (num_queued_frames < max_queued_frames) {
308 return should_quit || new_clip_ready || override_stream_idx != -1;
314 if (new_clip_ready) {
315 if (video_stream != nullptr) {
316 lock.unlock(); // Urg.
317 video_stream->clear_queue();
322 // Honor if we got an override request for the camera.
323 if (override_stream_idx != -1) {
324 stream_idx = override_stream_idx;
325 override_stream_idx = -1;
333 ss.imbue(locale("C"));
335 ss << "Futatabi " NAGERU_VERSION ";PLAYING;";
336 ss << fixed << time_remaining;
337 ss << ";" << format_duration(time_remaining) << " left";
341 // If there's nothing to interpolate between, or if interpolation is turned off,
342 // or we're a preview, then just display the frame.
343 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
344 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
345 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false,
350 // Snap to input frame: If we can do so with less than 1% jitter
351 // (ie., move less than 1% of an _output_ frame), do so.
352 // TODO: Snap secondary (fade-to) clips in the same fashion.
353 double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
354 bool snapped = false;
355 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
356 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
357 display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
358 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true,
360 in_pts_origin += snap_frame.pts - in_pts;
369 // The snapping above makes us lock to the input framerate, even in the presence
370 // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
371 // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
372 // get a snap very rarely (in the given case, once every 24 output frames), and by
373 // that time, we'd have drifted out. We could have solved this by changing the overall
374 // speed ever so slightly, but it requires that we know the actual frame rate (which
375 // is difficult in the presence of jitter and missed frames), or at least do some kind
376 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
377 // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
378 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
379 // in-between frame. Of course, we will still need to interpolate, but we get a lot
380 // closer when we actually get close to an original frame. In other words: Snap more
381 // often, but snap less each time. Unless the input and output frame rates are completely
382 // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
383 // really never see in practice).
384 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
385 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
386 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
387 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
388 in_pts_origin += lrint(subsnap_pts) - in_pts;
389 in_pts = lrint(subsnap_pts);
394 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
395 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
396 lrint(1e3 * duration<double>(time_behind).count()));
397 ++metric_dropped_interpolated_frame;
401 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
402 auto display_func = [this](shared_ptr<Frame> frame) {
403 if (destination != nullptr) {
404 destination->setFrame(frame);
407 if (secondary_stream_idx == -1) {
408 ++metric_interpolated_frame;
410 ++metric_interpolated_faded_frame;
412 video_stream->schedule_interpolated_frame(
413 next_frame_start, pts, display_func, QueueSpotHolder(this),
414 frame_lower, frame_upper, alpha,
415 secondary_frame, fade_alpha, subtitle);
416 last_pts_played = in_pts; // Not really needed; only previews use last_pts_played.
424 // Start the next clip from the point where the fade went out.
425 if (next_clip != nullptr) {
426 origin = next_frame_start;
427 in_pts_origin = next_clip->pts_in + lrint(next_clip_fade_time * TIMEBASE * clip->speed);
431 if (done_callback != nullptr) {
436 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)
438 auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha] {
439 if (destination != nullptr) {
440 destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
443 if (video_stream == nullptr) {
446 if (secondary_stream_idx == -1) {
447 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
449 ++metric_original_snapped_frame;
451 ++metric_original_frame;
453 video_stream->schedule_original_frame(
454 frame_start, pts, display_func, QueueSpotHolder(this),
455 primary_frame, subtitle);
457 assert(secondary_frame.pts != -1);
458 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
460 ++metric_faded_snapped_frame;
462 ++metric_faded_frame;
464 video_stream->schedule_faded_frame(frame_start, pts, display_func,
465 QueueSpotHolder(this), primary_frame,
466 secondary_frame, fade_alpha, subtitle);
469 last_pts_played = primary_frame.pts;
472 // Find the frame immediately before and after this point.
473 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
475 lock_guard<mutex> lock(frame_mu);
477 // Find the first frame such that frame.pts >= pts.
478 auto it = find_last_frame_before(frames[stream_idx], pts);
479 if (it == frames[stream_idx].end()) {
484 // Find the last frame such that in_pts <= frame.pts (if any).
485 if (it == frames[stream_idx].begin()) {
488 *frame_lower = *(it - 1);
490 assert(pts >= frame_lower->pts);
491 assert(pts <= frame_upper->pts);
495 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
496 : destination(destination), stream_output(stream_output)
498 player_thread = thread(&Player::thread_func, this, file_avctx);
500 if (stream_output == HTTPD_STREAM_OUTPUT) {
501 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_original_frame);
502 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_faded_frame);
503 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "snapped" } }, &metric_original_snapped_frame);
504 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "snapped" } }, &metric_faded_snapped_frame);
505 global_metrics.add("http_output_frames", { { "type", "interpolated" } }, &metric_interpolated_frame);
506 global_metrics.add("http_output_frames", { { "type", "interpolated_faded" } }, &metric_interpolated_faded_frame);
507 global_metrics.add("http_output_frames", { { "type", "refresh" } }, &metric_refresh_frame);
508 global_metrics.add("http_dropped_frames", { { "type", "interpolated" } }, &metric_dropped_interpolated_frame);
509 global_metrics.add("http_dropped_frames", { { "type", "unconditional" } }, &metric_dropped_unconditional_frame);
516 new_clip_changed.notify_all();
517 player_thread.join();
519 if (video_stream != nullptr) {
520 video_stream->stop();
524 void Player::play(const vector<ClipWithID> &clips)
526 lock_guard<mutex> lock(queue_state_mu);
527 new_clip_ready = true;
528 queued_clip_list = clips;
529 splice_ready = false;
530 override_stream_idx = -1;
531 new_clip_changed.notify_all();
534 void Player::splice_play(const vector<ClipWithID> &clips)
536 lock_guard<mutex> lock(queue_state_mu);
537 if (new_clip_ready) {
538 queued_clip_list = clips;
539 assert(!splice_ready);
544 to_splice_clip_list = clips; // Overwrite any queued but not executed splice.
547 void Player::override_angle(unsigned stream_idx)
551 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
553 lock_guard<mutex> lock(queue_state_mu);
554 if (new_clip_ready) {
555 assert(queued_clip_list.size() == 1);
556 queued_clip_list[0].clip.stream_idx = stream_idx;
560 // If we are playing a clip, set override_stream_idx, and the player thread will
561 // pick it up and change its internal index.
563 override_stream_idx = stream_idx;
564 new_clip_changed.notify_all();
568 // OK, so we're standing still, presumably at the end of a clip.
569 // Look at the last frame played (if it exists), and show the closest
571 if (last_pts_played < 0) {
574 last_pts = last_pts_played;
577 lock_guard<mutex> lock(frame_mu);
578 auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
579 if (it == frames[stream_idx].end()) {
582 destination->setFrame(stream_idx, *it);
585 void Player::take_queue_spot()
587 lock_guard<mutex> lock(queue_state_mu);
591 void Player::release_queue_spot()
593 lock_guard<mutex> lock(queue_state_mu);
594 assert(num_queued_frames > 0);
596 new_clip_changed.notify_all();
599 double compute_time_left(const vector<ClipWithID> &clips, size_t currently_playing_idx, double progress_currently_playing)
601 // Look at the last clip and then start counting from there.
602 double remaining = 0.0;
603 double last_fade_time_seconds = 0.0;
604 for (size_t row = currently_playing_idx; row < clips.size(); ++row) {
605 const Clip &clip = clips[row].clip;
606 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
607 if (row == currently_playing_idx) {
608 // A clip we're playing: Subtract the part we've already played.
609 remaining = clip_length * (1.0 - progress_currently_playing);
611 // A clip we haven't played yet: Subtract the part that's overlapping
612 // with a previous clip (due to fade).
613 remaining += max(clip_length - last_fade_time_seconds, 0.0);
615 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
620 string format_duration(double t)
622 int t_ms = lrint(t * 1e3);
624 int ms = t_ms % 1000;
631 snprintf(buf, sizeof(buf), "%d:%02d.%03d", m, s, ms);