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/mux.h"
12 #include "shared/timebase.h"
13 #include "video_stream.h"
17 #include <condition_variable>
18 #include <movit/util.h>
25 using namespace std::chrono;
27 extern HTTPD *global_httpd;
29 void Player::thread_func(Player::StreamOutput stream_output, AVFormatContext *file_avctx)
31 pthread_setname_np(pthread_self(), "Player");
33 QSurface *surface = create_surface();
34 QOpenGLContext *context = create_context(surface);
35 if (!make_current(context, surface)) {
42 // Create the VideoStream object, now that we have an OpenGL context.
43 if (stream_output != NO_STREAM_OUTPUT) {
44 video_stream.reset(new VideoStream(file_avctx));
45 video_stream->start();
52 size_t next_clip_idx = size_t(-1);
53 bool got_next_clip = false;
54 double next_clip_fade_time = -1.0;
56 while (!should_quit) {
59 steady_clock::time_point before_sleep = steady_clock::now();
61 // Wait until we're supposed to play something.
63 unique_lock<mutex> lock(queue_state_mu);
64 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
65 return should_quit || (new_clip_ready && current_clip.pts_in != -1);
70 new_clip_ready = false;
74 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
75 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
78 if (video_stream != nullptr) {
79 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
88 lock_guard<mutex> lock(mu);
90 clip_idx = current_clip_idx;
91 stream_idx = current_stream_idx;
93 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
94 int64_t in_pts_origin = clip.pts_in;
96 int64_t out_pts_origin = pts;
98 // Start playing exactly at a frame.
99 // TODO: Snap secondary (fade-to) clips in the same fashion
100 // so that we don't get jank here).
102 lock_guard<mutex> lock(frame_mu);
104 // Find the first frame such that frame.pts <= in_pts.
105 auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
106 if (it != frames[stream_idx].end()) {
107 in_pts_origin = it->pts;
111 int64_t in_pts_start_next_clip = -1;
112 steady_clock::time_point next_frame_start;
113 for (int frameno = 0; !should_quit; ++frameno) { // Ends when the clip ends.
114 double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
116 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
117 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
118 pts = lrint(out_pts);
120 if (in_pts >= clip.pts_out) {
124 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
125 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
126 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
127 lrint(1e3 * duration<double>(time_behind).count()));
131 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
132 if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
133 // Find the next clip so that we can begin a fade.
134 tie(next_clip, next_clip_idx) = next_clip_callback();
135 if (next_clip.pts_in != -1) {
136 got_next_clip = true;
138 double duration_next_clip = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / clip.speed;
139 next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
140 in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
144 // pts not affected by the swapping below.
145 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
147 int primary_stream_idx = stream_idx;
148 FrameOnDisk secondary_frame;
149 int secondary_stream_idx = -1;
150 float fade_alpha = 0.0f;
151 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
152 secondary_stream_idx = next_clip.stream_idx;
153 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
154 in_pts_secondary_for_progress = in_pts_secondary;
155 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
157 // If more than half-way through the fade, interpolate the next clip
158 // instead of the current one, since it's more visible.
159 if (fade_alpha >= 0.5f) {
160 swap(primary_stream_idx, secondary_stream_idx);
161 swap(in_pts, in_pts_secondary);
162 fade_alpha = 1.0f - fade_alpha;
165 FrameOnDisk frame_lower, frame_upper;
166 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
168 secondary_frame = frame_lower;
172 if (progress_callback != nullptr) {
173 // NOTE: None of this will take into account any snapping done below.
174 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / clip.speed;
175 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
176 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
178 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
179 double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / next_clip.speed;
180 double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / next_clip.speed;
181 progress[next_clip_idx] = played_next_clip / total_next_length;
183 progress_callback(progress);
186 FrameOnDisk frame_lower, frame_upper;
187 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
193 unique_lock<mutex> lock(queue_state_mu);
194 if (video_stream == nullptr) {
195 // No queue, just wait until the right time and then show the frame.
196 new_clip_changed.wait_until(lock, next_frame_start, [this]{
197 return should_quit || new_clip_ready || override_stream_idx != -1;
203 // If the queue is full (which is really the state we'd like to be in),
204 // wait until there's room for one more frame (ie., one was output from
205 // VideoStream), or until or until there's a new clip we're supposed to play.
207 // In this case, we don't sleep until next_frame_start; the displaying is
208 // done by the queue.
209 new_clip_changed.wait(lock, [this]{
210 if (num_queued_frames < max_queued_frames) {
213 return should_quit || new_clip_ready || override_stream_idx != -1;
219 if (new_clip_ready) {
220 if (video_stream != nullptr) {
221 lock.unlock(); // Urg.
222 video_stream->clear_queue();
225 got_next_clip = false;
228 if (override_stream_idx != -1) {
229 stream_idx = override_stream_idx;
230 override_stream_idx = -1;
235 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
236 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
237 if (destination != nullptr) {
238 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
241 if (video_stream == nullptr) {
244 if (secondary_stream_idx == -1) {
245 video_stream->schedule_original_frame(
246 next_frame_start, pts, display_func, QueueSpotHolder(this),
249 assert(secondary_frame.pts != -1);
250 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
251 QueueSpotHolder(this), frame_lower,
252 secondary_frame, fade_alpha);
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 video_stream->schedule_original_frame(
275 next_frame_start, pts, display_func,
276 QueueSpotHolder(this), snap_frame);
278 assert(secondary_frame.pts != -1);
279 video_stream->schedule_faded_frame(
280 next_frame_start, pts, display_func, QueueSpotHolder(this),
281 snap_frame, secondary_frame, fade_alpha);
284 in_pts_origin += snap_frame.pts - in_pts;
293 // The snapping above makes us lock to the input framerate, even in the presence
294 // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
295 // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
296 // get a snap very rarely (in the given case, once every 24 output frames), and by
297 // that time, we'd have drifted out. We could have solved this by changing the overall
298 // speed ever so slightly, but it requires that we know the actual frame rate (which
299 // is difficult in the presence of jitter and missed frames), or at least do some kind
300 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
301 // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
302 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
303 // in-between frame. Of course, we will still need to interpolate, but we get a lot
304 // closer when we actually get close to an original frame. In other words: Snap more
305 // often, but snap less each time. Unless the input and output frame rates are completely
306 // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
307 // really never see in practice).
308 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
309 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
310 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
311 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
312 in_pts_origin += lrint(subsnap_pts) - in_pts;
313 in_pts = lrint(subsnap_pts);
318 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
319 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
320 lrint(1e3 * duration<double>(time_behind).count()));
324 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
326 if (video_stream == nullptr) {
327 // Previews don't do any interpolation.
328 assert(secondary_stream_idx == -1);
329 if (destination != nullptr) {
330 destination->setFrame(primary_stream_idx, frame_lower);
333 auto display_func = [this](shared_ptr<Frame> frame) {
334 if (destination != nullptr) {
335 destination->setFrame(frame);
338 video_stream->schedule_interpolated_frame(
339 next_frame_start, pts, display_func, QueueSpotHolder(this),
340 frame_lower, frame_upper, alpha,
341 secondary_frame, fade_alpha);
351 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
352 if (!got_next_clip && next_clip_callback != nullptr) {
353 tie(next_clip, next_clip_idx) = next_clip_callback();
354 if (next_clip.pts_in != -1) {
355 got_next_clip = true;
356 in_pts_start_next_clip = next_clip.pts_in;
360 // Switch to next clip if we got it.
363 clip_idx = next_clip_idx;
364 stream_idx = next_clip.stream_idx; // Override is used for previews only, and next_clip is used for live ony.
365 if (done_callback != nullptr) {
368 got_next_clip = false;
370 // Start the next clip from the point where the fade went out.
371 origin = next_frame_start;
372 in_pts_origin = in_pts_start_next_clip;
377 unique_lock<mutex> lock(queue_state_mu);
380 if (done_callback != nullptr) {
386 // Find the frame immediately before and after this point.
387 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
389 lock_guard<mutex> lock(frame_mu);
391 // Find the first frame such that frame.pts >= pts.
392 auto it = find_last_frame_before(frames[stream_idx], pts);
393 if (it == frames[stream_idx].end()) {
398 // Find the last frame such that in_pts <= frame.pts (if any).
399 if (it == frames[stream_idx].begin()) {
402 *frame_lower = *(it - 1);
404 assert(pts >= frame_lower->pts);
405 assert(pts <= frame_upper->pts);
409 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
410 : destination(destination)
412 player_thread = thread(&Player::thread_func, this, stream_output, file_avctx);
418 if (video_stream != nullptr) {
419 video_stream->stop();
421 new_clip_changed.notify_all();
422 player_thread.join();
425 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
428 lock_guard<mutex> lock(mu);
430 current_stream_idx = stream_idx;
431 current_clip_idx = clip_idx;
435 lock_guard<mutex> lock(queue_state_mu);
436 new_clip_ready = true;
437 override_stream_idx = -1;
438 new_clip_changed.notify_all();
442 void Player::override_angle(unsigned stream_idx)
444 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
446 unique_lock<mutex> lock(queue_state_mu);
447 if (new_clip_ready) {
448 lock_guard<mutex> lock2(mu);
449 current_stream_idx = stream_idx;
454 // If we are playing a clip, set override_stream_idx, and the player thread will
455 // pick it up and change its internal index.
457 unique_lock<mutex> lock(queue_state_mu);
459 override_stream_idx = stream_idx;
460 new_clip_changed.notify_all();
464 // OK, so we're standing still, presumably at the end of a clip.
465 // Look at the current pts_out (if it exists), and show the closest
469 lock_guard<mutex> lock(mu);
470 if (current_clip.pts_out < 0) {
473 pts_out = current_clip.pts_out;
476 lock_guard<mutex> lock(frame_mu);
477 auto it = find_first_frame_at_or_after(frames[stream_idx], pts_out);
478 if (it == frames[stream_idx].end()) {
481 destination->setFrame(stream_idx, *it);
484 void Player::take_queue_spot()
486 unique_lock<mutex> lock(queue_state_mu);
490 void Player::release_queue_spot()
492 unique_lock<mutex> lock(queue_state_mu);
493 assert(num_queued_frames > 0);
495 new_clip_changed.notify_all();
498 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
500 // Look at the last clip and then start counting from there.
501 assert(!progress.empty());
502 auto last_it = progress.end();
504 double remaining = 0.0;
505 double last_fade_time_seconds = 0.0;
506 for (size_t row = last_it->first; row < clips.size(); ++row) {
507 const Clip &clip = clips[row];
508 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
509 if (row == last_it->first) {
510 // A clip we're playing: Subtract the part we've already played.
511 remaining = clip_length * (1.0 - last_it->second);
513 // A clip we haven't played yet: Subtract the part that's overlapping
514 // with a previous clip (due to fade).
515 remaining += max(clip_length - last_fade_time_seconds, 0.0);
517 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);