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