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