]> git.sesse.net Git - nageru/blob - player.cpp
Do not try to show a frame until we've computed it (do it in a callback instead).
[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         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(pts, /*display_func=*/nullptr);
77                         }
78                         continue;
79                 }
80
81                 Clip clip;
82                 unsigned stream_idx;
83                 {
84                         lock_guard<mutex> lock(mu);
85                         clip = current_clip;
86                         stream_idx = current_stream_idx;
87                 }
88                 steady_clock::time_point origin = steady_clock::now();
89                 int64_t in_pts_origin = clip.pts_in;
90 got_clip:
91                 int64_t out_pts_origin = pts;
92
93                 // Start playing exactly at a frame.
94                 // TODO: Snap secondary (fade-to) clips in the same fashion
95                 // so that we don't get jank here).
96                 {
97                         lock_guard<mutex> lock(frame_mu);
98
99                         // Find the first frame such that frame.pts <= in_pts.
100                         auto it = lower_bound(frames[stream_idx].begin(),
101                                 frames[stream_idx].end(),
102                                 in_pts_origin);
103                         if (it != frames[stream_idx].end()) {
104                                 in_pts_origin = *it;
105                         }
106                 }
107
108                 // TODO: Lock to a rational multiple of the frame rate if possible.
109                 double speed = 0.5;
110
111                 int64_t in_pts_start_next_clip = -1;
112                 for (int frameno = 0; ; ++frameno) {  // Ends when the clip ends.
113                         double out_pts = out_pts_origin + TIMEBASE * frameno / output_framerate;
114                         steady_clock::time_point next_frame_start =
115                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
116                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * speed / output_framerate);
117                         pts = lrint(out_pts);
118
119                         if (in_pts >= clip.pts_out) {
120                                 break;
121                         }
122
123                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
124                         if (time_behind >= milliseconds(200)) {
125                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
126                                         lrint(1e3 * duration<double>(time_behind).count()));
127                                 continue;
128                         }
129
130                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / speed;
131                         if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
132                                 // Find the next clip so that we can begin a fade.
133                                 next_clip = next_clip_callback();
134                                 if (next_clip.pts_in != -1) {
135                                         got_next_clip = true;
136
137                                         double duration_next_clip = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
138                                         next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
139                                         in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * speed);
140                                 }
141                         }
142
143                         int primary_stream_idx = stream_idx;
144                         int secondary_stream_idx = -1;
145                         int64_t secondary_pts = -1;
146                         int64_t in_pts_secondary = -1;
147                         float fade_alpha = 0.0f;
148                         if (got_next_clip) {
149                                 secondary_stream_idx = next_clip.stream_idx;
150                                 in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * speed);
151                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
152
153                                 // If more than half-way through the fade, interpolate the next clip
154                                 // instead of the current one, since it's more visible.
155                                 if (fade_alpha >= 0.5f) {
156                                         swap(primary_stream_idx, secondary_stream_idx);
157                                         swap(in_pts, in_pts_secondary);
158                                         fade_alpha = 1.0f - fade_alpha;
159                                 }
160
161                                 int64_t in_pts_lower, in_pts_upper;
162                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &in_pts_lower, &in_pts_upper);
163                                 if (ok) {
164                                         secondary_pts = in_pts_lower;
165                                 } else {
166                                         secondary_stream_idx = -1;
167                                 }
168                         }
169
170                         if (progress_callback != nullptr) {
171                                 // NOTE: None of this will take into account any snapping done below.
172                                 double played_this_clip = double(in_pts - clip.pts_in) / TIMEBASE / speed;
173                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / speed;
174                                 progress_callback(played_this_clip, total_length);
175                         }
176
177                         int64_t in_pts_lower, in_pts_upper;
178                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &in_pts_lower, &in_pts_upper);
179                         if (!ok) {
180                                 break;
181                         }
182
183                         // Sleep until the next frame start, or until there's a new clip we're supposed to play.
184                         {
185                                 unique_lock<mutex> lock(queue_state_mu);
186                                 new_clip_changed.wait_until(lock, next_frame_start, [this]{
187                                         return new_clip_ready || override_stream_idx != -1;
188                                 });
189                                 if (new_clip_ready) {
190                                         goto wait_for_clip;
191                                 }
192                                 if (override_stream_idx != -1) {
193                                         stream_idx = override_stream_idx;
194                                         override_stream_idx = -1;
195                                         continue;
196                                 }
197                         }
198
199                         if (in_pts_lower == in_pts_upper) {
200                                 auto display_func = [this, primary_stream_idx, in_pts_lower, secondary_stream_idx, secondary_pts, fade_alpha]{
201                                         destination->setFrame(primary_stream_idx, in_pts_lower, /*interpolated=*/false, secondary_stream_idx, secondary_pts, fade_alpha);
202                                 };
203                                 if (video_stream == nullptr) {
204                                         display_func();
205                                 } else {
206                                         if (secondary_stream_idx == -1) {
207                                                 video_stream->schedule_original_frame(pts, display_func, primary_stream_idx, in_pts_lower);
208                                         } else {
209                                                 video_stream->schedule_faded_frame(pts, display_func, primary_stream_idx, in_pts_lower, secondary_stream_idx, secondary_pts, fade_alpha);
210                                         }
211                                 }
212                                 continue;
213                         }
214
215                         // Snap to input frame: If we can do so with less than 1% jitter
216                         // (ie., move less than 1% of an _output_ frame), do so.
217                         // TODO: Snap secondary (fade-to) clips in the same fashion.
218                         bool snapped = false;
219                         for (int64_t snap_pts : { in_pts_lower, in_pts_upper }) {
220                                 double snap_pts_as_frameno = (snap_pts - in_pts_origin) * output_framerate / TIMEBASE / speed;
221                                 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
222                                         auto display_func = [this, primary_stream_idx, snap_pts, secondary_stream_idx, secondary_pts, fade_alpha]{
223                                                 destination->setFrame(primary_stream_idx, snap_pts, /*interpolated=*/false, secondary_stream_idx, secondary_pts, fade_alpha);
224                                         };
225                                         if (video_stream == nullptr) {
226                                                 display_func();
227                                         } else {
228                                                 if (secondary_stream_idx == -1) {
229                                                         video_stream->schedule_original_frame(pts, display_func, primary_stream_idx, snap_pts);
230                                                 } else {
231                                                         video_stream->schedule_faded_frame(pts, display_func, primary_stream_idx, snap_pts, secondary_stream_idx, secondary_pts, fade_alpha);
232                                                 }
233                                         }
234                                         in_pts_origin += snap_pts - in_pts;
235                                         snapped = true;
236                                         break;
237                                 }
238                         }
239                         if (snapped) {
240                                 continue;
241                         }
242
243                         if (time_behind >= milliseconds(100)) {
244                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
245                                         lrint(1e3 * duration<double>(time_behind).count()));
246                                 continue;
247                         }
248
249                         double alpha = double(in_pts - in_pts_lower) / (in_pts_upper - in_pts_lower);
250
251                         if (video_stream == nullptr) {
252                                 // Previews don't do any interpolation.
253                                 assert(secondary_stream_idx == -1);
254                                 destination->setFrame(primary_stream_idx, in_pts_lower, /*interpolated=*/false);
255                         } else {
256                                 // Calculate the interpolated frame. When it's done, the destination
257                                 // will be unblocked.
258                                 auto display_func = [this, primary_stream_idx, pts, secondary_stream_idx, secondary_pts, fade_alpha]{
259                                         destination->setFrame(primary_stream_idx, pts, /*interpolated=*/true, secondary_stream_idx, secondary_pts, fade_alpha);
260                                 };
261                                 video_stream->schedule_interpolated_frame(pts, display_func, primary_stream_idx, in_pts_lower, in_pts_upper, alpha, secondary_stream_idx, secondary_pts, fade_alpha);
262                         }
263                 }
264
265                 // The clip ended.
266
267                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
268                 if (!got_next_clip && next_clip_callback != nullptr) {
269                         next_clip = next_clip_callback();
270                         if (next_clip.pts_in != -1) {
271                                 got_next_clip = true;
272                                 in_pts_start_next_clip = next_clip.pts_in;
273                         }
274                 }
275
276                 // Switch to next clip if we got it.
277                 if (got_next_clip) {
278                         clip = next_clip;
279                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
280                         if (done_callback != nullptr) {
281                                 done_callback();
282                         }
283                         got_next_clip = false;
284
285                         // Start the next clip from the point where the fade went out.
286                         origin = steady_clock::now();
287                         in_pts_origin = in_pts_start_next_clip;
288                         goto got_clip;
289                 }
290
291                 {
292                         unique_lock<mutex> lock(queue_state_mu);
293                         playing = false;
294                 }
295                 if (done_callback != nullptr) {
296                         done_callback();
297                 }
298         }
299 }
300
301 // Find the frame immediately before and after this point.
302 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, int64_t *pts_lower, int64_t *pts_upper)
303 {
304         lock_guard<mutex> lock(frame_mu);
305
306         // Find the first frame such that frame.pts >= pts.
307         auto it = lower_bound(frames[stream_idx].begin(),
308                 frames[stream_idx].end(),
309                 pts);
310         if (it == frames[stream_idx].end()) {
311                 return false;
312         }
313         *pts_upper = *it;
314
315         // Find the last frame such that in_pts <= frame.pts (if any).
316         if (it == frames[stream_idx].begin()) {
317                 *pts_lower = *it;
318         } else {
319                 *pts_lower = *(it - 1);
320         }
321         assert(pts >= *pts_lower);
322         assert(pts <= *pts_upper);
323         return true;
324 }
325
326 Player::Player(JPEGFrameView *destination, bool also_output_to_stream)
327         : destination(destination)
328 {
329         thread(&Player::thread_func, this, also_output_to_stream).detach();
330 }
331
332 void Player::play_clip(const Clip &clip, unsigned stream_idx)
333 {
334         {
335                 lock_guard<mutex> lock(mu);
336                 current_clip = clip;
337                 current_stream_idx = stream_idx;
338         }
339
340         {
341                 lock_guard<mutex> lock(queue_state_mu);
342                 new_clip_ready = true;
343                 override_stream_idx = -1;
344                 new_clip_changed.notify_all();
345         }
346 }
347
348 void Player::override_angle(unsigned stream_idx)
349 {
350         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
351         {
352                 unique_lock<mutex> lock(queue_state_mu);
353                 if (new_clip_ready) {
354                         lock_guard<mutex> lock2(mu);
355                         current_stream_idx = stream_idx;
356                         return;
357                 }
358         }
359
360         // If we are playing a clip, set override_stream_idx, and the player thread will
361         // pick it up and change its internal index.
362         {
363                 unique_lock<mutex> lock(queue_state_mu);
364                 if (playing) {
365                         override_stream_idx = stream_idx;
366                         new_clip_changed.notify_all();
367                 }
368         }
369
370         // OK, so we're standing still, presumably at the end of a clip.
371         // Look at the current pts_out (if it exists), and show the closest
372         // thing we've got.
373         int64_t pts_out;
374         {
375                 lock_guard<mutex> lock(mu);
376                 if (current_clip.pts_out < 0) {
377                         return;
378                 }
379                 pts_out = current_clip.pts_out;
380         }
381
382         lock_guard<mutex> lock(frame_mu);
383         auto it = upper_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts_out);
384         if (it == frames[stream_idx].end()) {
385                 return;
386         }
387         destination->setFrame(stream_idx, *it, /*interpolated=*/false);
388 }