]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
Improve frame snapping in difficult cases.
[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                 int64_t in_pts_start_next_clip = -1;
112                 steady_clock::time_point next_frame_start;
113                 for (int frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
114                         double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
115                         next_frame_start =
116                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
117                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
118                         pts = lrint(out_pts);
119
120                         if (in_pts >= clip.pts_out) {
121                                 break;
122                         }
123
124                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
125                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
126                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
127                                         lrint(1e3 * duration<double>(time_behind).count()));
128                                 continue;
129                         }
130
131                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
132                         if (!got_next_clip && next_clip_callback != nullptr && time_left_this_clip <= clip.fade_time_seconds) {
133                                 // Find the next clip so that we can begin a fade.
134                                 tie(next_clip, next_clip_idx) = next_clip_callback();
135                                 if (next_clip.pts_in != -1) {
136                                         got_next_clip = true;
137
138                                         double duration_next_clip = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / clip.speed;
139                                         next_clip_fade_time = std::min(time_left_this_clip, duration_next_clip);
140                                         in_pts_start_next_clip = next_clip.pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
141                                 }
142                         }
143
144                         // pts not affected by the swapping below.
145                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
146
147                         int primary_stream_idx = stream_idx;
148                         FrameOnDisk secondary_frame;
149                         int secondary_stream_idx = -1;
150                         float fade_alpha = 0.0f;
151                         if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
152                                 secondary_stream_idx = next_clip.stream_idx;
153                                 int64_t in_pts_secondary = lrint(next_clip.pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
154                                 in_pts_secondary_for_progress = in_pts_secondary;
155                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
156
157                                 // If more than half-way through the fade, interpolate the next clip
158                                 // instead of the current one, since it's more visible.
159                                 if (fade_alpha >= 0.5f) {
160                                         swap(primary_stream_idx, secondary_stream_idx);
161                                         swap(in_pts, in_pts_secondary);
162                                         fade_alpha = 1.0f - fade_alpha;
163                                 }
164
165                                 FrameOnDisk frame_lower, frame_upper;
166                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
167                                 if (ok) {
168                                         secondary_frame = frame_lower;
169                                 }
170                         }
171
172                         if (progress_callback != nullptr) {
173                                 // NOTE: None of this will take into account any snapping done below.
174                                 double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / clip.speed;
175                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
176                                 map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
177
178                                 if (got_next_clip && time_left_this_clip <= next_clip_fade_time) {
179                                         double played_next_clip = double(in_pts_secondary_for_progress - next_clip.pts_in) / TIMEBASE / next_clip.speed;
180                                         double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / next_clip.speed;
181                                         progress[next_clip_idx] = played_next_clip / total_next_length;
182                                 }
183                                 progress_callback(progress);
184                         }
185
186                         FrameOnDisk frame_lower, frame_upper;
187                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
188                         if (!ok) {
189                                 break;
190                         }
191
192                         {
193                                 unique_lock<mutex> lock(queue_state_mu);
194                                 if (video_stream == nullptr) {
195                                         // No queue, just wait until the right time and then show the frame.
196                                         new_clip_changed.wait_until(lock, next_frame_start, [this]{
197                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
198                                         });
199                                 if (should_quit) {
200                                         return;
201                                 }
202                                 } else {
203                                         // If the queue is full (which is really the state we'd like to be in),
204                                         // wait until there's room for one more frame (ie., one was output from
205                                         // VideoStream), or until or until there's a new clip we're supposed to play.
206                                         //
207                                         // In this case, we don't sleep until next_frame_start; the displaying is
208                                         // done by the queue.
209                                         new_clip_changed.wait(lock, [this]{
210                                                 if (num_queued_frames < max_queued_frames) {
211                                                         return true;
212                                                 }
213                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
214                                         });
215                                 }
216                                 if (should_quit) {
217                                         return;
218                                 }
219                                 if (new_clip_ready) {
220                                         if (video_stream != nullptr) {
221                                                 lock.unlock();  // Urg.
222                                                 video_stream->clear_queue();
223                                                 lock.lock();
224                                         }
225                                         got_next_clip = false;
226                                         goto wait_for_clip;
227                                 }
228                                 if (override_stream_idx != -1) {
229                                         stream_idx = override_stream_idx;
230                                         override_stream_idx = -1;
231                                         continue;
232                                 }
233                         }
234
235                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
236                                 auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
237                                         if (destination != nullptr) {
238                                                 destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
239                                         }
240                                 };
241                                 if (video_stream == nullptr) {
242                                         display_func();
243                                 } else {
244                                         if (secondary_stream_idx == -1) {
245                                                 video_stream->schedule_original_frame(
246                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
247                                                         frame_lower);
248                                         } else {
249                                                 assert(secondary_frame.pts != -1);
250                                                 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
251                                                         QueueSpotHolder(this), frame_lower,
252                                                         secondary_frame, fade_alpha);
253                                         }
254                                 }
255                                 continue;
256                         }
257
258                         // Snap to input frame: If we can do so with less than 1% jitter
259                         // (ie., move less than 1% of an _output_ frame), do so.
260                         // TODO: Snap secondary (fade-to) clips in the same fashion.
261                         double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
262                         bool snapped = false;
263                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
264                                 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
265                                         auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
266                                                 if (destination != nullptr) {
267                                                         destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
268                                                 }
269                                         };
270                                         if (video_stream == nullptr) {
271                                                 display_func();
272                                         } else {
273                                                 if (secondary_stream_idx == -1) {
274                                                         video_stream->schedule_original_frame(
275                                                                 next_frame_start, pts, display_func,
276                                                                 QueueSpotHolder(this), snap_frame);
277                                                 } else {
278                                                         assert(secondary_frame.pts != -1);
279                                                         video_stream->schedule_faded_frame(
280                                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
281                                                                 snap_frame, secondary_frame, fade_alpha);
282                                                 }
283                                         }
284                                         in_pts_origin += snap_frame.pts - in_pts;
285                                         snapped = true;
286                                         break;
287                                 }
288                         }
289                         if (snapped) {
290                                 continue;
291                         }
292
293                         // The snapping above makes us lock to the input framerate, even in the presence
294                         // of pts drift, for most typical cases where it's needed, like converting 60 → 2x60
295                         // or 60 → 2x59.94. However, there are some corner cases like 25 → 2x59.94, where we'd
296                         // get a snap very rarely (in the given case, once every 24 output frames), and by
297                         // that time, we'd have drifted out. We could have solved this by changing the overall
298                         // speed ever so slightly, but it requires that we know the actual frame rate (which
299                         // is difficult in the presence of jitter and missed frames), or at least do some kind
300                         // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
301                         // points if we can. E.g., if we are converting 60 → 2x60, we would not only snap to
302                         // an original frame every other frame; we would also snap to exactly alpha=0.5 every
303                         // in-between frame. Of course, we will still need to interpolate, but we get a lot
304                         // closer when we actually get close to an original frame. In other words: Snap more
305                         // often, but snap less each time. Unless the input and output frame rates are completely
306                         // decorrelated with no common factor, of course (e.g. 12.345 → 34.567, which we should
307                         // really never see in practice).
308                         for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
309                                                  1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
310                                 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
311                                 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
312                                         in_pts_origin += lrint(subsnap_pts) - in_pts;
313                                         in_pts = lrint(subsnap_pts);
314                                         break;
315                                 }
316                         }
317
318                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
319                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
320                                         lrint(1e3 * duration<double>(time_behind).count()));
321                                 continue;
322                         }
323
324                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
325
326                         if (video_stream == nullptr) {
327                                 // Previews don't do any interpolation.
328                                 assert(secondary_stream_idx == -1);
329                                 if (destination != nullptr) {
330                                         destination->setFrame(primary_stream_idx, frame_lower);
331                                 }
332                         } else {
333                                 auto display_func = [this](shared_ptr<Frame> frame) {
334                                         if (destination != nullptr) {
335                                                 destination->setFrame(frame);
336                                         }
337                                 };
338                                 video_stream->schedule_interpolated_frame(
339                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
340                                         frame_lower, frame_upper, alpha,
341                                         secondary_frame, fade_alpha);
342                         }
343                 }
344
345                 if (should_quit) {
346                         return;
347                 }
348
349                 // The clip ended.
350
351                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
352                 if (!got_next_clip && next_clip_callback != nullptr) {
353                         tie(next_clip, next_clip_idx) = next_clip_callback();
354                         if (next_clip.pts_in != -1) {
355                                 got_next_clip = true;
356                                 in_pts_start_next_clip = next_clip.pts_in;
357                         }
358                 }
359
360                 // Switch to next clip if we got it.
361                 if (got_next_clip) {
362                         clip = next_clip;
363                         clip_idx = next_clip_idx;
364                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
365                         if (done_callback != nullptr) {
366                                 done_callback();
367                         }
368                         got_next_clip = false;
369
370                         // Start the next clip from the point where the fade went out.
371                         origin = next_frame_start;
372                         in_pts_origin = in_pts_start_next_clip;
373                         goto got_clip;
374                 }
375
376                 {
377                         unique_lock<mutex> lock(queue_state_mu);
378                         playing = false;
379                 }
380                 if (done_callback != nullptr) {
381                         done_callback();
382                 }
383         }
384 }
385
386 // Find the frame immediately before and after this point.
387 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
388 {
389         lock_guard<mutex> lock(frame_mu);
390
391         // Find the first frame such that frame.pts >= pts.
392         auto it = find_last_frame_before(frames[stream_idx], pts);
393         if (it == frames[stream_idx].end()) {
394                 return false;
395         }
396         *frame_upper = *it;
397
398         // Find the last frame such that in_pts <= frame.pts (if any).
399         if (it == frames[stream_idx].begin()) {
400                 *frame_lower = *it;
401         } else {
402                 *frame_lower = *(it - 1);
403         }
404         assert(pts >= frame_lower->pts);
405         assert(pts <= frame_upper->pts);
406         return true;
407 }
408
409 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
410         : destination(destination)
411 {
412         player_thread = thread(&Player::thread_func, this, stream_output, file_avctx);
413 }
414
415 Player::~Player()
416 {
417         should_quit = true;
418         if (video_stream != nullptr) {
419                 video_stream->stop();
420         }
421         new_clip_changed.notify_all();
422         player_thread.join();
423 }
424
425 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
426 {
427         {
428                 lock_guard<mutex> lock(mu);
429                 current_clip = clip;
430                 current_stream_idx = stream_idx;
431                 current_clip_idx = clip_idx;
432         }
433
434         {
435                 lock_guard<mutex> lock(queue_state_mu);
436                 new_clip_ready = true;
437                 override_stream_idx = -1;
438                 new_clip_changed.notify_all();
439         }
440 }
441
442 void Player::override_angle(unsigned stream_idx)
443 {
444         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
445         {
446                 unique_lock<mutex> lock(queue_state_mu);
447                 if (new_clip_ready) {
448                         lock_guard<mutex> lock2(mu);
449                         current_stream_idx = stream_idx;
450                         return;
451                 }
452         }
453
454         // If we are playing a clip, set override_stream_idx, and the player thread will
455         // pick it up and change its internal index.
456         {
457                 unique_lock<mutex> lock(queue_state_mu);
458                 if (playing) {
459                         override_stream_idx = stream_idx;
460                         new_clip_changed.notify_all();
461                 }
462         }
463
464         // OK, so we're standing still, presumably at the end of a clip.
465         // Look at the current pts_out (if it exists), and show the closest
466         // thing we've got.
467         int64_t pts_out;
468         {
469                 lock_guard<mutex> lock(mu);
470                 if (current_clip.pts_out < 0) {
471                         return;
472                 }
473                 pts_out = current_clip.pts_out;
474         }
475
476         lock_guard<mutex> lock(frame_mu);
477         auto it = find_first_frame_at_or_after(frames[stream_idx], pts_out);
478         if (it == frames[stream_idx].end()) {
479                 return;
480         }
481         destination->setFrame(stream_idx, *it);
482 }
483
484 void Player::take_queue_spot()
485 {
486         unique_lock<mutex> lock(queue_state_mu);
487         ++num_queued_frames;
488 }
489
490 void Player::release_queue_spot()
491 {
492         unique_lock<mutex> lock(queue_state_mu);
493         assert(num_queued_frames > 0);
494         --num_queued_frames;
495         new_clip_changed.notify_all();
496 }
497
498 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
499 {
500         // Look at the last clip and then start counting from there.
501         assert(!progress.empty());
502         auto last_it = progress.end();
503         --last_it;
504         double remaining = 0.0;
505         double last_fade_time_seconds = 0.0;
506         for (size_t row = last_it->first; row < clips.size(); ++row) {
507                 const Clip &clip = clips[row];
508                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
509                 if (row == last_it->first) {
510                         // A clip we're playing: Subtract the part we've already played.
511                         remaining = clip_length * (1.0 - last_it->second);
512                 } else {
513                         // A clip we haven't played yet: Subtract the part that's overlapping
514                         // with a previous clip (due to fade).
515                         remaining += max(clip_length - last_fade_time_seconds, 0.0);
516                 }
517                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
518         }
519         return remaining;
520 }