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(bool also_output_to_stream)
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 (also_output_to_stream) {
44 video_stream.reset(new VideoStream);
45 video_stream->start();
50 constexpr double output_framerate = 60000.0 / 1001.0; // FIXME: make configurable
53 size_t next_clip_idx = size_t(-1);
54 bool got_next_clip = false;
55 double next_clip_fade_time = -1.0;
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 new_clip_ready && current_clip.pts_in != -1;
68 new_clip_ready = false;
72 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
73 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
76 if (video_stream != nullptr) {
77 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
86 lock_guard<mutex> lock(mu);
88 clip_idx = current_clip_idx;
89 stream_idx = current_stream_idx;
91 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
92 int64_t in_pts_origin = clip.pts_in;
94 int64_t out_pts_origin = pts;
96 // Start playing exactly at a frame.
97 // TODO: Snap secondary (fade-to) clips in the same fashion
98 // so that we don't get jank here).
100 lock_guard<mutex> lock(frame_mu);
102 // Find the first frame such that frame.pts <= in_pts.
103 auto it = lower_bound(frames[stream_idx].begin(),
104 frames[stream_idx].end(),
106 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
107 if (it != frames[stream_idx].end()) {
108 in_pts_origin = it->pts;
112 // TODO: Lock to a rational multiple of the frame rate if possible.
115 int64_t in_pts_start_next_clip = -1;
116 steady_clock::time_point next_frame_start;
117 for (int frameno = 0; ; ++frameno) { // Ends when the clip ends.
118 double out_pts = out_pts_origin + TIMEBASE * frameno / output_framerate;
120 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
121 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * speed / output_framerate);
122 pts = lrint(out_pts);
124 if (in_pts >= clip.pts_out) {
128 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
129 if (time_behind >= milliseconds(200)) {
130 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
131 lrint(1e3 * duration<double>(time_behind).count()));
135 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / speed;
136 if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
137 // Find the next clip so that we can begin a fade.
138 tie(next_clip, next_clip_idx) = next_clip_callback();
139 if (next_clip.pts_in != -1) {
140 got_next_clip = true;
142 double duration_next_clip = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
143 next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
144 in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * speed);
148 // pts not affected by the swapping below.
149 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
151 int primary_stream_idx = stream_idx;
152 FrameOnDisk secondary_frame;
153 int secondary_stream_idx = -1;
154 float fade_alpha = 0.0f;
155 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
156 secondary_stream_idx = next_clip.stream_idx;
157 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * speed);
158 in_pts_secondary_for_progress = in_pts_secondary;
159 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
161 // If more than half-way through the fade, interpolate the next clip
162 // instead of the current one, since it's more visible.
163 if (fade_alpha >= 0.5f) {
164 swap(primary_stream_idx, secondary_stream_idx);
165 swap(in_pts, in_pts_secondary);
166 fade_alpha = 1.0f - fade_alpha;
169 FrameOnDisk frame_lower, frame_upper;
170 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
172 secondary_frame = frame_lower;
176 if (progress_callback != nullptr) {
177 // NOTE: None of this will take into account any snapping done below.
178 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / speed;
179 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / speed;
180 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
182 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
183 double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / speed;
184 double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
185 progress[next_clip_idx] = played_next_clip / total_next_length;
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);
197 unique_lock<mutex> lock(queue_state_mu);
198 if (video_stream == nullptr) {
199 // No queue, just wait until the right time and then show the frame.
200 new_clip_changed.wait_until(lock, next_frame_start, [this]{
201 return new_clip_ready || override_stream_idx != -1;
204 // If the queue is full (which is really the state we'd like to be in),
205 // wait until there's room for one more frame (ie., one was output from
206 // VideoStream), or until or until there's a new clip we're supposed to play.
208 // In this case, we don't sleep until next_frame_start; the displaying is
209 // done by the queue.
210 new_clip_changed.wait(lock, [this]{
211 if (num_queued_frames < max_queued_frames) {
214 return new_clip_ready || override_stream_idx != -1;
217 if (new_clip_ready) {
218 if (video_stream != nullptr) {
219 lock.unlock(); // Urg.
220 video_stream->clear_queue();
223 got_next_clip = false;
226 if (override_stream_idx != -1) {
227 stream_idx = override_stream_idx;
228 override_stream_idx = -1;
233 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
234 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
235 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
237 if (video_stream == nullptr) {
240 if (secondary_stream_idx == -1) {
241 video_stream->schedule_original_frame(
242 next_frame_start, pts, display_func, QueueSpotHolder(this),
245 assert(secondary_frame.pts != -1);
246 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
247 QueueSpotHolder(this), frame_lower,
248 secondary_frame, fade_alpha);
254 // Snap to input frame: If we can do so with less than 1% jitter
255 // (ie., move less than 1% of an _output_ frame), do so.
256 // TODO: Snap secondary (fade-to) clips in the same fashion.
257 bool snapped = false;
258 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
259 double snap_pts_as_frameno = (snap_frame.pts - in_pts_origin) * output_framerate / TIMEBASE / speed;
260 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
261 auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
262 destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
264 if (video_stream == nullptr) {
267 if (secondary_stream_idx == -1) {
268 video_stream->schedule_original_frame(
269 next_frame_start, pts, display_func,
270 QueueSpotHolder(this), snap_frame);
272 assert(secondary_frame.pts != -1);
273 video_stream->schedule_faded_frame(
274 next_frame_start, pts, display_func, QueueSpotHolder(this),
275 snap_frame, secondary_frame, fade_alpha);
278 in_pts_origin += snap_frame.pts - in_pts;
287 if (time_behind >= milliseconds(100)) {
288 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
289 lrint(1e3 * duration<double>(time_behind).count()));
293 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
295 if (video_stream == nullptr) {
296 // Previews don't do any interpolation.
297 assert(secondary_stream_idx == -1);
298 destination->setFrame(primary_stream_idx, frame_lower);
300 auto display_func = [this](shared_ptr<Frame> frame) {
301 destination->setFrame(frame);
303 video_stream->schedule_interpolated_frame(
304 next_frame_start, pts, display_func, QueueSpotHolder(this),
305 frame_lower, frame_upper, alpha,
306 secondary_frame, fade_alpha);
312 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
313 if (!got_next_clip && next_clip_callback != nullptr) {
314 tie(next_clip, next_clip_idx) = next_clip_callback();
315 if (next_clip.pts_in != -1) {
316 got_next_clip = true;
317 in_pts_start_next_clip = next_clip.pts_in;
321 // Switch to next clip if we got it.
324 clip_idx = next_clip_idx;
325 stream_idx = next_clip.stream_idx; // Override is used for previews only, and next_clip is used for live ony.
326 if (done_callback != nullptr) {
329 got_next_clip = false;
331 // Start the next clip from the point where the fade went out.
332 origin = next_frame_start;
333 in_pts_origin = in_pts_start_next_clip;
338 unique_lock<mutex> lock(queue_state_mu);
341 if (done_callback != nullptr) {
347 // Find the frame immediately before and after this point.
348 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
350 lock_guard<mutex> lock(frame_mu);
352 // Find the first frame such that frame.pts >= pts.
353 auto it = lower_bound(frames[stream_idx].begin(),
354 frames[stream_idx].end(),
356 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
357 if (it == frames[stream_idx].end()) {
362 // Find the last frame such that in_pts <= frame.pts (if any).
363 if (it == frames[stream_idx].begin()) {
366 *frame_lower = *(it - 1);
368 assert(pts >= frame_lower->pts);
369 assert(pts <= frame_upper->pts);
373 Player::Player(JPEGFrameView *destination, bool also_output_to_stream)
374 : destination(destination)
376 thread(&Player::thread_func, this, also_output_to_stream).detach();
379 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
382 lock_guard<mutex> lock(mu);
384 current_stream_idx = stream_idx;
385 current_clip_idx = clip_idx;
389 lock_guard<mutex> lock(queue_state_mu);
390 new_clip_ready = true;
391 override_stream_idx = -1;
392 new_clip_changed.notify_all();
396 void Player::override_angle(unsigned stream_idx)
398 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
400 unique_lock<mutex> lock(queue_state_mu);
401 if (new_clip_ready) {
402 lock_guard<mutex> lock2(mu);
403 current_stream_idx = stream_idx;
408 // If we are playing a clip, set override_stream_idx, and the player thread will
409 // pick it up and change its internal index.
411 unique_lock<mutex> lock(queue_state_mu);
413 override_stream_idx = stream_idx;
414 new_clip_changed.notify_all();
418 // OK, so we're standing still, presumably at the end of a clip.
419 // Look at the current pts_out (if it exists), and show the closest
423 lock_guard<mutex> lock(mu);
424 if (current_clip.pts_out < 0) {
427 pts_out = current_clip.pts_out;
430 lock_guard<mutex> lock(frame_mu);
431 auto it = upper_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts_out,
432 [](int64_t pts, const FrameOnDisk &frame) { return pts < frame.pts; });
433 if (it == frames[stream_idx].end()) {
436 destination->setFrame(stream_idx, *it);
439 void Player::take_queue_spot()
441 unique_lock<mutex> lock(queue_state_mu);
445 void Player::release_queue_spot()
447 unique_lock<mutex> lock(queue_state_mu);
448 assert(num_queued_frames > 0);
450 new_clip_changed.notify_all();