]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
e20a43cc26bf84fe920ac9dff3b2892d96ee6644
[nageru] / futatabi / player.cpp
1 #include "player.h"
2
3 #include "clip_list.h"
4 #include "shared/context.h"
5 #include "defs.h"
6 #include "shared/ffmpeg_raii.h"
7 #include "flags.h"
8 #include "frame_on_disk.h"
9 #include "shared/httpd.h"
10 #include "jpeg_frame_view.h"
11 #include "shared/mux.h"
12 #include "shared/timebase.h"
13 #include "video_stream.h"
14
15 #include <algorithm>
16 #include <chrono>
17 #include <condition_variable>
18 #include <movit/util.h>
19 #include <mutex>
20 #include <stdio.h>
21 #include <thread>
22 #include <vector>
23
24 using namespace std;
25 using namespace std::chrono;
26
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         size_t next_clip_idx = size_t(-1);
54         bool got_next_clip = false;
55         double next_clip_fade_time = -1.0;
56
57         while (!should_quit) {
58 wait_for_clip:
59                 bool clip_ready;
60                 steady_clock::time_point before_sleep = steady_clock::now();
61
62                 // Wait until we're supposed to play something.
63                 {
64                         unique_lock<mutex> lock(queue_state_mu);
65                         clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
66                                 return should_quit || (new_clip_ready && current_clip.pts_in != -1);
67                         });
68                         if (should_quit) {
69                                 return;
70                         }
71                         new_clip_ready = false;
72                         playing = true;
73                 }
74
75                 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
76                 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
77
78                 if (!clip_ready) {
79                         if (video_stream != nullptr) {
80                                 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
81                         }
82                         continue;
83                 }
84
85                 Clip clip;
86                 size_t clip_idx;
87                 unsigned stream_idx;
88                 {
89                         lock_guard<mutex> lock(mu);
90                         clip = current_clip;
91                         clip_idx = current_clip_idx;
92                         stream_idx = current_stream_idx;
93                 }
94                 steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
95                 int64_t in_pts_origin = clip.pts_in;
96 got_clip:
97                 int64_t out_pts_origin = pts;
98
99                 // Start playing exactly at a frame.
100                 // TODO: Snap secondary (fade-to) clips in the same fashion
101                 // so that we don't get jank here).
102                 {
103                         lock_guard<mutex> lock(frame_mu);
104
105                         // Find the first frame such that frame.pts <= in_pts.
106                         auto it = lower_bound(frames[stream_idx].begin(),
107                                 frames[stream_idx].end(),
108                                 in_pts_origin,
109                                 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
110                         if (it != frames[stream_idx].end()) {
111                                 in_pts_origin = it->pts;
112                         }
113                 }
114
115                 // TODO: Lock to a rational multiple of the frame rate if possible.
116                 double speed = 0.5;
117
118                 int64_t in_pts_start_next_clip = -1;
119                 steady_clock::time_point next_frame_start;
120                 for (int frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
121                         double out_pts = out_pts_origin + TIMEBASE * frameno / output_framerate;
122                         next_frame_start =
123                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
124                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * speed / output_framerate);
125                         pts = lrint(out_pts);
126
127                         if (in_pts >= clip.pts_out) {
128                                 break;
129                         }
130
131                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
132                         if (time_behind >= milliseconds(200)) {
133                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
134                                         lrint(1e3 * duration<double>(time_behind).count()));
135                                 continue;
136                         }
137
138                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / speed;
139                         if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
140                                 // Find the next clip so that we can begin a fade.
141                                 tie(next_clip, next_clip_idx) = next_clip_callback();
142                                 if (next_clip.pts_in != -1) {
143                                         got_next_clip = true;
144
145                                         double duration_next_clip = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
146                                         next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
147                                         in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * speed);
148                                 }
149                         }
150
151                         // pts not affected by the swapping below.
152                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
153
154                         int primary_stream_idx = stream_idx;
155                         FrameOnDisk secondary_frame;
156                         int secondary_stream_idx = -1;
157                         float fade_alpha = 0.0f;
158                         if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
159                                 secondary_stream_idx = next_clip.stream_idx;
160                                 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * speed);
161                                 in_pts_secondary_for_progress = in_pts_secondary;
162                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
163
164                                 // If more than half-way through the fade, interpolate the next clip
165                                 // instead of the current one, since it's more visible.
166                                 if (fade_alpha >= 0.5f) {
167                                         swap(primary_stream_idx, secondary_stream_idx);
168                                         swap(in_pts, in_pts_secondary);
169                                         fade_alpha = 1.0f - fade_alpha;
170                                 }
171
172                                 FrameOnDisk frame_lower, frame_upper;
173                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
174                                 if (ok) {
175                                         secondary_frame = frame_lower;
176                                 }
177                         }
178
179                         if (progress_callback != nullptr) {
180                                 // NOTE: None of this will take into account any snapping done below.
181                                 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / speed;
182                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / speed;
183                                 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
184
185                                 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
186                                         double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / speed;
187                                         double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / speed;
188                                         progress[next_clip_idx] = played_next_clip / total_next_length;
189                                 }
190                                 progress_callback(progress);
191                         }
192
193                         FrameOnDisk frame_lower, frame_upper;
194                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
195                         if (!ok) {
196                                 break;
197                         }
198
199                         {
200                                 unique_lock<mutex> lock(queue_state_mu);
201                                 if (video_stream == nullptr) {
202                                         // No queue, just wait until the right time and then show the frame.
203                                         new_clip_changed.wait_until(lock, next_frame_start, [this]{
204                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
205                                         });
206                                 if (should_quit) {
207                                         return;
208                                 }
209                                 } else {
210                                         // If the queue is full (which is really the state we'd like to be in),
211                                         // wait until there's room for one more frame (ie., one was output from
212                                         // VideoStream), or until or until there's a new clip we're supposed to play.
213                                         //
214                                         // In this case, we don't sleep until next_frame_start; the displaying is
215                                         // done by the queue.
216                                         new_clip_changed.wait(lock, [this]{
217                                                 if (num_queued_frames < max_queued_frames) {
218                                                         return true;
219                                                 }
220                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
221                                         });
222                                 }
223                                 if (should_quit) {
224                                         return;
225                                 }
226                                 if (new_clip_ready) {
227                                         if (video_stream != nullptr) {
228                                                 lock.unlock();  // Urg.
229                                                 video_stream->clear_queue();
230                                                 lock.lock();
231                                         }
232                                         got_next_clip = false;
233                                         goto wait_for_clip;
234                                 }
235                                 if (override_stream_idx != -1) {
236                                         stream_idx = override_stream_idx;
237                                         override_stream_idx = -1;
238                                         continue;
239                                 }
240                         }
241
242                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
243                                 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
244                                         destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
245                                 };
246                                 if (video_stream == nullptr) {
247                                         display_func();
248                                 } else {
249                                         if (secondary_stream_idx == -1) {
250                                                 video_stream->schedule_original_frame(
251                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
252                                                         frame_lower);
253                                         } else {
254                                                 assert(secondary_frame.pts != -1);
255                                                 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
256                                                         QueueSpotHolder(this), frame_lower,
257                                                         secondary_frame, fade_alpha);
258                                         }
259                                 }
260                                 continue;
261                         }
262
263                         // Snap to input frame: If we can do so with less than 1% jitter
264                         // (ie., move less than 1% of an _output_ frame), do so.
265                         // TODO: Snap secondary (fade-to) clips in the same fashion.
266                         bool snapped = false;
267                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
268                                 double snap_pts_as_frameno = (snap_frame.pts - in_pts_origin) * output_framerate / TIMEBASE / speed;
269                                 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
270                                         auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
271                                                 destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
272                                         };
273                                         if (video_stream == nullptr) {
274                                                 display_func();
275                                         } else {
276                                                 if (secondary_stream_idx == -1) {
277                                                         video_stream->schedule_original_frame(
278                                                                 next_frame_start, pts, display_func,
279                                                                 QueueSpotHolder(this), snap_frame);
280                                                 } else {
281                                                         assert(secondary_frame.pts != -1);
282                                                         video_stream->schedule_faded_frame(
283                                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
284                                                                 snap_frame, secondary_frame, fade_alpha);
285                                                 }
286                                         }
287                                         in_pts_origin += snap_frame.pts - in_pts;
288                                         snapped = true;
289                                         break;
290                                 }
291                         }
292                         if (snapped) {
293                                 continue;
294                         }
295
296                         if (time_behind >= milliseconds(100)) {
297                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
298                                         lrint(1e3 * duration<double>(time_behind).count()));
299                                 continue;
300                         }
301
302                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
303
304                         if (video_stream == nullptr) {
305                                 // Previews don't do any interpolation.
306                                 assert(secondary_stream_idx == -1);
307                                 destination->setFrame(primary_stream_idx, frame_lower);
308                         } else {
309                                 auto display_func = [this](shared_ptr<Frame> frame) {
310                                         destination->setFrame(frame);
311                                 };
312                                 video_stream->schedule_interpolated_frame(
313                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
314                                         frame_lower, frame_upper, alpha,
315                                         secondary_frame, fade_alpha);
316                         }
317                 }
318
319                 if (should_quit) {
320                         return;
321                 }
322
323                 // The clip ended.
324
325                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
326                 if (!got_next_clip && next_clip_callback != nullptr) {
327                         tie(next_clip, next_clip_idx) = next_clip_callback();
328                         if (next_clip.pts_in != -1) {
329                                 got_next_clip = true;
330                                 in_pts_start_next_clip = next_clip.pts_in;
331                         }
332                 }
333
334                 // Switch to next clip if we got it.
335                 if (got_next_clip) {
336                         clip = next_clip;
337                         clip_idx = next_clip_idx;
338                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
339                         if (done_callback != nullptr) {
340                                 done_callback();
341                         }
342                         got_next_clip = false;
343
344                         // Start the next clip from the point where the fade went out.
345                         origin = next_frame_start;
346                         in_pts_origin = in_pts_start_next_clip;
347                         goto got_clip;
348                 }
349
350                 {
351                         unique_lock<mutex> lock(queue_state_mu);
352                         playing = false;
353                 }
354                 if (done_callback != nullptr) {
355                         done_callback();
356                 }
357         }
358 }
359
360 // Find the frame immediately before and after this point.
361 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
362 {
363         lock_guard<mutex> lock(frame_mu);
364
365         // Find the first frame such that frame.pts >= pts.
366         auto it = lower_bound(frames[stream_idx].begin(),
367                 frames[stream_idx].end(),
368                 pts,
369                 [](const FrameOnDisk &frame, int64_t pts) { return frame.pts < pts; });
370         if (it == frames[stream_idx].end()) {
371                 return false;
372         }
373         *frame_upper = *it;
374
375         // Find the last frame such that in_pts <= frame.pts (if any).
376         if (it == frames[stream_idx].begin()) {
377                 *frame_lower = *it;
378         } else {
379                 *frame_lower = *(it - 1);
380         }
381         assert(pts >= frame_lower->pts);
382         assert(pts <= frame_upper->pts);
383         return true;
384 }
385
386 Player::Player(JPEGFrameView *destination, bool also_output_to_stream)
387         : destination(destination)
388 {
389         player_thread = thread(&Player::thread_func, this, also_output_to_stream);
390 }
391
392 Player::~Player()
393 {
394         should_quit = true;
395         if (video_stream != nullptr) {
396                 video_stream->stop();
397         }
398         new_clip_changed.notify_all();
399         player_thread.join();
400 }
401
402 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
403 {
404         {
405                 lock_guard<mutex> lock(mu);
406                 current_clip = clip;
407                 current_stream_idx = stream_idx;
408                 current_clip_idx = clip_idx;
409         }
410
411         {
412                 lock_guard<mutex> lock(queue_state_mu);
413                 new_clip_ready = true;
414                 override_stream_idx = -1;
415                 new_clip_changed.notify_all();
416         }
417 }
418
419 void Player::override_angle(unsigned stream_idx)
420 {
421         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
422         {
423                 unique_lock<mutex> lock(queue_state_mu);
424                 if (new_clip_ready) {
425                         lock_guard<mutex> lock2(mu);
426                         current_stream_idx = stream_idx;
427                         return;
428                 }
429         }
430
431         // If we are playing a clip, set override_stream_idx, and the player thread will
432         // pick it up and change its internal index.
433         {
434                 unique_lock<mutex> lock(queue_state_mu);
435                 if (playing) {
436                         override_stream_idx = stream_idx;
437                         new_clip_changed.notify_all();
438                 }
439         }
440
441         // OK, so we're standing still, presumably at the end of a clip.
442         // Look at the current pts_out (if it exists), and show the closest
443         // thing we've got.
444         int64_t pts_out;
445         {
446                 lock_guard<mutex> lock(mu);
447                 if (current_clip.pts_out < 0) {
448                         return;
449                 }
450                 pts_out = current_clip.pts_out;
451         }
452
453         lock_guard<mutex> lock(frame_mu);
454         auto it = upper_bound(frames[stream_idx].begin(), frames[stream_idx].end(), pts_out,
455                 [](int64_t pts, const FrameOnDisk &frame) { return pts < frame.pts; });
456         if (it == frames[stream_idx].end()) {
457                 return;
458         }
459         destination->setFrame(stream_idx, *it);
460 }
461
462 void Player::take_queue_spot()
463 {
464         unique_lock<mutex> lock(queue_state_mu);
465         ++num_queued_frames;
466 }
467
468 void Player::release_queue_spot()
469 {
470         unique_lock<mutex> lock(queue_state_mu);
471         assert(num_queued_frames > 0);
472         --num_queued_frames;
473         new_clip_changed.notify_all();
474 }