4 #include "shared/context.h"
6 #include "shared/ffmpeg_raii.h"
7 #include "frame_on_disk.h"
8 #include "shared/httpd.h"
9 #include "jpeg_frame_view.h"
10 #include "shared/mux.h"
11 #include "shared/timebase.h"
12 #include "video_stream.h"
16 #include <condition_variable>
17 #include <movit/util.h>
24 using namespace std::chrono;
26 extern HTTPD *global_httpd;
28 void Player::thread_func(bool also_output_to_stream)
30 pthread_setname_np(pthread_self(), "Player");
32 QSurface *surface = create_surface();
33 QOpenGLContext *context = create_context(surface);
34 if (!make_current(context, surface)) {
41 // Create the VideoStream object, now that we have an OpenGL context.
42 if (also_output_to_stream) {
43 video_stream.reset(new VideoStream);
44 video_stream->start();
49 constexpr double output_framerate = 60000.0 / 1001.0; // FIXME: make configurable
52 size_t next_clip_idx = size_t(-1);
53 bool got_next_clip = false;
54 double next_clip_fade_time = -1.0;
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 new_clip_ready && current_clip.pts_in != -1;
67 new_clip_ready = false;
71 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
72 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
75 if (video_stream != nullptr) {
76 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
85 lock_guard<mutex> lock(mu);
87 clip_idx = current_clip_idx;
88 stream_idx = current_stream_idx;
90 steady_clock::time_point origin = steady_clock::now(); // TODO: Add a 100 ms buffer for ramp-up?
91 int64_t in_pts_origin = clip.pts_in;
93 int64_t out_pts_origin = pts;
95 // Start playing exactly at a frame.
96 // TODO: Snap secondary (fade-to) clips in the same fashion
97 // so that we don't get jank here).
99 lock_guard<mutex> lock(frame_mu);
101 // Find the first frame such that frame.pts <= in_pts.
102 auto it = lower_bound(frames[stream_idx].begin(),
103 frames[stream_idx].end(),
105 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
106 if (it != frames[stream_idx].end()) {
107 in_pts_origin = it->pts;
111 // TODO: Lock to a rational multiple of the frame rate if possible.
114 int64_t in_pts_start_next_clip = -1;
115 steady_clock::time_point next_frame_start;
116 for (int frameno = 0; ; ++frameno) { // Ends when the clip ends.
117 double out_pts = out_pts_origin + TIMEBASE * frameno / output_framerate;
119 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
120 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * speed / output_framerate);
121 pts = lrint(out_pts);
123 if (in_pts >= clip.pts_out) {
127 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
128 if (time_behind >= milliseconds(200)) {
129 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
130 lrint(1e3 * duration<double>(time_behind).count()));
134 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / 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 = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / 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 * 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 * 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 / speed;
178 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / 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 / speed;
183 double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / 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 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 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();
222 got_next_clip = false;
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) {
233 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
234 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
236 if (video_stream == nullptr) {
239 if (secondary_stream_idx == -1) {
240 video_stream->schedule_original_frame(
241 next_frame_start, pts, display_func, QueueSpotHolder(this),
244 assert(secondary_frame.pts != -1);
245 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
246 QueueSpotHolder(this), frame_lower,
247 secondary_frame, fade_alpha);
253 // Snap to input frame: If we can do so with less than 1% jitter
254 // (ie., move less than 1% of an _output_ frame), do so.
255 // TODO: Snap secondary (fade-to) clips in the same fashion.
256 bool snapped = false;
257 for (int64_t snap_pts : { frame_lower.pts, frame_upper.pts }) {
258 double snap_pts_as_frameno = (snap_pts - in_pts_origin) * output_framerate / TIMEBASE / speed;
259 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
260 FrameOnDisk snap_frame = frame_lower;
261 snap_frame.pts = snap_pts;
262 auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
263 destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
265 if (video_stream == nullptr) {
268 if (secondary_stream_idx == -1) {
269 video_stream->schedule_original_frame(
270 next_frame_start, pts, display_func,
271 QueueSpotHolder(this), snap_frame);
273 assert(secondary_frame.pts != -1);
274 video_stream->schedule_faded_frame(
275 next_frame_start, pts, display_func, QueueSpotHolder(this),
276 snap_frame, secondary_frame, fade_alpha);
279 in_pts_origin += snap_pts - in_pts;
288 if (time_behind >= milliseconds(100)) {
289 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
290 lrint(1e3 * duration<double>(time_behind).count()));
294 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
296 if (video_stream == nullptr) {
297 // Previews don't do any interpolation.
298 assert(secondary_stream_idx == -1);
299 destination->setFrame(primary_stream_idx, frame_lower);
301 auto display_func = [this](shared_ptr<Frame> frame) {
302 destination->setFrame(frame);
304 video_stream->schedule_interpolated_frame(
305 next_frame_start, pts, display_func, QueueSpotHolder(this),
306 frame_lower, frame_upper, alpha,
307 secondary_frame, fade_alpha);
313 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
314 if (!got_next_clip && next_clip_callback != nullptr) {
315 tie(next_clip, next_clip_idx) = next_clip_callback();
316 if (next_clip.pts_in != -1) {
317 got_next_clip = true;
318 in_pts_start_next_clip = next_clip.pts_in;
322 // Switch to next clip if we got it.
325 clip_idx = next_clip_idx;
326 stream_idx = next_clip.stream_idx; // Override is used for previews only, and next_clip is used for live ony.
327 if (done_callback != nullptr) {
330 got_next_clip = false;
332 // Start the next clip from the point where the fade went out.
333 origin = next_frame_start;
334 in_pts_origin = in_pts_start_next_clip;
339 unique_lock<mutex> lock(queue_state_mu);
342 if (done_callback != nullptr) {
348 // Find the frame immediately before and after this point.
349 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
351 lock_guard<mutex> lock(frame_mu);
353 // Find the first frame such that frame.pts >= pts.
354 auto it = lower_bound(frames[stream_idx].begin(),
355 frames[stream_idx].end(),
357 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
358 if (it == frames[stream_idx].end()) {
363 // Find the last frame such that in_pts <= frame.pts (if any).
364 if (it == frames[stream_idx].begin()) {
367 *frame_lower = *(it - 1);
369 assert(pts >= frame_lower->pts);
370 assert(pts <= frame_upper->pts);
374 Player::Player(JPEGFrameView *destination, bool also_output_to_stream)
375 : destination(destination)
377 thread(&Player::thread_func, this, also_output_to_stream).detach();
380 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
383 lock_guard<mutex> lock(mu);
385 current_stream_idx = stream_idx;
386 current_clip_idx = clip_idx;
390 lock_guard<mutex> lock(queue_state_mu);
391 new_clip_ready = true;
392 override_stream_idx = -1;
393 new_clip_changed.notify_all();
397 void Player::override_angle(unsigned stream_idx)
399 // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
401 unique_lock<mutex> lock(queue_state_mu);
402 if (new_clip_ready) {
403 lock_guard<mutex> lock2(mu);
404 current_stream_idx = stream_idx;
409 // If we are playing a clip, set override_stream_idx, and the player thread will
410 // pick it up and change its internal index.
412 unique_lock<mutex> lock(queue_state_mu);
414 override_stream_idx = stream_idx;
415 new_clip_changed.notify_all();
419 // OK, so we're standing still, presumably at the end of a clip.
420 // Look at the current pts_out (if it exists), and show the closest
424 lock_guard<mutex> lock(mu);
425 if (current_clip.pts_out < 0) {
428 pts_out = current_clip.pts_out;
431 lock_guard<mutex> lock(frame_mu);
432 auto it = upper_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts_out,
433 [](int64_t pts, const FrameOnDisk &frame) { return pts < frame.pts; });
434 if (it == frames[stream_idx].end()) {
437 destination->setFrame(stream_idx, *it);
440 void Player::take_queue_spot()
442 unique_lock<mutex> lock(queue_state_mu);
446 void Player::release_queue_spot()
448 unique_lock<mutex> lock(queue_state_mu);
449 assert(num_queued_frames > 0);
451 new_clip_changed.notify_all();