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