]> git.sesse.net Git - nageru/blob - player.cpp
Unbreak preview.
[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 "httpd.h"
8 #include "jpeg_frame_view.h"
9 #include "mux.h"
10 #include "timebase.h"
11 #include "video_stream.h"
12
13 #include <algorithm>
14 #include <chrono>
15 #include <condition_variable>
16 #include <movit/util.h>
17 #include <mutex>
18 #include <stdio.h>
19 #include <thread>
20 #include <vector>
21
22 using namespace std;
23 using namespace std::chrono;
24
25 extern mutex frame_mu;
26 extern vector<int64_t> frames[MAX_STREAMS];
27 extern HTTPD *global_httpd;
28
29 void Player::thread_func(bool also_output_to_stream)
30 {
31         pthread_setname_np(pthread_self(), "Player");
32
33         QSurface *surface = create_surface();
34         QOpenGLContext *context = create_context(surface);
35         if (!make_current(context, surface)) {
36                 printf("oops\n");
37                 exit(1);
38         }
39
40         check_error();
41
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();
46         }
47
48         check_error();
49
50         constexpr double output_framerate = 60000.0 / 1001.0;  // FIXME: make configurable
51         int64_t pts = 0;
52         Clip next_clip;
53         size_t next_clip_idx = size_t(-1);
54         bool got_next_clip = false;
55         double next_clip_fade_time = -1.0;
56
57         for ( ;; ) {
58 wait_for_clip:
59                 bool clip_ready;
60                 steady_clock::time_point before_sleep = steady_clock::now();
61
62                 // Wait until we're supposed to play something.
63                 {
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;
67                         });
68                         new_clip_ready = false;
69                         playing = true;
70                 }
71
72                 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
73                 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
74
75                 if (!clip_ready) {
76                         if (video_stream != nullptr) {
77                                 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
78                         }
79                         continue;
80                 }
81
82                 Clip clip;
83                 size_t clip_idx;
84                 unsigned stream_idx;
85                 {
86                         lock_guard<mutex> lock(mu);
87                         clip = current_clip;
88                         clip_idx = current_clip_idx;
89                         stream_idx = current_stream_idx;
90                 }
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;
93 got_clip:
94                 int64_t out_pts_origin = pts;
95
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).
99                 {
100                         lock_guard<mutex> lock(frame_mu);
101
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(),
105                                 in_pts_origin);
106                         if (it != frames[stream_idx].end()) {
107                                 in_pts_origin = *it;
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                         int secondary_stream_idx = -1;
151                         int64_t secondary_pts = -1;
152                         int64_t in_pts_secondary = -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                                 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;
159
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;
166                                 }
167
168                                 int64_t in_pts_lower, in_pts_upper;
169                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &in_pts_lower, &in_pts_upper);
170                                 if (ok) {
171                                         secondary_pts = in_pts_lower;
172                                 } else {
173                                         secondary_stream_idx = -1;
174                                 }
175                         }
176
177                         if (progress_callback != nullptr) {
178                                 // NOTE: None of this will take into account any snapping done below.
179                                 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / speed;
180                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / speed;
181                                 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
182
183                                 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
184                                         double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / speed;
185                                         double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
186                                         progress[next_clip_idx] = played_next_clip / total_next_length;
187                                 }
188                                 progress_callback(progress);
189                         }
190
191                         int64_t in_pts_lower, in_pts_upper;
192                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &in_pts_lower, &in_pts_upper);
193                         if (!ok) {
194                                 break;
195                         }
196
197                         {
198                                 unique_lock<mutex> lock(queue_state_mu);
199                                 if (video_stream == nullptr) {
200                                         // No queue, just wait until the right time and then show the frame.
201                                         new_clip_changed.wait_until(lock, next_frame_start, [this]{
202                                                 return new_clip_ready || override_stream_idx != -1;
203                                         });
204                                 } else {
205                                         // If the queue is full (which is really the state we'd like to be in),
206                                         // wait until there's room for one more frame (ie., one was output from
207                                         // VideoStream), or until or until there's a new clip we're supposed to play.
208                                         //
209                                         // In this case, we don't sleep until next_frame_start; the displaying is
210                                         // done by the queue.
211                                         new_clip_changed.wait(lock, [this]{
212                                                 if (num_queued_frames < max_queued_frames) {
213                                                         return true;
214                                                 }
215                                                 return new_clip_ready || override_stream_idx != -1;
216                                         });
217                                 }
218                                 if (new_clip_ready) {
219                                         if (video_stream != nullptr) {
220                                                 lock.unlock();  // Urg.
221                                                 video_stream->clear_queue();
222                                                 lock.lock();
223                                         }
224                                         goto wait_for_clip;
225                                 }
226                                 if (override_stream_idx != -1) {
227                                         stream_idx = override_stream_idx;
228                                         override_stream_idx = -1;
229                                         continue;
230                                 }
231                         }
232
233                         if (in_pts_lower == in_pts_upper) {
234                                 auto display_func = [this, primary_stream_idx, in_pts_lower, secondary_stream_idx, secondary_pts, fade_alpha]{
235                                         destination->setFrame(primary_stream_idx, in_pts_lower, /*interpolated=*/false, secondary_stream_idx, secondary_pts, fade_alpha);
236                                 };
237                                 if (video_stream == nullptr) {
238                                         display_func();
239                                 } else {
240                                         if (secondary_stream_idx == -1) {
241                                                 video_stream->schedule_original_frame(
242                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
243                                                         primary_stream_idx, in_pts_lower);
244                                         } else {
245                                                 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
246                                                         QueueSpotHolder(this), primary_stream_idx, in_pts_lower,
247                                                         secondary_stream_idx, secondary_pts, fade_alpha);
248                                         }
249                                 }
250                                 continue;
251                         }
252
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 : { in_pts_lower, in_pts_upper }) {
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                                         auto display_func = [this, primary_stream_idx, snap_pts, secondary_stream_idx, secondary_pts, fade_alpha]{
261                                                 destination->setFrame(primary_stream_idx, snap_pts, /*interpolated=*/false, secondary_stream_idx, secondary_pts, fade_alpha);
262                                         };
263                                         if (video_stream == nullptr) {
264                                                 display_func();
265                                         } else {
266                                                 if (secondary_stream_idx == -1) {
267                                                         video_stream->schedule_original_frame(
268                                                                 next_frame_start, pts, display_func,
269                                                                 QueueSpotHolder(this), primary_stream_idx, snap_pts);
270                                                 } else {
271                                                         video_stream->schedule_faded_frame(
272                                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
273                                                                 primary_stream_idx, snap_pts, secondary_stream_idx, secondary_pts, fade_alpha);
274                                                 }
275                                         }
276                                         in_pts_origin += snap_pts - in_pts;
277                                         snapped = true;
278                                         break;
279                                 }
280                         }
281                         if (snapped) {
282                                 continue;
283                         }
284
285                         if (time_behind >= milliseconds(100)) {
286                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
287                                         lrint(1e3 * duration<double>(time_behind).count()));
288                                 continue;
289                         }
290
291                         double alpha = double(in_pts - in_pts_lower) / (in_pts_upper - in_pts_lower);
292
293                         if (video_stream == nullptr) {
294                                 // Previews don't do any interpolation.
295                                 assert(secondary_stream_idx == -1);
296                                 destination->setFrame(primary_stream_idx, in_pts_lower, /*interpolated=*/false);
297                         } else {
298                                 auto display_func = [this, primary_stream_idx, pts, secondary_stream_idx, secondary_pts, fade_alpha]{
299                                         destination->setFrame(primary_stream_idx, pts, /*interpolated=*/true, secondary_stream_idx, secondary_pts, fade_alpha);
300                                 };
301                                 video_stream->schedule_interpolated_frame(
302                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
303                                         primary_stream_idx, in_pts_lower, in_pts_upper, alpha,
304                                         secondary_stream_idx, secondary_pts, fade_alpha);
305                         }
306                 }
307
308                 // The clip ended.
309
310                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
311                 if (!got_next_clip && next_clip_callback != nullptr) {
312                         tie(next_clip, next_clip_idx) = next_clip_callback();
313                         if (next_clip.pts_in != -1) {
314                                 got_next_clip = true;
315                                 in_pts_start_next_clip = next_clip.pts_in;
316                         }
317                 }
318
319                 // Switch to next clip if we got it.
320                 if (got_next_clip) {
321                         clip = next_clip;
322                         clip_idx = next_clip_idx;
323                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
324                         if (done_callback != nullptr) {
325                                 done_callback();
326                         }
327                         got_next_clip = false;
328
329                         // Start the next clip from the point where the fade went out.
330                         origin = steady_clock::now();
331                         in_pts_origin = in_pts_start_next_clip;
332                         goto got_clip;
333                 }
334
335                 {
336                         unique_lock<mutex> lock(queue_state_mu);
337                         playing = false;
338                 }
339                 if (done_callback != nullptr) {
340                         done_callback();
341                 }
342         }
343 }
344
345 // Find the frame immediately before and after this point.
346 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, int64_t *pts_lower, int64_t *pts_upper)
347 {
348         lock_guard<mutex> lock(frame_mu);
349
350         // Find the first frame such that frame.pts >= pts.
351         auto it = lower_bound(frames[stream_idx].begin(),
352                 frames[stream_idx].end(),
353                 pts);
354         if (it == frames[stream_idx].end()) {
355                 return false;
356         }
357         *pts_upper = *it;
358
359         // Find the last frame such that in_pts <= frame.pts (if any).
360         if (it == frames[stream_idx].begin()) {
361                 *pts_lower = *it;
362         } else {
363                 *pts_lower = *(it - 1);
364         }
365         assert(pts >= *pts_lower);
366         assert(pts <= *pts_upper);
367         return true;
368 }
369
370 Player::Player(JPEGFrameView *destination, bool also_output_to_stream)
371         : destination(destination)
372 {
373         thread(&Player::thread_func, this, also_output_to_stream).detach();
374 }
375
376 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
377 {
378         {
379                 lock_guard<mutex> lock(mu);
380                 current_clip = clip;
381                 current_stream_idx = stream_idx;
382                 current_clip_idx = clip_idx;
383         }
384
385         {
386                 lock_guard<mutex> lock(queue_state_mu);
387                 new_clip_ready = true;
388                 override_stream_idx = -1;
389                 new_clip_changed.notify_all();
390         }
391 }
392
393 void Player::override_angle(unsigned stream_idx)
394 {
395         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
396         {
397                 unique_lock<mutex> lock(queue_state_mu);
398                 if (new_clip_ready) {
399                         lock_guard<mutex> lock2(mu);
400                         current_stream_idx = stream_idx;
401                         return;
402                 }
403         }
404
405         // If we are playing a clip, set override_stream_idx, and the player thread will
406         // pick it up and change its internal index.
407         {
408                 unique_lock<mutex> lock(queue_state_mu);
409                 if (playing) {
410                         override_stream_idx = stream_idx;
411                         new_clip_changed.notify_all();
412                 }
413         }
414
415         // OK, so we're standing still, presumably at the end of a clip.
416         // Look at the current pts_out (if it exists), and show the closest
417         // thing we've got.
418         int64_t pts_out;
419         {
420                 lock_guard<mutex> lock(mu);
421                 if (current_clip.pts_out < 0) {
422                         return;
423                 }
424                 pts_out = current_clip.pts_out;
425         }
426
427         lock_guard<mutex> lock(frame_mu);
428         auto it = upper_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts_out);
429         if (it == frames[stream_idx].end()) {
430                 return;
431         }
432         destination->setFrame(stream_idx, *it, /*interpolated=*/false);
433 }
434
435 void Player::take_queue_spot()
436 {
437         unique_lock<mutex> lock(queue_state_mu);
438         ++num_queued_frames;
439 }
440
441 void Player::release_queue_spot()
442 {
443         unique_lock<mutex> lock(queue_state_mu);
444         assert(num_queued_frames > 0);
445         --num_queued_frames;
446         new_clip_changed.notify_all();
447 }