]> git.sesse.net Git - nageru/blob - player.cpp
Allow symlinked frame files. Useful for testing.
[nageru] / player.cpp
1 #include "player.h"
2
3 #include "clip_list.h"
4 #include "context.h"
5 #include "defs.h"
6 #include "ffmpeg_raii.h"
7 #include "frame_on_disk.h"
8 #include "httpd.h"
9 #include "jpeg_frame_view.h"
10 #include "mux.h"
11 #include "timebase.h"
12 #include "video_stream.h"
13
14 #include <algorithm>
15 #include <chrono>
16 #include <condition_variable>
17 #include <movit/util.h>
18 #include <mutex>
19 #include <stdio.h>
20 #include <thread>
21 #include <vector>
22
23 using namespace std;
24 using namespace std::chrono;
25
26 extern HTTPD *global_httpd;
27
28 void Player::thread_func(bool also_output_to_stream)
29 {
30         pthread_setname_np(pthread_self(), "Player");
31
32         QSurface *surface = create_surface();
33         QOpenGLContext *context = create_context(surface);
34         if (!make_current(context, surface)) {
35                 printf("oops\n");
36                 exit(1);
37         }
38
39         check_error();
40
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();
45         }
46
47         check_error();
48
49         constexpr double output_framerate = 60000.0 / 1001.0;  // FIXME: make configurable
50         int64_t pts = 0;
51         Clip next_clip;
52         size_t next_clip_idx = size_t(-1);
53         bool got_next_clip = false;
54         double next_clip_fade_time = -1.0;
55
56         for ( ;; ) {
57 wait_for_clip:
58                 bool clip_ready;
59                 steady_clock::time_point before_sleep = steady_clock::now();
60
61                 // Wait until we're supposed to play something.
62                 {
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;
66                         });
67                         new_clip_ready = false;
68                         playing = true;
69                 }
70
71                 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
72                 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
73
74                 if (!clip_ready) {
75                         if (video_stream != nullptr) {
76                                 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
77                         }
78                         continue;
79                 }
80
81                 Clip clip;
82                 size_t clip_idx;
83                 unsigned stream_idx;
84                 {
85                         lock_guard<mutex> lock(mu);
86                         clip = current_clip;
87                         clip_idx = current_clip_idx;
88                         stream_idx = current_stream_idx;
89                 }
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;
92 got_clip:
93                 int64_t out_pts_origin = pts;
94
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).
98                 {
99                         lock_guard<mutex> lock(frame_mu);
100
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(),
104                                 in_pts_origin,
105                                 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
106                         if (it != frames[stream_idx].end()) {
107                                 in_pts_origin = it->pts;
108                         }
109                 }
110
111                 // TODO: Lock to a rational multiple of the frame rate if possible.
112                 double speed = 0.5;
113
114                 int64_t in_pts_start_next_clip = -1;
115                 for (int frameno = 0; ; ++frameno) {  // Ends when the clip ends.
116                         double out_pts = out_pts_origin + TIMEBASE * frameno / output_framerate;
117                         steady_clock::time_point next_frame_start =
118                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
119                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * speed / output_framerate);
120                         pts = lrint(out_pts);
121
122                         if (in_pts >= clip.pts_out) {
123                                 break;
124                         }
125
126                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
127                         if (time_behind >= milliseconds(200)) {
128                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
129                                         lrint(1e3 * duration<double>(time_behind).count()));
130                                 continue;
131                         }
132
133                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / speed;
134                         if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
135                                 // Find the next clip so that we can begin a fade.
136                                 tie(next_clip, next_clip_idx) = next_clip_callback();
137                                 if (next_clip.pts_in != -1) {
138                                         got_next_clip = true;
139
140                                         double duration_next_clip = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
141                                         next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
142                                         in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * speed);
143                                 }
144                         }
145
146                         // pts not affected by the swapping below.
147                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
148
149                         int primary_stream_idx = stream_idx;
150                         FrameOnDisk secondary_frame;
151                         int secondary_stream_idx = -1;
152                         float fade_alpha = 0.0f;
153                         if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
154                                 secondary_stream_idx = next_clip.stream_idx;
155                                 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * speed);
156                                 in_pts_secondary_for_progress = in_pts_secondary;
157                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
158
159                                 // If more than half-way through the fade, interpolate the next clip
160                                 // instead of the current one, since it's more visible.
161                                 if (fade_alpha >= 0.5f) {
162                                         swap(primary_stream_idx, secondary_stream_idx);
163                                         swap(in_pts, in_pts_secondary);
164                                         fade_alpha = 1.0f - fade_alpha;
165                                 }
166
167                                 FrameOnDisk frame_lower, frame_upper;
168                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
169                                 if (ok) {
170                                         secondary_frame = frame_lower;
171                                 }
172                         }
173
174                         if (progress_callback != nullptr) {
175                                 // NOTE: None of this will take into account any snapping done below.
176                                 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / speed;
177                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / speed;
178                                 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
179
180                                 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
181                                         double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / speed;
182                                         double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
183                                         progress[next_clip_idx] = played_next_clip / total_next_length;
184                                 }
185                                 progress_callback(progress);
186                         }
187
188                         FrameOnDisk frame_lower, frame_upper;
189                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
190                         if (!ok) {
191                                 break;
192                         }
193
194                         {
195                                 unique_lock<mutex> lock(queue_state_mu);
196                                 if (video_stream == nullptr) {
197                                         // No queue, just wait until the right time and then show the frame.
198                                         new_clip_changed.wait_until(lock, next_frame_start, [this]{
199                                                 return new_clip_ready || override_stream_idx != -1;
200                                         });
201                                 } else {
202                                         // If the queue is full (which is really the state we'd like to be in),
203                                         // wait until there's room for one more frame (ie., one was output from
204                                         // VideoStream), or until or until there's a new clip we're supposed to play.
205                                         //
206                                         // In this case, we don't sleep until next_frame_start; the displaying is
207                                         // done by the queue.
208                                         new_clip_changed.wait(lock, [this]{
209                                                 if (num_queued_frames < max_queued_frames) {
210                                                         return true;
211                                                 }
212                                                 return new_clip_ready || override_stream_idx != -1;
213                                         });
214                                 }
215                                 if (new_clip_ready) {
216                                         if (video_stream != nullptr) {
217                                                 lock.unlock();  // Urg.
218                                                 video_stream->clear_queue();
219                                                 lock.lock();
220                                         }
221                                         got_next_clip = false;
222                                         goto wait_for_clip;
223                                 }
224                                 if (override_stream_idx != -1) {
225                                         stream_idx = override_stream_idx;
226                                         override_stream_idx = -1;
227                                         continue;
228                                 }
229                         }
230
231                         if (frame_lower.pts == frame_upper.pts) {
232                                 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
233                                         destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
234                                 };
235                                 if (video_stream == nullptr) {
236                                         display_func();
237                                 } else {
238                                         if (secondary_stream_idx == -1) {
239                                                 video_stream->schedule_original_frame(
240                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
241                                                         frame_lower);
242                                         } else {
243                                                 assert(secondary_frame.pts != -1);
244                                                 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
245                                                         QueueSpotHolder(this), frame_lower,
246                                                         secondary_frame, fade_alpha);
247                                         }
248                                 }
249                                 continue;
250                         }
251
252                         // Snap to input frame: If we can do so with less than 1% jitter
253                         // (ie., move less than 1% of an _output_ frame), do so.
254                         // TODO: Snap secondary (fade-to) clips in the same fashion.
255                         bool snapped = false;
256                         for (int64_t snap_pts : { frame_lower.pts, frame_upper.pts }) {
257                                 double snap_pts_as_frameno = (snap_pts - in_pts_origin) * output_framerate / TIMEBASE / speed;
258                                 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
259                                         FrameOnDisk snap_frame = frame_lower;
260                                         snap_frame.pts = snap_pts;
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);
263                                         };
264                                         if (video_stream == nullptr) {
265                                                 display_func();
266                                         } else {
267                                                 if (secondary_stream_idx == -1) {
268                                                         video_stream->schedule_original_frame(
269                                                                 next_frame_start, pts, display_func,
270                                                                 QueueSpotHolder(this), snap_frame);
271                                                 } else {
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);
276                                                 }
277                                         }
278                                         in_pts_origin += snap_pts - in_pts;
279                                         snapped = true;
280                                         break;
281                                 }
282                         }
283                         if (snapped) {
284                                 continue;
285                         }
286
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()));
290                                 continue;
291                         }
292
293                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
294
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);
299                         } else {
300                                 auto display_func = [this](shared_ptr<Frame> frame) {
301                                         destination->setFrame(frame);
302                                 };
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);
307                         }
308                 }
309
310                 // The clip ended.
311
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;
318                         }
319                 }
320
321                 // Switch to next clip if we got it.
322                 if (got_next_clip) {
323                         clip = next_clip;
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) {
327                                 done_callback();
328                         }
329                         got_next_clip = false;
330
331                         // Start the next clip from the point where the fade went out.
332                         origin = steady_clock::now();
333                         in_pts_origin = in_pts_start_next_clip;
334                         goto got_clip;
335                 }
336
337                 {
338                         unique_lock<mutex> lock(queue_state_mu);
339                         playing = false;
340                 }
341                 if (done_callback != nullptr) {
342                         done_callback();
343                 }
344         }
345 }
346
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)
349 {
350         lock_guard<mutex> lock(frame_mu);
351
352         // Find the first frame such that frame.pts >= pts.
353         auto it = lower_bound(frames[stream_idx].begin(),
354                 frames[stream_idx].end(),
355                 pts,
356                 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
357         if (it == frames[stream_idx].end()) {
358                 return false;
359         }
360         *frame_upper = *it;
361
362         // Find the last frame such that in_pts <= frame.pts (if any).
363         if (it == frames[stream_idx].begin()) {
364                 *frame_lower = *it;
365         } else {
366                 *frame_lower = *(it - 1);
367         }
368         assert(pts >= frame_lower->pts);
369         assert(pts <= frame_upper->pts);
370         return true;
371 }
372
373 Player::Player(JPEGFrameView *destination, bool also_output_to_stream)
374         : destination(destination)
375 {
376         thread(&Player::thread_func, this, also_output_to_stream).detach();
377 }
378
379 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
380 {
381         {
382                 lock_guard<mutex> lock(mu);
383                 current_clip = clip;
384                 current_stream_idx = stream_idx;
385                 current_clip_idx = clip_idx;
386         }
387
388         {
389                 lock_guard<mutex> lock(queue_state_mu);
390                 new_clip_ready = true;
391                 override_stream_idx = -1;
392                 new_clip_changed.notify_all();
393         }
394 }
395
396 void Player::override_angle(unsigned stream_idx)
397 {
398         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
399         {
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;
404                         return;
405                 }
406         }
407
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.
410         {
411                 unique_lock<mutex> lock(queue_state_mu);
412                 if (playing) {
413                         override_stream_idx = stream_idx;
414                         new_clip_changed.notify_all();
415                 }
416         }
417
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
420         // thing we've got.
421         int64_t pts_out;
422         {
423                 lock_guard<mutex> lock(mu);
424                 if (current_clip.pts_out < 0) {
425                         return;
426                 }
427                 pts_out = current_clip.pts_out;
428         }
429
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()) {
434                 return;
435         }
436         destination->setFrame(stream_idx, *it);
437 }
438
439 void Player::take_queue_spot()
440 {
441         unique_lock<mutex> lock(queue_state_mu);
442         ++num_queued_frames;
443 }
444
445 void Player::release_queue_spot()
446 {
447         unique_lock<mutex> lock(queue_state_mu);
448         assert(num_queued_frames > 0);
449         --num_queued_frames;
450         new_clip_changed.notify_all();
451 }