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(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);
65 void Player::play_playlist_once()
67 vector<Clip> clip_list;
69 steady_clock::time_point before_sleep = steady_clock::now();
71 // Wait until we're supposed to play something.
73 unique_lock<mutex> lock(queue_state_mu);
75 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
76 return should_quit || new_clip_ready;
82 new_clip_ready = false;
84 clip_list = move(queued_clip_list);
85 queued_clip_list.clear();
86 assert(!clip_list.empty());
90 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
91 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
94 if (video_stream != nullptr) {
95 ++metric_refresh_frame;
96 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
101 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
102 int64_t in_pts_origin = clip_list[0].pts_in;
103 for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
104 const Clip &clip = clip_list[clip_idx];
105 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1] : nullptr;
106 int64_t out_pts_origin = pts;
108 double next_clip_fade_time = -1.0;
109 if (next_clip != nullptr) {
110 double duration_this_clip = double(clip.pts_out - in_pts_origin) / TIMEBASE / clip.speed;
111 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip.speed;
112 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip.fade_time_seconds);
115 int stream_idx = clip.stream_idx;
117 // Start playing exactly at a frame.
118 // TODO: Snap secondary (fade-to) clips in the same fashion
119 // so that we don't get jank here).
121 lock_guard<mutex> lock(frame_mu);
123 // Find the first frame such that frame.pts <= in_pts.
124 auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
125 if (it != frames[stream_idx].end()) {
126 in_pts_origin = it->pts;
130 steady_clock::time_point next_frame_start;
131 for (int frameno = 0; !should_quit; ++frameno) { // Ends when the clip ends.
132 double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
134 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
135 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
136 pts = lrint(out_pts);
138 if (in_pts >= clip.pts_out) {
142 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
143 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
144 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
145 lrint(1e3 * duration<double>(time_behind).count()));
146 ++metric_dropped_unconditional_frame;
151 // pts not affected by the swapping below.
152 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
154 int primary_stream_idx = stream_idx;
155 FrameOnDisk secondary_frame;
156 int secondary_stream_idx = -1;
157 float fade_alpha = 0.0f;
158 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
159 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
160 // We're in a fade to the next clip.
161 secondary_stream_idx = next_clip->stream_idx;
162 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
163 in_pts_secondary_for_progress = in_pts_secondary;
164 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
166 // If more than half-way through the fade, interpolate the next clip
167 // instead of the current one, since it's more visible.
168 if (fade_alpha >= 0.5f) {
169 swap(primary_stream_idx, secondary_stream_idx);
170 swap(in_pts, in_pts_secondary);
171 fade_alpha = 1.0f - fade_alpha;
174 FrameOnDisk frame_lower, frame_upper;
175 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
177 secondary_frame = frame_lower;
181 if (progress_callback != nullptr) {
182 // NOTE: None of this will take into account any snapping done below.
183 map<size_t, double> progress{{ clip_idx, calc_progress(clip, in_pts_for_progress) }};
184 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
185 progress[clip_idx + 1] = calc_progress(*next_clip, in_pts_secondary_for_progress);
187 progress_callback(progress);
190 FrameOnDisk frame_lower, frame_upper;
191 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
196 // Wait until we should, or (given buffering) can, output the frame.
198 unique_lock<mutex> lock(queue_state_mu);
199 if (video_stream == nullptr) {
200 // No queue, just wait until the right time and then show the frame.
201 new_clip_changed.wait_until(lock, next_frame_start, [this]{
202 return should_quit || new_clip_ready || override_stream_idx != -1;
208 // If the queue is full (which is really the state we'd like to be in),
209 // wait until there's room for one more frame (ie., one was output from
210 // VideoStream), or until or until there's a new clip we're supposed to play.
212 // In this case, we don't sleep until next_frame_start; the displaying is
213 // done by the queue.
214 new_clip_changed.wait(lock, [this]{
215 if (num_queued_frames < max_queued_frames) {
218 return should_quit || new_clip_ready || override_stream_idx != -1;
224 if (new_clip_ready) {
225 if (video_stream != nullptr) {
226 lock.unlock(); // Urg.
227 video_stream->clear_queue();
232 // Honor if we got an override request for the camera.
233 if (override_stream_idx != -1) {
234 stream_idx = override_stream_idx;
235 override_stream_idx = -1;
240 // If there's nothing to interpolate between, or if interpolation is turned off,
241 // or we're a preview, then just display the frame.
242 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
243 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
244 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false);
248 // Snap to input frame: If we can do so with less than 1% jitter
249 // (ie., move less than 1% of an _output_ frame), do so.
250 // TODO: Snap secondary (fade-to) clips in the same fashion.
251 double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
252 bool snapped = false;
253 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
254 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
255 display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
256 secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true);
257 in_pts_origin += snap_frame.pts - in_pts;
266 // The snapping above makes us lock to the input framerate, even in the presence
267 // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
268 // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
269 // get a snap very rarely (in the given case, once every 24 output frames), and by
270 // that time, we'd have drifted out. We could have solved this by changing the overall
271 // speed ever so slightly, but it requires that we know the actual frame rate (which
272 // is difficult in the presence of jitter and missed frames), or at least do some kind
273 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
274 // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
275 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
276 // in-between frame. Of course, we will still need to interpolate, but we get a lot
277 // closer when we actually get close to an original frame. In other words: Snap more
278 // often, but snap less each time. Unless the input and output frame rates are completely
279 // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
280 // really never see in practice).
281 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
282 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
283 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
284 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
285 in_pts_origin += lrint(subsnap_pts) - in_pts;
286 in_pts = lrint(subsnap_pts);
291 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
292 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
293 lrint(1e3 * duration<double>(time_behind).count()));
294 ++metric_dropped_interpolated_frame;
298 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
299 auto display_func = [this](shared_ptr<Frame> frame) {
300 if (destination != nullptr) {
301 destination->setFrame(frame);
304 if (secondary_stream_idx == -1) {
305 ++metric_interpolated_frame;
307 ++metric_interpolated_faded_frame;
309 video_stream->schedule_interpolated_frame(
310 next_frame_start, pts, display_func, QueueSpotHolder(this),
311 frame_lower, frame_upper, alpha,
312 secondary_frame, fade_alpha);
313 last_pts_played = in_pts; // Not really needed; only previews use last_pts_played.
320 if (done_callback != nullptr) {
324 // Start the next clip from the point where the fade went out.
325 if (next_clip != nullptr) {
326 origin = next_frame_start;
327 in_pts_origin = next_clip->pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
331 if (done_callback != nullptr) {
336 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)
338 auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha]{
339 if (destination != nullptr) {
340 destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
343 if (video_stream == nullptr) {
346 if (secondary_stream_idx == -1) {
347 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
349 ++metric_original_snapped_frame;
351 ++metric_original_frame;
353 video_stream->schedule_original_frame(
354 frame_start, pts, display_func, QueueSpotHolder(this),
357 assert(secondary_frame.pts != -1);
358 // NOTE: We could be increasing unused metrics for previews, but that's harmless.
360 ++metric_faded_snapped_frame;
362 ++metric_faded_frame;
364 video_stream->schedule_faded_frame(frame_start, pts, display_func,
365 QueueSpotHolder(this), primary_frame,
366 secondary_frame, fade_alpha);
369 last_pts_played = primary_frame.pts;
372 // Find the frame immediately before and after this point.
373 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
375 lock_guard<mutex> lock(frame_mu);
377 // Find the first frame such that frame.pts >= pts.
378 auto it = find_last_frame_before(frames[stream_idx], pts);
379 if (it == frames[stream_idx].end()) {
384 // Find the last frame such that in_pts <= frame.pts (if any).
385 if (it == frames[stream_idx].begin()) {
388 *frame_lower = *(it - 1);
390 assert(pts >= frame_lower->pts);
391 assert(pts <= frame_upper->pts);
395 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
396 : destination(destination), stream_output(stream_output)
398 player_thread = thread(&Player::thread_func, this, file_avctx);
400 if (stream_output == HTTPD_STREAM_OUTPUT) {
401 global_metrics.add("http_output_frames", {{ "type", "original" }, { "reason", "edge_frame_or_no_interpolation" }}, &metric_original_frame);
402 global_metrics.add("http_output_frames", {{ "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" }}, &metric_faded_frame);
403 global_metrics.add("http_output_frames", {{ "type", "original" }, { "reason", "snapped" }}, &metric_original_snapped_frame);
404 global_metrics.add("http_output_frames", {{ "type", "faded" }, { "reason", "snapped" }}, &metric_faded_snapped_frame);
405 global_metrics.add("http_output_frames", {{ "type", "interpolated" }}, &metric_interpolated_frame);
406 global_metrics.add("http_output_frames", {{ "type", "interpolated_faded" }}, &metric_interpolated_faded_frame);
407 global_metrics.add("http_output_frames", {{ "type", "refresh" }}, &metric_refresh_frame);
408 global_metrics.add("http_dropped_frames", {{ "type", "interpolated" }}, &metric_dropped_interpolated_frame);
409 global_metrics.add("http_dropped_frames", {{ "type", "unconditional" }}, &metric_dropped_unconditional_frame);
416 if (video_stream != nullptr) {
417 video_stream->stop();
419 new_clip_changed.notify_all();
420 player_thread.join();
423 void Player::play(const vector<Clip> &clips)
425 lock_guard<mutex> lock(queue_state_mu);
426 new_clip_ready = true;
427 queued_clip_list = clips;
428 override_stream_idx = -1;
429 new_clip_changed.notify_all();
432 void Player::override_angle(unsigned stream_idx)
436 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
438 lock_guard<mutex> lock(queue_state_mu);
439 if (new_clip_ready) {
440 assert(queued_clip_list.size() == 1);
441 queued_clip_list[0].stream_idx = stream_idx;
445 // If we are playing a clip, set override_stream_idx, and the player thread will
446 // pick it up and change its internal index.
448 override_stream_idx = stream_idx;
449 new_clip_changed.notify_all();
453 // OK, so we're standing still, presumably at the end of a clip.
454 // Look at the last frame played (if it exists), and show the closest
456 if (last_pts_played < 0) {
459 last_pts = last_pts_played;
462 lock_guard<mutex> lock(frame_mu);
463 auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
464 if (it == frames[stream_idx].end()) {
467 destination->setFrame(stream_idx, *it);
470 void Player::take_queue_spot()
472 lock_guard<mutex> lock(queue_state_mu);
476 void Player::release_queue_spot()
478 lock_guard<mutex> lock(queue_state_mu);
479 assert(num_queued_frames > 0);
481 new_clip_changed.notify_all();
484 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
486 // Look at the last clip and then start counting from there.
487 assert(!progress.empty());
488 auto last_it = progress.end();
490 double remaining = 0.0;
491 double last_fade_time_seconds = 0.0;
492 for (size_t row = last_it->first; row < clips.size(); ++row) {
493 const Clip &clip = clips[row];
494 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
495 if (row == last_it->first) {
496 // A clip we're playing: Subtract the part we've already played.
497 remaining = clip_length * (1.0 - last_it->second);
499 // A clip we haven't played yet: Subtract the part that's overlapping
500 // with a previous clip (due to fade).
501 remaining += max(clip_length - last_fade_time_seconds, 0.0);
503 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);