]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
Support per-clip variable speed.
[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(Player::StreamOutput stream_output, AVFormatContext *file_avctx)
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 (stream_output != NO_STREAM_OUTPUT) {
44                 video_stream.reset(new VideoStream(file_avctx));
45                 video_stream->start();
46         }
47
48         check_error();
49
50         int64_t pts = 0;
51         Clip next_clip;
52         size_t next_clip_idx = size_t(-1);
53         bool got_next_clip = false;
54         double next_clip_fade_time = -1.0;
55
56         while (!should_quit) {
57 wait_for_clip:
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 should_quit || (new_clip_ready && current_clip.pts_in != -1);
66                         });
67                         if (should_quit) {
68                                 return;
69                         }
70                         new_clip_ready = false;
71                         playing = true;
72                 }
73
74                 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
75                 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
76
77                 if (!clip_ready) {
78                         if (video_stream != nullptr) {
79                                 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
80                         }
81                         continue;
82                 }
83
84                 Clip clip;
85                 size_t clip_idx;
86                 unsigned stream_idx;
87                 {
88                         lock_guard<mutex> lock(mu);
89                         clip = current_clip;
90                         clip_idx = current_clip_idx;
91                         stream_idx = current_stream_idx;
92                 }
93                 steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
94                 int64_t in_pts_origin = clip.pts_in;
95 got_clip:
96                 int64_t out_pts_origin = pts;
97
98                 // Start playing exactly at a frame.
99                 // TODO: Snap secondary (fade-to) clips in the same fashion
100                 // so that we don't get jank here).
101                 {
102                         lock_guard<mutex> lock(frame_mu);
103
104                         // Find the first frame such that frame.pts <= in_pts.
105                         auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
106                         if (it != frames[stream_idx].end()) {
107                                 in_pts_origin = it->pts;
108                         }
109                 }
110
111                 // TODO: Lock the speed to a rational multiple of the frame rate if possible.
112
113                 int64_t in_pts_start_next_clip = -1;
114                 steady_clock::time_point next_frame_start;
115                 for (int frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
116                         double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
117                         next_frame_start =
118                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
119                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
120                         pts = lrint(out_pts);
121
122                         if (in_pts >= clip.pts_out) {
123                                 break;
124                         }
125
126                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
127                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
128                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
129                                         lrint(1e3 * duration<double>(time_behind).count()));
130                                 continue;
131                         }
132
133                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
134                         if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
135                                 // Find the next clip so that we can begin a fade.
136                                 tie(next_clip, next_clip_idx) = next_clip_callback();
137                                 if (next_clip.pts_in != -1) {
138                                         got_next_clip = true;
139
140                                         double duration_next_clip = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / clip.speed;
141                                         next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
142                                         in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
143                                 }
144                         }
145
146                         // pts not affected by the swapping below.
147                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
148
149                         int primary_stream_idx = stream_idx;
150                         FrameOnDisk secondary_frame;
151                         int secondary_stream_idx = -1;
152                         float fade_alpha = 0.0f;
153                         if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
154                                 secondary_stream_idx = next_clip.stream_idx;
155                                 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
156                                 in_pts_secondary_for_progress = in_pts_secondary;
157                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
158
159                                 // If more than half-way through the fade, interpolate the next clip
160                                 // instead of the current one, since it's more visible.
161                                 if (fade_alpha >= 0.5f) {
162                                         swap(primary_stream_idx, secondary_stream_idx);
163                                         swap(in_pts, in_pts_secondary);
164                                         fade_alpha = 1.0f - fade_alpha;
165                                 }
166
167                                 FrameOnDisk frame_lower, frame_upper;
168                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
169                                 if (ok) {
170                                         secondary_frame = frame_lower;
171                                 }
172                         }
173
174                         if (progress_callback != nullptr) {
175                                 // NOTE: None of this will take into account any snapping done below.
176                                 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / clip.speed;
177                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
178                                 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
179
180                                 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
181                                         double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / next_clip.speed;
182                                         double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / next_clip.speed;
183                                         progress[next_clip_idx] = played_next_clip / total_next_length;
184                                 }
185                                 progress_callback(progress);
186                         }
187
188                         FrameOnDisk frame_lower, frame_upper;
189                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
190                         if (!ok) {
191                                 break;
192                         }
193
194                         {
195                                 unique_lock<mutex> lock(queue_state_mu);
196                                 if (video_stream == nullptr) {
197                                         // No queue, just wait until the right time and then show the frame.
198                                         new_clip_changed.wait_until(lock, next_frame_start, [this]{
199                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
200                                         });
201                                 if (should_quit) {
202                                         return;
203                                 }
204                                 } else {
205                                         // If the queue is full (which is really the state we'd like to be in),
206                                         // wait until there's room for one more frame (ie., one was output from
207                                         // VideoStream), or until or until there's a new clip we're supposed to play.
208                                         //
209                                         // In this case, we don't sleep until next_frame_start; the displaying is
210                                         // done by the queue.
211                                         new_clip_changed.wait(lock, [this]{
212                                                 if (num_queued_frames < max_queued_frames) {
213                                                         return true;
214                                                 }
215                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
216                                         });
217                                 }
218                                 if (should_quit) {
219                                         return;
220                                 }
221                                 if (new_clip_ready) {
222                                         if (video_stream != nullptr) {
223                                                 lock.unlock();  // Urg.
224                                                 video_stream->clear_queue();
225                                                 lock.lock();
226                                         }
227                                         got_next_clip = false;
228                                         goto wait_for_clip;
229                                 }
230                                 if (override_stream_idx != -1) {
231                                         stream_idx = override_stream_idx;
232                                         override_stream_idx = -1;
233                                         continue;
234                                 }
235                         }
236
237                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
238                                 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
239                                         if (destination != nullptr) {
240                                                 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
241                                         }
242                                 };
243                                 if (video_stream == nullptr) {
244                                         display_func();
245                                 } else {
246                                         if (secondary_stream_idx == -1) {
247                                                 video_stream->schedule_original_frame(
248                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
249                                                         frame_lower);
250                                         } else {
251                                                 assert(secondary_frame.pts != -1);
252                                                 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
253                                                         QueueSpotHolder(this), frame_lower,
254                                                         secondary_frame, fade_alpha);
255                                         }
256                                 }
257                                 continue;
258                         }
259
260                         // Snap to input frame: If we can do so with less than 1% jitter
261                         // (ie., move less than 1% of an _output_ frame), do so.
262                         // TODO: Snap secondary (fade-to) clips in the same fashion.
263                         bool snapped = false;
264                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
265                                 double snap_pts_as_frameno = (snap_frame.pts - in_pts_origin) * global_flags.output_framerate / TIMEBASE / clip.speed;
266                                 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
267                                         auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
268                                                 if (destination != nullptr) {
269                                                         destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
270                                                 }
271                                         };
272                                         if (video_stream == nullptr) {
273                                                 display_func();
274                                         } else {
275                                                 if (secondary_stream_idx == -1) {
276                                                         video_stream->schedule_original_frame(
277                                                                 next_frame_start, pts, display_func,
278                                                                 QueueSpotHolder(this), snap_frame);
279                                                 } else {
280                                                         assert(secondary_frame.pts != -1);
281                                                         video_stream->schedule_faded_frame(
282                                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
283                                                                 snap_frame, secondary_frame, fade_alpha);
284                                                 }
285                                         }
286                                         in_pts_origin += snap_frame.pts - in_pts;
287                                         snapped = true;
288                                         break;
289                                 }
290                         }
291                         if (snapped) {
292                                 continue;
293                         }
294
295                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
296                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
297                                         lrint(1e3 * duration<double>(time_behind).count()));
298                                 continue;
299                         }
300
301                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
302
303                         if (video_stream == nullptr) {
304                                 // Previews don't do any interpolation.
305                                 assert(secondary_stream_idx == -1);
306                                 if (destination != nullptr) {
307                                         destination->setFrame(primary_stream_idx, frame_lower);
308                                 }
309                         } else {
310                                 auto display_func = [this](shared_ptr<Frame> frame) {
311                                         if (destination != nullptr) {
312                                                 destination->setFrame(frame);
313                                         }
314                                 };
315                                 video_stream->schedule_interpolated_frame(
316                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
317                                         frame_lower, frame_upper, alpha,
318                                         secondary_frame, fade_alpha);
319                         }
320                 }
321
322                 if (should_quit) {
323                         return;
324                 }
325
326                 // The clip ended.
327
328                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
329                 if (!got_next_clip && next_clip_callback != nullptr) {
330                         tie(next_clip, next_clip_idx) = next_clip_callback();
331                         if (next_clip.pts_in != -1) {
332                                 got_next_clip = true;
333                                 in_pts_start_next_clip = next_clip.pts_in;
334                         }
335                 }
336
337                 // Switch to next clip if we got it.
338                 if (got_next_clip) {
339                         clip = next_clip;
340                         clip_idx = next_clip_idx;
341                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
342                         if (done_callback != nullptr) {
343                                 done_callback();
344                         }
345                         got_next_clip = false;
346
347                         // Start the next clip from the point where the fade went out.
348                         origin = next_frame_start;
349                         in_pts_origin = in_pts_start_next_clip;
350                         goto got_clip;
351                 }
352
353                 {
354                         unique_lock<mutex> lock(queue_state_mu);
355                         playing = false;
356                 }
357                 if (done_callback != nullptr) {
358                         done_callback();
359                 }
360         }
361 }
362
363 // Find the frame immediately before and after this point.
364 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
365 {
366         lock_guard<mutex> lock(frame_mu);
367
368         // Find the first frame such that frame.pts >= pts.
369         auto it = find_last_frame_before(frames[stream_idx], 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, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
387         : destination(destination)
388 {
389         player_thread = thread(&Player::thread_func, this, stream_output, file_avctx);
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 = find_first_frame_at_or_after(frames[stream_idx], pts_out);
455         if (it == frames[stream_idx].end()) {
456                 return;
457         }
458         destination->setFrame(stream_idx, *it);
459 }
460
461 void Player::take_queue_spot()
462 {
463         unique_lock<mutex> lock(queue_state_mu);
464         ++num_queued_frames;
465 }
466
467 void Player::release_queue_spot()
468 {
469         unique_lock<mutex> lock(queue_state_mu);
470         assert(num_queued_frames > 0);
471         --num_queued_frames;
472         new_clip_changed.notify_all();
473 }
474
475 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
476 {
477         // Look at the last clip and then start counting from there.
478         assert(!progress.empty());
479         auto last_it = progress.end();
480         --last_it;
481         double remaining = 0.0;
482         double last_fade_time_seconds = 0.0;
483         for (size_t row = last_it->first; row < clips.size(); ++row) {
484                 const Clip &clip = clips[row];
485                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
486                 if (row == last_it->first) {
487                         // A clip we're playing: Subtract the part we've already played.
488                         remaining = clip_length * (1.0 - last_it->second);
489                 } else {
490                         // A clip we haven't played yet: Subtract the part that's overlapping
491                         // with a previous clip (due to fade).
492                         remaining += max(clip_length - last_fade_time_seconds, 0.0);
493                 }
494                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
495         }
496         return remaining;
497 }