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) {
53 if (done_callback != nullptr) {
61 double calc_progress(const Clip &clip, int64_t pts)
63 return double(pts - clip.pts_in) / (clip.pts_out - clip.pts_in);
68 void Player::play_playlist_once()
70 vector<ClipWithID> clip_list;
72 steady_clock::time_point before_sleep = steady_clock::now();
74 // Wait until we're supposed to play something.
76 unique_lock<mutex> lock(queue_state_mu);
78 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
79 return should_quit || new_clip_ready;
85 new_clip_ready = false;
87 clip_list = move(queued_clip_list);
88 queued_clip_list.clear();
89 assert(!clip_list.empty());
93 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
94 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
97 if (video_stream != nullptr) {
98 ++metric_refresh_frame;
99 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
104 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
105 int64_t in_pts_origin = clip_list[0].clip.pts_in;
106 for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
107 const Clip &clip = clip_list[clip_idx].clip;
108 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
109 int64_t out_pts_origin = pts;
111 double next_clip_fade_time = -1.0;
112 if (next_clip != nullptr) {
113 double duration_this_clip = double(clip.pts_out - in_pts_origin) / TIMEBASE / clip.speed;
114 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip.speed;
115 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip.fade_time_seconds);
118 int stream_idx = clip.stream_idx;
120 // Start playing exactly at a frame.
121 // TODO: Snap secondary (fade-to) clips in the same fashion
122 // so that we don't get jank here).
124 lock_guard<mutex> lock(frame_mu);
126 // Find the first frame such that frame.pts <= in_pts.
127 auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
128 if (it != frames[stream_idx].end()) {
129 in_pts_origin = it->pts;
133 steady_clock::time_point next_frame_start;
134 for (int frameno = 0; !should_quit; ++frameno) { // Ends when the clip ends.
135 double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
137 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
138 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
139 pts = lrint(out_pts);
141 if (in_pts >= clip.pts_out) {
145 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
146 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
147 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
148 lrint(1e3 * duration<double>(time_behind).count()));
149 ++metric_dropped_unconditional_frame;
153 // pts not affected by the swapping below.
154 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
156 int primary_stream_idx = stream_idx;
157 FrameOnDisk secondary_frame;
158 int secondary_stream_idx = -1;
159 float fade_alpha = 0.0f;
160 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
161 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
162 // We're in a fade to the next clip.
163 secondary_stream_idx = next_clip->stream_idx;
164 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
165 in_pts_secondary_for_progress = in_pts_secondary;
166 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
168 // If more than half-way through the fade, interpolate the next clip
169 // instead of the current one, since it's more visible.
170 if (fade_alpha >= 0.5f) {
171 swap(primary_stream_idx, secondary_stream_idx);
172 swap(in_pts, in_pts_secondary);
173 fade_alpha = 1.0f - fade_alpha;
176 FrameOnDisk frame_lower, frame_upper;
177 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
179 secondary_frame = frame_lower;
183 if (progress_callback != nullptr) {
184 // NOTE: None of this will take into account any snapping done below.
185 double clip_progress = calc_progress(clip, in_pts_for_progress);
186 map<uint64_t, double> progress{ { clip_list[clip_idx].id, clip_progress } };
187 double time_remaining;
188 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
189 double next_clip_progress = calc_progress(*next_clip, in_pts_secondary_for_progress);
190 progress[clip_list[clip_idx + 1].id] = next_clip_progress;
191 time_remaining = compute_time_left(clip_list, clip_idx + 1, next_clip_progress);
193 time_remaining = compute_time_left(clip_list, clip_idx, clip_progress);
195 progress_callback(progress, time_remaining);
198 FrameOnDisk frame_lower, frame_upper;
199 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
204 // Wait until we should, or (given buffering) can, output the frame.
206 unique_lock<mutex> lock(queue_state_mu);
207 if (video_stream == nullptr) {
208 // No queue, just wait until the right time and then show the frame.
209 new_clip_changed.wait_until(lock, next_frame_start, [this] {
210 return should_quit || new_clip_ready || override_stream_idx != -1;
216 // If the queue is full (which is really the state we'd like to be in),
217 // wait until there's room for one more frame (ie., one was output from
218 // VideoStream), or until or until there's a new clip we're supposed to play.
220 // In this case, we don't sleep until next_frame_start; the displaying is
221 // done by the queue.
222 new_clip_changed.wait(lock, [this] {
223 if (num_queued_frames < max_queued_frames) {
226 return should_quit || new_clip_ready || override_stream_idx != -1;
232 if (new_clip_ready) {
233 if (video_stream != nullptr) {
234 lock.unlock(); // Urg.
235 video_stream->clear_queue();
240 // Honor if we got an override request for the camera.
241 if (override_stream_idx != -1) {
242 stream_idx = override_stream_idx;
243 override_stream_idx = -1;
248 // If there's nothing to interpolate between, or if interpolation is turned off,
249 // or we're a preview, then just display the frame.
250 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
251 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
252 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false);
256 // Snap to input frame: If we can do so with less than 1% jitter
257 // (ie., move less than 1% of an _output_ frame), do so.
258 // TODO: Snap secondary (fade-to) clips in the same fashion.
259 double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
260 bool snapped = false;
261 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
262 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
263 display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
264 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true);
265 in_pts_origin += snap_frame.pts - in_pts;
274 // The snapping above makes us lock to the input framerate, even in the presence
275 // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
276 // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
277 // get a snap very rarely (in the given case, once every 24 output frames), and by
278 // that time, we'd have drifted out. We could have solved this by changing the overall
279 // speed ever so slightly, but it requires that we know the actual frame rate (which
280 // is difficult in the presence of jitter and missed frames), or at least do some kind
281 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
282 // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
283 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
284 // in-between frame. Of course, we will still need to interpolate, but we get a lot
285 // closer when we actually get close to an original frame. In other words: Snap more
286 // often, but snap less each time. Unless the input and output frame rates are completely
287 // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
288 // really never see in practice).
289 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
290 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
291 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
292 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
293 in_pts_origin += lrint(subsnap_pts) - in_pts;
294 in_pts = lrint(subsnap_pts);
299 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
300 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
301 lrint(1e3 * duration<double>(time_behind).count()));
302 ++metric_dropped_interpolated_frame;
306 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
307 auto display_func = [this](shared_ptr<Frame> frame) {
308 if (destination != nullptr) {
309 destination->setFrame(frame);
312 if (secondary_stream_idx == -1) {
313 ++metric_interpolated_frame;
315 ++metric_interpolated_faded_frame;
317 video_stream->schedule_interpolated_frame(
318 next_frame_start, pts, display_func, QueueSpotHolder(this),
319 frame_lower, frame_upper, alpha,
320 secondary_frame, fade_alpha);
321 last_pts_played = in_pts; // Not really needed; only previews use last_pts_played.
329 // Start the next clip from the point where the fade went out.
330 if (next_clip != nullptr) {
331 origin = next_frame_start;
332 in_pts_origin = next_clip->pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
337 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)
339 auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha] {
340 if (destination != nullptr) {
341 destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
344 if (video_stream == nullptr) {
347 if (secondary_stream_idx == -1) {
348 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
350 ++metric_original_snapped_frame;
352 ++metric_original_frame;
354 video_stream->schedule_original_frame(
355 frame_start, pts, display_func, QueueSpotHolder(this),
358 assert(secondary_frame.pts != -1);
359 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
361 ++metric_faded_snapped_frame;
363 ++metric_faded_frame;
365 video_stream->schedule_faded_frame(frame_start, pts, display_func,
366 QueueSpotHolder(this), primary_frame,
367 secondary_frame, fade_alpha);
370 last_pts_played = primary_frame.pts;
373 // Find the frame immediately before and after this point.
374 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
376 lock_guard<mutex> lock(frame_mu);
378 // Find the first frame such that frame.pts >= pts.
379 auto it = find_last_frame_before(frames[stream_idx], pts);
380 if (it == frames[stream_idx].end()) {
385 // Find the last frame such that in_pts <= frame.pts (if any).
386 if (it == frames[stream_idx].begin()) {
389 *frame_lower = *(it - 1);
391 assert(pts >= frame_lower->pts);
392 assert(pts <= frame_upper->pts);
396 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
397 : destination(destination), stream_output(stream_output)
399 player_thread = thread(&Player::thread_func, this, file_avctx);
401 if (stream_output == HTTPD_STREAM_OUTPUT) {
402 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_original_frame);
403 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_faded_frame);
404 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "snapped" } }, &metric_original_snapped_frame);
405 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "snapped" } }, &metric_faded_snapped_frame);
406 global_metrics.add("http_output_frames", { { "type", "interpolated" } }, &metric_interpolated_frame);
407 global_metrics.add("http_output_frames", { { "type", "interpolated_faded" } }, &metric_interpolated_faded_frame);
408 global_metrics.add("http_output_frames", { { "type", "refresh" } }, &metric_refresh_frame);
409 global_metrics.add("http_dropped_frames", { { "type", "interpolated" } }, &metric_dropped_interpolated_frame);
410 global_metrics.add("http_dropped_frames", { { "type", "unconditional" } }, &metric_dropped_unconditional_frame);
417 if (video_stream != nullptr) {
418 video_stream->stop();
420 new_clip_changed.notify_all();
421 player_thread.join();
424 void Player::play(const vector<ClipWithID> &clips)
426 lock_guard<mutex> lock(queue_state_mu);
427 new_clip_ready = true;
428 queued_clip_list = clips;
429 override_stream_idx = -1;
430 new_clip_changed.notify_all();
433 void Player::override_angle(unsigned stream_idx)
437 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
439 lock_guard<mutex> lock(queue_state_mu);
440 if (new_clip_ready) {
441 assert(queued_clip_list.size() == 1);
442 queued_clip_list[0].clip.stream_idx = stream_idx;
446 // If we are playing a clip, set override_stream_idx, and the player thread will
447 // pick it up and change its internal index.
449 override_stream_idx = stream_idx;
450 new_clip_changed.notify_all();
454 // OK, so we're standing still, presumably at the end of a clip.
455 // Look at the last frame played (if it exists), and show the closest
457 if (last_pts_played < 0) {
460 last_pts = last_pts_played;
463 lock_guard<mutex> lock(frame_mu);
464 auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
465 if (it == frames[stream_idx].end()) {
468 destination->setFrame(stream_idx, *it);
471 void Player::take_queue_spot()
473 lock_guard<mutex> lock(queue_state_mu);
477 void Player::release_queue_spot()
479 lock_guard<mutex> lock(queue_state_mu);
480 assert(num_queued_frames > 0);
482 new_clip_changed.notify_all();
485 double compute_time_left(const vector<ClipWithID> &clips, size_t currently_playing_idx, double progress_currently_playing)
487 // Look at the last clip and then start counting from there.
488 double remaining = 0.0;
489 double last_fade_time_seconds = 0.0;
490 for (size_t row = currently_playing_idx; row < clips.size(); ++row) {
491 const Clip &clip = clips[row].clip;
492 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
493 if (row == currently_playing_idx) {
494 // A clip we're playing: Subtract the part we've already played.
495 remaining = clip_length * (1.0 - progress_currently_playing);
497 // A clip we haven't played yet: Subtract the part that's overlapping
498 // with a previous clip (due to fade).
499 remaining += max(clip_length - last_fade_time_seconds, 0.0);
501 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);