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