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();
52 while (!should_quit) {
54 vector<Clip> clip_list;
56 steady_clock::time_point before_sleep = steady_clock::now();
58 // Wait until we're supposed to play something.
60 unique_lock<mutex> lock(queue_state_mu);
62 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
63 return should_quit || new_clip_ready;
69 new_clip_ready = false;
71 clip_list = move(queued_clip_list);
72 queued_clip_list.clear();
73 assert(!clip_list.empty());
77 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
78 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
81 if (video_stream != nullptr) {
82 ++metric_refresh_frame;
83 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
88 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
89 int64_t in_pts_origin = clip_list[0].pts_in;
90 for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
91 const Clip &clip = clip_list[clip_idx];
92 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1] : nullptr;
93 int64_t out_pts_origin = pts;
95 double next_clip_fade_time = -1.0;
96 if (next_clip != nullptr) {
97 double duration_this_clip = double(clip.pts_out - in_pts_origin) / TIMEBASE / clip.speed;
98 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip.speed;
99 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip.fade_time_seconds);
102 int stream_idx = clip.stream_idx;
104 // Start playing exactly at a frame.
105 // TODO: Snap secondary (fade-to) clips in the same fashion
106 // so that we don't get jank here).
108 lock_guard<mutex> lock(frame_mu);
110 // Find the first frame such that frame.pts <= in_pts.
111 auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
112 if (it != frames[stream_idx].end()) {
113 in_pts_origin = it->pts;
117 steady_clock::time_point next_frame_start;
118 for (int frameno = 0; !should_quit; ++frameno) { // Ends when the clip ends.
119 double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
121 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
122 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
123 pts = lrint(out_pts);
125 if (in_pts >= clip.pts_out) {
129 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
130 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
131 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
132 lrint(1e3 * duration<double>(time_behind).count()));
133 ++metric_dropped_unconditional_frame;
138 // pts not affected by the swapping below.
139 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
141 int primary_stream_idx = stream_idx;
142 FrameOnDisk secondary_frame;
143 int secondary_stream_idx = -1;
144 float fade_alpha = 0.0f;
145 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
146 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
147 // We're in a fade to the next clip.
148 secondary_stream_idx = next_clip->stream_idx;
149 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
150 in_pts_secondary_for_progress = in_pts_secondary;
151 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
153 // If more than half-way through the fade, interpolate the next clip
154 // instead of the current one, since it's more visible.
155 if (fade_alpha >= 0.5f) {
156 swap(primary_stream_idx, secondary_stream_idx);
157 swap(in_pts, in_pts_secondary);
158 fade_alpha = 1.0f - fade_alpha;
161 FrameOnDisk frame_lower, frame_upper;
162 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
164 secondary_frame = frame_lower;
168 if (progress_callback != nullptr) {
169 // NOTE: None of this will take into account any snapping done below.
170 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / clip.speed;
171 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
172 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
174 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
175 double played_next_clip = double(in_pts_secondary_for_progress - next_clip->pts_in) / TIMEBASE / next_clip->speed;
176 double total_next_length = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / next_clip->speed;
177 progress[clip_idx + 1] = played_next_clip / total_next_length;
179 progress_callback(progress);
182 FrameOnDisk frame_lower, frame_upper;
183 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
188 // Wait until we should, or (given buffering) can, output the frame.
190 unique_lock<mutex> lock(queue_state_mu);
191 if (video_stream == nullptr) {
192 // No queue, just wait until the right time and then show the frame.
193 new_clip_changed.wait_until(lock, next_frame_start, [this]{
194 return should_quit || new_clip_ready || override_stream_idx != -1;
200 // If the queue is full (which is really the state we'd like to be in),
201 // wait until there's room for one more frame (ie., one was output from
202 // VideoStream), or until or until there's a new clip we're supposed to play.
204 // In this case, we don't sleep until next_frame_start; the displaying is
205 // done by the queue.
206 new_clip_changed.wait(lock, [this]{
207 if (num_queued_frames < max_queued_frames) {
210 return should_quit || new_clip_ready || override_stream_idx != -1;
216 if (new_clip_ready) {
217 if (video_stream != nullptr) {
218 lock.unlock(); // Urg.
219 video_stream->clear_queue();
224 // Honor if we got an override request for the camera.
225 if (override_stream_idx != -1) {
226 stream_idx = override_stream_idx;
227 override_stream_idx = -1;
232 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
233 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
234 if (destination != nullptr) {
235 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
238 if (video_stream == nullptr) {
241 if (secondary_stream_idx == -1) {
242 ++metric_original_frame;
243 video_stream->schedule_original_frame(
244 next_frame_start, pts, display_func, QueueSpotHolder(this),
247 assert(secondary_frame.pts != -1);
248 ++metric_faded_frame;
249 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
250 QueueSpotHolder(this), frame_lower,
251 secondary_frame, fade_alpha);
254 last_pts_played = frame_lower.pts;
258 // Snap to input frame: If we can do so with less than 1% jitter
259 // (ie., move less than 1% of an _output_ frame), do so.
260 // TODO: Snap secondary (fade-to) clips in the same fashion.
261 double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
262 bool snapped = false;
263 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
264 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
265 auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
266 if (destination != nullptr) {
267 destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
270 if (video_stream == nullptr) {
273 if (secondary_stream_idx == -1) {
274 ++metric_original_snapped_frame;
275 video_stream->schedule_original_frame(
276 next_frame_start, pts, display_func,
277 QueueSpotHolder(this), snap_frame);
279 assert(secondary_frame.pts != -1);
280 ++metric_faded_snapped_frame;
281 video_stream->schedule_faded_frame(
282 next_frame_start, pts, display_func, QueueSpotHolder(this),
283 snap_frame, secondary_frame, fade_alpha);
286 in_pts_origin += snap_frame.pts - in_pts;
288 last_pts_played = snap_frame.pts;
296 // The snapping above makes us lock to the input framerate, even in the presence
297 // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
298 // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
299 // get a snap very rarely (in the given case, once every 24 output frames), and by
300 // that time, we'd have drifted out. We could have solved this by changing the overall
301 // speed ever so slightly, but it requires that we know the actual frame rate (which
302 // is difficult in the presence of jitter and missed frames), or at least do some kind
303 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
304 // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
305 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
306 // in-between frame. Of course, we will still need to interpolate, but we get a lot
307 // closer when we actually get close to an original frame. In other words: Snap more
308 // often, but snap less each time. Unless the input and output frame rates are completely
309 // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
310 // really never see in practice).
311 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
312 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
313 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
314 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
315 in_pts_origin += lrint(subsnap_pts) - in_pts;
316 in_pts = lrint(subsnap_pts);
321 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
322 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
323 lrint(1e3 * duration<double>(time_behind).count()));
324 ++metric_dropped_interpolated_frame;
328 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
330 if (video_stream == nullptr) {
331 // Previews don't do any interpolation.
332 assert(secondary_stream_idx == -1);
333 if (destination != nullptr) {
334 destination->setFrame(primary_stream_idx, frame_lower);
336 last_pts_played = frame_lower.pts;
338 auto display_func = [this](shared_ptr<Frame> frame) {
339 if (destination != nullptr) {
340 destination->setFrame(frame);
343 if (secondary_stream_idx == -1) {
344 ++metric_interpolated_frame;
346 ++metric_interpolated_faded_frame;
348 video_stream->schedule_interpolated_frame(
349 next_frame_start, pts, display_func, QueueSpotHolder(this),
350 frame_lower, frame_upper, alpha,
351 secondary_frame, fade_alpha);
352 last_pts_played = in_pts; // Not really needed; only previews use last_pts_played.
360 if (done_callback != nullptr) {
364 // Start the next clip from the point where the fade went out.
365 if (next_clip != nullptr) {
366 origin = next_frame_start;
367 in_pts_origin = next_clip->pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
371 if (done_callback != nullptr) {
377 // Find the frame immediately before and after this point.
378 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
380 lock_guard<mutex> lock(frame_mu);
382 // Find the first frame such that frame.pts >= pts.
383 auto it = find_last_frame_before(frames[stream_idx], pts);
384 if (it == frames[stream_idx].end()) {
389 // Find the last frame such that in_pts <= frame.pts (if any).
390 if (it == frames[stream_idx].begin()) {
393 *frame_lower = *(it - 1);
395 assert(pts >= frame_lower->pts);
396 assert(pts <= frame_upper->pts);
400 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
401 : destination(destination)
403 player_thread = thread(&Player::thread_func, this, stream_output, file_avctx);
405 if (stream_output == HTTPD_STREAM_OUTPUT) {
406 global_metrics.add("http_output_frames", {{ "type", "original" }, { "reason", "edge_frame_or_no_interpolation" }}, &metric_original_frame);
407 global_metrics.add("http_output_frames", {{ "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" }}, &metric_faded_frame);
408 global_metrics.add("http_output_frames", {{ "type", "original" }, { "reason", "snapped" }}, &metric_original_snapped_frame);
409 global_metrics.add("http_output_frames", {{ "type", "faded" }, { "reason", "snapped" }}, &metric_faded_snapped_frame);
410 global_metrics.add("http_output_frames", {{ "type", "interpolated" }}, &metric_interpolated_frame);
411 global_metrics.add("http_output_frames", {{ "type", "interpolated_faded" }}, &metric_interpolated_faded_frame);
412 global_metrics.add("http_output_frames", {{ "type", "refresh" }}, &metric_refresh_frame);
413 global_metrics.add("http_dropped_frames", {{ "type", "interpolated" }}, &metric_dropped_interpolated_frame);
414 global_metrics.add("http_dropped_frames", {{ "type", "unconditional" }}, &metric_dropped_unconditional_frame);
421 if (video_stream != nullptr) {
422 video_stream->stop();
424 new_clip_changed.notify_all();
425 player_thread.join();
428 void Player::play(const vector<Clip> &clips)
430 lock_guard<mutex> lock(queue_state_mu);
431 new_clip_ready = true;
432 queued_clip_list = clips;
433 override_stream_idx = -1;
434 new_clip_changed.notify_all();
437 void Player::override_angle(unsigned stream_idx)
441 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
443 lock_guard<mutex> lock(queue_state_mu);
444 if (new_clip_ready) {
445 assert(queued_clip_list.size() == 1);
446 queued_clip_list[0].stream_idx = stream_idx;
450 // If we are playing a clip, set override_stream_idx, and the player thread will
451 // pick it up and change its internal index.
453 override_stream_idx = stream_idx;
454 new_clip_changed.notify_all();
458 // OK, so we're standing still, presumably at the end of a clip.
459 // Look at the last frame played (if it exists), and show the closest
461 if (last_pts_played < 0) {
464 last_pts = last_pts_played;
467 lock_guard<mutex> lock(frame_mu);
468 auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
469 if (it == frames[stream_idx].end()) {
472 destination->setFrame(stream_idx, *it);
475 void Player::take_queue_spot()
477 lock_guard<mutex> lock(queue_state_mu);
481 void Player::release_queue_spot()
483 lock_guard<mutex> lock(queue_state_mu);
484 assert(num_queued_frames > 0);
486 new_clip_changed.notify_all();
489 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
491 // Look at the last clip and then start counting from there.
492 assert(!progress.empty());
493 auto last_it = progress.end();
495 double remaining = 0.0;
496 double last_fade_time_seconds = 0.0;
497 for (size_t row = last_it->first; row < clips.size(); ++row) {
498 const Clip &clip = clips[row];
499 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
500 if (row == last_it->first) {
501 // A clip we're playing: Subtract the part we've already played.
502 remaining = clip_length * (1.0 - last_it->second);
504 // A clip we haven't played yet: Subtract the part that's overlapping
505 // with a previous clip (due to fade).
506 remaining += max(clip_length - last_fade_time_seconds, 0.0);
508 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);