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