4 #include "shared/context.h"
6 #include "shared/ffmpeg_raii.h"
8 #include "frame_on_disk.h"
9 #include "shared/httpd.h"
10 #include "jpeg_frame_view.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(Player::StreamOutput stream_output, 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();
53 size_t next_clip_idx = size_t(-1);
54 bool got_next_clip = false;
55 double next_clip_fade_time = -1.0;
57 while (!should_quit) {
60 steady_clock::time_point before_sleep = steady_clock::now();
62 // Wait until we're supposed to play something.
64 unique_lock<mutex> lock(queue_state_mu);
65 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
66 return should_quit || (new_clip_ready && current_clip.pts_in != -1);
71 new_clip_ready = false;
75 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
76 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
79 if (video_stream != nullptr) {
80 ++metric_refresh_frame;
81 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
90 lock_guard<mutex> lock(mu);
92 clip_idx = current_clip_idx;
93 stream_idx = current_stream_idx;
95 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
96 int64_t in_pts_origin = clip.pts_in;
98 int64_t out_pts_origin = pts;
100 // Start playing exactly at a frame.
101 // TODO: Snap secondary (fade-to) clips in the same fashion
102 // so that we don't get jank here).
104 lock_guard<mutex> lock(frame_mu);
106 // Find the first frame such that frame.pts <= in_pts.
107 auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
108 if (it != frames[stream_idx].end()) {
109 in_pts_origin = it->pts;
113 int64_t in_pts_start_next_clip = -1;
114 steady_clock::time_point next_frame_start;
115 for (int frameno = 0; !should_quit; ++frameno) { // Ends when the clip ends.
116 double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
118 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
119 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
120 pts = lrint(out_pts);
122 if (in_pts >= clip.pts_out) {
126 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
127 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
128 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
129 lrint(1e3 * duration<double>(time_behind).count()));
130 ++metric_dropped_unconditional_frame;
134 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
135 if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
136 // Find the next clip so that we can begin a fade.
137 tie(next_clip, next_clip_idx) = next_clip_callback();
138 if (next_clip.pts_in != -1) {
139 got_next_clip = true;
141 double duration_next_clip = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / clip.speed;
142 next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
143 in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
147 // pts not affected by the swapping below.
148 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
150 int primary_stream_idx = stream_idx;
151 FrameOnDisk secondary_frame;
152 int secondary_stream_idx = -1;
153 float fade_alpha = 0.0f;
154 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
155 secondary_stream_idx = next_clip.stream_idx;
156 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
157 in_pts_secondary_for_progress = in_pts_secondary;
158 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
160 // If more than half-way through the fade, interpolate the next clip
161 // instead of the current one, since it's more visible.
162 if (fade_alpha >= 0.5f) {
163 swap(primary_stream_idx, secondary_stream_idx);
164 swap(in_pts, in_pts_secondary);
165 fade_alpha = 1.0f - fade_alpha;
168 FrameOnDisk frame_lower, frame_upper;
169 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
171 secondary_frame = frame_lower;
175 if (progress_callback != nullptr) {
176 // NOTE: None of this will take into account any snapping done below.
177 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / clip.speed;
178 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
179 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
181 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
182 double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / next_clip.speed;
183 double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / next_clip.speed;
184 progress[next_clip_idx] = played_next_clip / total_next_length;
186 progress_callback(progress);
189 FrameOnDisk frame_lower, frame_upper;
190 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
196 unique_lock<mutex> lock(queue_state_mu);
197 if (video_stream == nullptr) {
198 // No queue, just wait until the right time and then show the frame.
199 new_clip_changed.wait_until(lock, next_frame_start, [this]{
200 return should_quit || new_clip_ready || override_stream_idx != -1;
206 // If the queue is full (which is really the state we'd like to be in),
207 // wait until there's room for one more frame (ie., one was output from
208 // VideoStream), or until or until there's a new clip we're supposed to play.
210 // In this case, we don't sleep until next_frame_start; the displaying is
211 // done by the queue.
212 new_clip_changed.wait(lock, [this]{
213 if (num_queued_frames < max_queued_frames) {
216 return should_quit || new_clip_ready || override_stream_idx != -1;
222 if (new_clip_ready) {
223 if (video_stream != nullptr) {
224 lock.unlock(); // Urg.
225 video_stream->clear_queue();
228 got_next_clip = false;
231 if (override_stream_idx != -1) {
232 stream_idx = override_stream_idx;
233 override_stream_idx = -1;
238 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
239 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
240 if (destination != nullptr) {
241 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
244 if (video_stream == nullptr) {
247 if (secondary_stream_idx == -1) {
248 ++metric_original_frame;
249 video_stream->schedule_original_frame(
250 next_frame_start, pts, display_func, QueueSpotHolder(this),
253 assert(secondary_frame.pts != -1);
254 ++metric_faded_frame;
255 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
256 QueueSpotHolder(this), frame_lower,
257 secondary_frame, fade_alpha);
263 // Snap to input frame: If we can do so with less than 1% jitter
264 // (ie., move less than 1% of an _output_ frame), do so.
265 // TODO: Snap secondary (fade-to) clips in the same fashion.
266 double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
267 bool snapped = false;
268 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
269 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
270 auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
271 if (destination != nullptr) {
272 destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
275 if (video_stream == nullptr) {
278 if (secondary_stream_idx == -1) {
279 ++metric_original_snapped_frame;
280 video_stream->schedule_original_frame(
281 next_frame_start, pts, display_func,
282 QueueSpotHolder(this), snap_frame);
284 assert(secondary_frame.pts != -1);
285 ++metric_faded_snapped_frame;
286 video_stream->schedule_faded_frame(
287 next_frame_start, pts, display_func, QueueSpotHolder(this),
288 snap_frame, secondary_frame, fade_alpha);
291 in_pts_origin += snap_frame.pts - in_pts;
300 // The snapping above makes us lock to the input framerate, even in the presence
301 // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
302 // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
303 // get a snap very rarely (in the given case, once every 24 output frames), and by
304 // that time, we'd have drifted out. We could have solved this by changing the overall
305 // speed ever so slightly, but it requires that we know the actual frame rate (which
306 // is difficult in the presence of jitter and missed frames), or at least do some kind
307 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
308 // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
309 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
310 // in-between frame. Of course, we will still need to interpolate, but we get a lot
311 // closer when we actually get close to an original frame. In other words: Snap more
312 // often, but snap less each time. Unless the input and output frame rates are completely
313 // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
314 // really never see in practice).
315 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
316 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
317 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
318 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
319 in_pts_origin += lrint(subsnap_pts) - in_pts;
320 in_pts = lrint(subsnap_pts);
325 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
326 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
327 lrint(1e3 * duration<double>(time_behind).count()));
328 ++metric_dropped_interpolated_frame;
332 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
334 if (video_stream == nullptr) {
335 // Previews don't do any interpolation.
336 assert(secondary_stream_idx == -1);
337 if (destination != nullptr) {
338 destination->setFrame(primary_stream_idx, frame_lower);
341 auto display_func = [this](shared_ptr<Frame> frame) {
342 if (destination != nullptr) {
343 destination->setFrame(frame);
346 if (secondary_stream_idx == -1) {
347 ++metric_interpolated_frame;
349 ++metric_interpolated_faded_frame;
351 video_stream->schedule_interpolated_frame(
352 next_frame_start, pts, display_func, QueueSpotHolder(this),
353 frame_lower, frame_upper, alpha,
354 secondary_frame, fade_alpha);
364 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
365 if (!got_next_clip && next_clip_callback != nullptr) {
366 tie(next_clip, next_clip_idx) = next_clip_callback();
367 if (next_clip.pts_in != -1) {
368 got_next_clip = true;
369 in_pts_start_next_clip = next_clip.pts_in;
373 // Switch to next clip if we got it.
376 clip_idx = next_clip_idx;
377 stream_idx = next_clip.stream_idx; // Override is used for previews only, and next_clip is used for live ony.
378 if (done_callback != nullptr) {
381 got_next_clip = false;
383 // Start the next clip from the point where the fade went out.
384 origin = next_frame_start;
385 in_pts_origin = in_pts_start_next_clip;
390 unique_lock<mutex> lock(queue_state_mu);
393 if (done_callback != nullptr) {
399 // Find the frame immediately before and after this point.
400 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
402 lock_guard<mutex> lock(frame_mu);
404 // Find the first frame such that frame.pts >= pts.
405 auto it = find_last_frame_before(frames[stream_idx], pts);
406 if (it == frames[stream_idx].end()) {
411 // Find the last frame such that in_pts <= frame.pts (if any).
412 if (it == frames[stream_idx].begin()) {
415 *frame_lower = *(it - 1);
417 assert(pts >= frame_lower->pts);
418 assert(pts <= frame_upper->pts);
422 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
423 : destination(destination)
425 player_thread = thread(&Player::thread_func, this, stream_output, file_avctx);
427 if (stream_output == HTTPD_STREAM_OUTPUT) {
428 global_metrics.add("http_output_frames", {{ "type", "original" }, { "reason", "edge_frame_or_no_interpolation" }}, &metric_original_frame);
429 global_metrics.add("http_output_frames", {{ "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" }}, &metric_faded_frame);
430 global_metrics.add("http_output_frames", {{ "type", "original" }, { "reason", "snapped" }}, &metric_original_snapped_frame);
431 global_metrics.add("http_output_frames", {{ "type", "faded" }, { "reason", "snapped" }}, &metric_faded_snapped_frame);
432 global_metrics.add("http_output_frames", {{ "type", "interpolated" }}, &metric_interpolated_frame);
433 global_metrics.add("http_output_frames", {{ "type", "interpolated_faded" }}, &metric_interpolated_faded_frame);
434 global_metrics.add("http_output_frames", {{ "type", "refresh" }}, &metric_refresh_frame);
435 global_metrics.add("http_dropped_frames", {{ "type", "interpolated" }}, &metric_dropped_interpolated_frame);
436 global_metrics.add("http_dropped_frames", {{ "type", "unconditional" }}, &metric_dropped_unconditional_frame);
443 if (video_stream != nullptr) {
444 video_stream->stop();
446 new_clip_changed.notify_all();
447 player_thread.join();
450 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
453 lock_guard<mutex> lock(mu);
455 current_stream_idx = stream_idx;
456 current_clip_idx = clip_idx;
460 lock_guard<mutex> lock(queue_state_mu);
461 new_clip_ready = true;
462 override_stream_idx = -1;
463 new_clip_changed.notify_all();
467 void Player::override_angle(unsigned stream_idx)
469 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
471 unique_lock<mutex> lock(queue_state_mu);
472 if (new_clip_ready) {
473 lock_guard<mutex> lock2(mu);
474 current_stream_idx = stream_idx;
479 // If we are playing a clip, set override_stream_idx, and the player thread will
480 // pick it up and change its internal index.
482 unique_lock<mutex> lock(queue_state_mu);
484 override_stream_idx = stream_idx;
485 new_clip_changed.notify_all();
489 // OK, so we're standing still, presumably at the end of a clip.
490 // Look at the current pts_out (if it exists), and show the closest
494 lock_guard<mutex> lock(mu);
495 if (current_clip.pts_out < 0) {
498 pts_out = current_clip.pts_out;
501 lock_guard<mutex> lock(frame_mu);
502 auto it = find_first_frame_at_or_after(frames[stream_idx], pts_out);
503 if (it == frames[stream_idx].end()) {
506 destination->setFrame(stream_idx, *it);
509 void Player::take_queue_spot()
511 unique_lock<mutex> lock(queue_state_mu);
515 void Player::release_queue_spot()
517 unique_lock<mutex> lock(queue_state_mu);
518 assert(num_queued_frames > 0);
520 new_clip_changed.notify_all();
523 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
525 // Look at the last clip and then start counting from there.
526 assert(!progress.empty());
527 auto last_it = progress.end();
529 double remaining = 0.0;
530 double last_fade_time_seconds = 0.0;
531 for (size_t row = last_it->first; row < clips.size(); ++row) {
532 const Clip &clip = clips[row];
533 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
534 if (row == last_it->first) {
535 // A clip we're playing: Subtract the part we've already played.
536 remaining = clip_length * (1.0 - last_it->second);
538 // A clip we haven't played yet: Subtract the part that's overlapping
539 // with a previous clip (due to fade).
540 remaining += max(clip_length - last_fade_time_seconds, 0.0);
542 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);