]> git.sesse.net Git - nageru/blob - player.cpp
Fix fades that are not between clips with the same start pts.
[nageru] / player.cpp
1 #include <algorithm>
2 #include <chrono>
3 #include <condition_variable>
4 #include <mutex>
5 #include <thread>
6 #include <vector>
7
8 #include <stdio.h>
9
10 #include <movit/util.h>
11
12 #include "clip_list.h"
13 #include "context.h"
14 #include "defs.h"
15 #include "ffmpeg_raii.h"
16 #include "httpd.h"
17 #include "jpeg_frame_view.h"
18 #include "mux.h"
19 #include "player.h"
20 #include "timebase.h"
21 #include "video_stream.h"
22
23 using namespace std;
24 using namespace std::chrono;
25
26 extern mutex frame_mu;
27 extern vector<int64_t> frames[MAX_STREAMS];
28 extern HTTPD *global_httpd;
29
30 void Player::thread_func(bool also_output_to_stream)
31 {
32         pthread_setname_np(pthread_self(), "Player");
33
34         QSurface *surface = create_surface();
35         QOpenGLContext *context = create_context(surface);
36         if (!make_current(context, surface)) {
37                 printf("oops\n");
38                 exit(1);
39         }
40
41         check_error();
42
43         // Create the VideoStream object, now that we have an OpenGL context.
44         if (also_output_to_stream) {
45                 video_stream.reset(new VideoStream);
46                 video_stream->start();
47         }
48         
49         check_error();
50
51         constexpr double output_framerate = 60000.0 / 1001.0;  // FIXME: make configurable
52         int64_t pts = 0;
53         Clip next_clip;
54         bool got_next_clip = false;
55         double next_clip_fade_time = -1.0;
56
57         for ( ;; ) {
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);
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                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
120                         if (time_behind >= milliseconds(200)) {
121                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
122                                         lrint(1e3 * duration<double>(time_behind).count()));
123                                 continue;
124                         }
125
126                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / speed;
127                         if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
128                                 // Find the next clip so that we can begin a fade.
129                                 next_clip = next_clip_callback();
130                                 if (next_clip.pts_in != -1) {
131                                         got_next_clip = true;
132
133                                         double duration_next_clip = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
134                                         next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
135                                         in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * speed);
136                                 }
137                         }
138
139                         int primary_stream_idx = stream_idx;
140                         int secondary_stream_idx = -1;
141                         float fade_alpha = 0.0f;
142                         if (got_next_clip) {
143                                 secondary_stream_idx = next_clip.stream_idx;
144                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
145
146                                 // If more than half-way through the fade, interpolate the next clip
147                                 // instead of the current one, since it's more visible.
148                                 if (fade_alpha >= 0.5f) {
149                                         swap(primary_stream_idx, secondary_stream_idx);
150                                         fade_alpha = 1.0f - fade_alpha;
151                                 }
152                         }
153
154                         int64_t secondary_pts = -1;
155                         if (got_next_clip) {
156                                 int64_t in_pts_secondary = lrint(next_clip.pts_in + TIMEBASE * frameno * speed / output_framerate);
157                                 int64_t in_pts_lower, in_pts_upper;
158                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &in_pts_lower, &in_pts_upper);
159                                 if (ok) {
160                                         secondary_pts = in_pts_lower;
161                                 } else {
162                                         secondary_stream_idx = -1;
163                                 }
164                         }
165
166                         if (progress_callback != nullptr) {
167                                 // NOTE: None of this will take into account any snapping done below.
168                                 double played_this_clip = double(in_pts - clip.pts_in) / TIMEBASE / speed;
169                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / speed;
170                                 progress_callback(played_this_clip, total_length);
171                         }
172
173                         int64_t in_pts_lower, in_pts_upper;
174                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &in_pts_lower, &in_pts_upper);
175                         if (!ok || in_pts_upper >= clip.pts_out) {
176                                 break;
177                         }
178
179                         // Sleep until the next frame start, or until there's a new clip we're supposed to play.
180                         {
181                                 unique_lock<mutex> lock(queue_state_mu);
182                                 new_clip_changed.wait_until(lock, next_frame_start, [this]{
183                                         return new_clip_ready || override_stream_idx != -1;
184                                 });
185                                 if (new_clip_ready) break;
186                                 if (override_stream_idx != -1) {
187                                         stream_idx = override_stream_idx;
188                                         override_stream_idx = -1;
189                                         continue;
190                                 }
191                         }
192
193                         if (in_pts_lower == in_pts_upper) {
194                                 destination->setFrame(primary_stream_idx, in_pts_lower, /*interpolated=*/false, secondary_stream_idx, secondary_pts, fade_alpha);
195                                 if (video_stream != nullptr) {
196                                         if (secondary_stream_idx == -1) {
197                                                 video_stream->schedule_original_frame(pts, primary_stream_idx, in_pts_lower);
198                                         } else {
199                                                 video_stream->schedule_faded_frame(pts, primary_stream_idx, in_pts_lower, secondary_stream_idx, secondary_pts, fade_alpha);
200                                         }
201                                 }
202                                 continue;
203                         }
204
205                         // Snap to input frame: If we can do so with less than 1% jitter
206                         // (ie., move less than 1% of an _output_ frame), do so.
207                         // TODO: Snap secondary (fade-to) clips in the same fashion.
208                         bool snapped = false;
209                         for (int64_t snap_pts : { in_pts_lower, in_pts_upper }) {
210                                 double snap_pts_as_frameno = (snap_pts - in_pts_origin) * output_framerate / TIMEBASE / speed;
211                                 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
212                                         destination->setFrame(primary_stream_idx, snap_pts, /*interpolated=*/false, secondary_stream_idx, secondary_pts, fade_alpha);
213                                         if (video_stream != nullptr) {
214                                                 if (secondary_stream_idx == -1) {
215                                                         video_stream->schedule_original_frame(pts, primary_stream_idx, snap_pts);
216                                                 } else {
217                                                         video_stream->schedule_faded_frame(pts, primary_stream_idx, snap_pts, secondary_stream_idx, secondary_pts, fade_alpha);
218                                                 }
219                                         }
220                                         in_pts_origin += snap_pts - in_pts;
221                                         snapped = true;
222                                         break;
223                                 }
224                         }
225                         if (snapped) {
226                                 continue;
227                         }
228
229                         if (time_behind >= milliseconds(100)) {
230                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
231                                         lrint(1e3 * duration<double>(time_behind).count()));
232                                 continue;
233                         }
234
235                         double alpha = double(in_pts - in_pts_lower) / (in_pts_upper - in_pts_lower);
236
237                         if (video_stream == nullptr) {
238                                 // Previews don't do any interpolation.
239                                 assert(secondary_stream_idx == -1);
240                                 destination->setFrame(primary_stream_idx, in_pts_lower, /*interpolated=*/false);
241                         } else {
242                                 // Calculate the interpolated frame. When it's done, the destination
243                                 // will be unblocked.
244                                 destination->setFrame(primary_stream_idx, pts, /*interpolated=*/true, secondary_stream_idx, secondary_pts, fade_alpha);
245                                 video_stream->schedule_interpolated_frame(pts, primary_stream_idx, in_pts_lower, in_pts_upper, alpha, secondary_stream_idx, secondary_pts, fade_alpha);
246                         }
247                 }
248
249                 // The clip ended.
250
251                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
252                 if (!got_next_clip && next_clip_callback != nullptr) {
253                         next_clip = next_clip_callback();
254                         if (next_clip.pts_in != -1) {
255                                 got_next_clip = true;
256                                 in_pts_start_next_clip = next_clip.pts_in;
257                         }
258                 }
259
260                 // Switch to next clip if we got it.
261                 if (got_next_clip) {
262                         clip = next_clip;
263                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
264                         if (done_callback != nullptr) {
265                                 done_callback();
266                         }
267                         got_next_clip = false;
268
269                         // Start the next clip from the point where the fade went out.
270                         origin = steady_clock::now();
271                         in_pts_origin = in_pts_start_next_clip;
272                         goto got_clip;
273                 }
274
275                 {
276                         unique_lock<mutex> lock(queue_state_mu);
277                         playing = false;
278                 }
279                 if (done_callback != nullptr) {
280                         done_callback();
281                 }
282         }
283 }
284
285 // Find the frame immediately before and after this point.
286 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, int64_t *pts_lower, int64_t *pts_upper)
287 {
288         lock_guard<mutex> lock(frame_mu);
289
290         // Find the first frame such that frame.pts >= pts.
291         auto it = lower_bound(frames[stream_idx].begin(),
292                 frames[stream_idx].end(),
293                 pts);
294         if (it == frames[stream_idx].end()) {
295                 return false;
296         }
297         *pts_upper = *it;
298
299         // Find the last frame such that in_pts <= frame.pts (if any).
300         if (it == frames[stream_idx].begin()) {
301                 *pts_lower = *it;
302         } else {
303                 *pts_lower = *(it - 1);
304         }
305         assert(pts >= *pts_lower);
306         assert(pts <= *pts_upper);
307         return true;
308 }
309
310 Player::Player(JPEGFrameView *destination, bool also_output_to_stream)
311         : destination(destination)
312 {
313         thread(&Player::thread_func, this, also_output_to_stream).detach();
314 }
315
316 void Player::play_clip(const Clip &clip, unsigned stream_idx)
317 {
318         {
319                 lock_guard<mutex> lock(mu);
320                 current_clip = clip;
321                 current_stream_idx = stream_idx;
322         }
323
324         {
325                 lock_guard<mutex> lock(queue_state_mu);
326                 new_clip_ready = true;
327                 override_stream_idx = -1;
328                 new_clip_changed.notify_all();
329         }
330 }
331
332 void Player::override_angle(unsigned stream_idx)
333 {
334         // Corner case: If a new clip is waiting to be played, change its stream and then we're done. 
335         {
336                 unique_lock<mutex> lock(queue_state_mu);
337                 if (new_clip_ready) {
338                         lock_guard<mutex> lock2(mu);
339                         current_stream_idx = stream_idx;
340                         return;
341                 }
342         }
343
344         // If we are playing a clip, set override_stream_idx, and the player thread will
345         // pick it up and change its internal index.
346         {
347                 unique_lock<mutex> lock(queue_state_mu);
348                 if (playing) {
349                         override_stream_idx = stream_idx;
350                         new_clip_changed.notify_all();
351                 }
352         }
353
354         // OK, so we're standing still, presumably at the end of a clip.
355         // Look at the current pts_out (if it exists), and show the closest
356         // thing we've got.
357         int64_t pts_out;
358         {
359                 lock_guard<mutex> lock(mu);
360                 if (current_clip.pts_out < 0) {
361                         return;
362                 }
363                 pts_out = current_clip.pts_out;
364         }
365                         
366         lock_guard<mutex> lock(frame_mu);
367         auto it = upper_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts_out);
368         if (it == frames[stream_idx].end()) {
369                 return;
370         }
371         destination->setFrame(stream_idx, *it, /*interpolated=*/false);
372 }