]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
Move estimation of time left into Player.
[nageru] / futatabi / player.cpp
1 #include "player.h"
2
3 #include "clip_list.h"
4 #include "defs.h"
5 #include "flags.h"
6 #include "frame_on_disk.h"
7 #include "jpeg_frame_view.h"
8 #include "shared/context.h"
9 #include "shared/ffmpeg_raii.h"
10 #include "shared/httpd.h"
11 #include "shared/metrics.h"
12 #include "shared/mux.h"
13 #include "shared/timebase.h"
14 #include "video_stream.h"
15
16 #include <algorithm>
17 #include <chrono>
18 #include <condition_variable>
19 #include <movit/util.h>
20 #include <mutex>
21 #include <stdio.h>
22 #include <thread>
23 #include <vector>
24
25 using namespace std;
26 using namespace std::chrono;
27
28 extern HTTPD *global_httpd;
29
30 void Player::thread_func(AVFormatContext *file_avctx)
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 (stream_output != NO_STREAM_OUTPUT) {
45                 video_stream.reset(new VideoStream(file_avctx));
46                 video_stream->start();
47         }
48
49         check_error();
50
51         while (!should_quit) {
52                 play_playlist_once();
53         }
54 }
55
56 namespace {
57
58 double calc_progress(const Clip &clip, int64_t pts)
59 {
60         return double(pts - clip.pts_in) / (clip.pts_out - clip.pts_in);
61 }
62
63 }  // namespace
64
65 void Player::play_playlist_once()
66 {
67         vector<ClipWithRow> clip_list;
68         bool clip_ready;
69         steady_clock::time_point before_sleep = steady_clock::now();
70
71         // Wait until we're supposed to play something.
72         {
73                 unique_lock<mutex> lock(queue_state_mu);
74                 playing = false;
75                 clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
76                         return should_quit || new_clip_ready;
77                 });
78                 if (should_quit) {
79                         return;
80                 }
81                 if (clip_ready) {
82                         new_clip_ready = false;
83                         playing = true;
84                         clip_list = move(queued_clip_list);
85                         queued_clip_list.clear();
86                         assert(!clip_list.empty());
87                 }
88         }
89
90         steady_clock::duration time_slept = steady_clock::now() - before_sleep;
91         pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
92
93         if (!clip_ready) {
94                 if (video_stream != nullptr) {
95                         ++metric_refresh_frame;
96                         video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
97                 }
98                 return;
99         }
100
101         steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
102         int64_t in_pts_origin = clip_list[0].clip.pts_in;
103         for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
104                 const Clip &clip = clip_list[clip_idx].clip;
105                 const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1].clip : nullptr;
106                 int64_t out_pts_origin = pts;
107
108                 double next_clip_fade_time = -1.0;
109                 if (next_clip != nullptr) {
110                         double duration_this_clip = double(clip.pts_out - in_pts_origin) / TIMEBASE / clip.speed;
111                         double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip.speed;
112                         next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip.fade_time_seconds);
113                 }
114
115                 int stream_idx = clip.stream_idx;
116
117                 // Start playing exactly at a frame.
118                 // TODO: Snap secondary (fade-to) clips in the same fashion
119                 // so that we don't get jank here).
120                 {
121                         lock_guard<mutex> lock(frame_mu);
122
123                         // Find the first frame such that frame.pts <= in_pts.
124                         auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
125                         if (it != frames[stream_idx].end()) {
126                                 in_pts_origin = it->pts;
127                         }
128                 }
129
130                 steady_clock::time_point next_frame_start;
131                 for (int frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
132                         double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
133                         next_frame_start =
134                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
135                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
136                         pts = lrint(out_pts);
137
138                         if (in_pts >= clip.pts_out) {
139                                 break;
140                         }
141
142                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
143                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
144                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
145                                         lrint(1e3 * duration<double>(time_behind).count()));
146                                 ++metric_dropped_unconditional_frame;
147                                 continue;
148                         }
149
150                         // pts not affected by the swapping below.
151                         int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
152
153                         int primary_stream_idx = stream_idx;
154                         FrameOnDisk secondary_frame;
155                         int secondary_stream_idx = -1;
156                         float fade_alpha = 0.0f;
157                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
158                         if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
159                                 // We're in a fade to the next clip.
160                                 secondary_stream_idx = next_clip->stream_idx;
161                                 int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
162                                 in_pts_secondary_for_progress = in_pts_secondary;
163                                 fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
164
165                                 // If more than half-way through the fade, interpolate the next clip
166                                 // instead of the current one, since it's more visible.
167                                 if (fade_alpha >= 0.5f) {
168                                         swap(primary_stream_idx, secondary_stream_idx);
169                                         swap(in_pts, in_pts_secondary);
170                                         fade_alpha = 1.0f - fade_alpha;
171                                 }
172
173                                 FrameOnDisk frame_lower, frame_upper;
174                                 bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
175                                 if (ok) {
176                                         secondary_frame = frame_lower;
177                                 }
178                         }
179
180                         if (progress_callback != nullptr) {
181                                 // NOTE: None of this will take into account any snapping done below.
182                                 double clip_progress = calc_progress(clip, in_pts_for_progress);
183                                 map<size_t, double> progress{ { clip_list[clip_idx].row, clip_progress } };
184                                 double time_remaining;
185                                 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
186                                         double next_clip_progress = calc_progress(*next_clip, in_pts_secondary_for_progress);
187                                         progress[clip_list[clip_idx + 1].row] = next_clip_progress;
188                                         time_remaining = compute_time_left(clip_list, clip_idx + 1, next_clip_progress);
189                                 } else {
190                                         time_remaining = compute_time_left(clip_list, clip_idx, clip_progress);
191                                 }
192                                 progress_callback(progress, time_remaining);
193                         }
194
195                         FrameOnDisk frame_lower, frame_upper;
196                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
197                         if (!ok) {
198                                 break;
199                         }
200
201                         // Wait until we should, or (given buffering) can, output the frame.
202                         {
203                                 unique_lock<mutex> lock(queue_state_mu);
204                                 if (video_stream == nullptr) {
205                                         // No queue, just wait until the right time and then show the frame.
206                                         new_clip_changed.wait_until(lock, next_frame_start, [this] {
207                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
208                                         });
209                                         if (should_quit) {
210                                                 return;
211                                         }
212                                 } else {
213                                         // If the queue is full (which is really the state we'd like to be in),
214                                         // wait until there's room for one more frame (ie., one was output from
215                                         // VideoStream), or until or until there's a new clip we're supposed to play.
216                                         //
217                                         // In this case, we don't sleep until next_frame_start; the displaying is
218                                         // done by the queue.
219                                         new_clip_changed.wait(lock, [this] {
220                                                 if (num_queued_frames < max_queued_frames) {
221                                                         return true;
222                                                 }
223                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
224                                         });
225                                 }
226                                 if (should_quit) {
227                                         return;
228                                 }
229                                 if (new_clip_ready) {
230                                         if (video_stream != nullptr) {
231                                                 lock.unlock();  // Urg.
232                                                 video_stream->clear_queue();
233                                                 lock.lock();
234                                         }
235                                         return;
236                                 }
237                                 // Honor if we got an override request for the camera.
238                                 if (override_stream_idx != -1) {
239                                         stream_idx = override_stream_idx;
240                                         override_stream_idx = -1;
241                                         continue;
242                                 }
243                         }
244
245                         // If there's nothing to interpolate between, or if interpolation is turned off,
246                         // or we're a preview, then just display the frame.
247                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
248                                 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
249                                                      secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false);
250                                 continue;
251                         }
252
253                         // Snap to input frame: If we can do so with less than 1% jitter
254                         // (ie., move less than 1% of an _output_ frame), do so.
255                         // TODO: Snap secondary (fade-to) clips in the same fashion.
256                         double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
257                         bool snapped = false;
258                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
259                                 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
260                                         display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
261                                                              secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true);
262                                         in_pts_origin += snap_frame.pts - in_pts;
263                                         snapped = true;
264                                         break;
265                                 }
266                         }
267                         if (snapped) {
268                                 continue;
269                         }
270
271                         // The snapping above makes us lock to the input framerate, even in the presence
272                         // of pts drift, for most typical cases where it's needed, like converting 60 â†’ 2x60
273                         // or 60 â†’ 2x59.94. However, there are some corner cases like 25 â†’ 2x59.94, where we'd
274                         // get a snap very rarely (in the given case, once every 24 output frames), and by
275                         // that time, we'd have drifted out. We could have solved this by changing the overall
276                         // speed ever so slightly, but it requires that we know the actual frame rate (which
277                         // is difficult in the presence of jitter and missed frames), or at least do some kind
278                         // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
279                         // points if we can. E.g., if we are converting 60 â†’ 2x60, we would not only snap to
280                         // an original frame every other frame; we would also snap to exactly alpha=0.5 every
281                         // in-between frame. Of course, we will still need to interpolate, but we get a lot
282                         // closer when we actually get close to an original frame. In other words: Snap more
283                         // often, but snap less each time. Unless the input and output frame rates are completely
284                         // decorrelated with no common factor, of course (e.g. 12.345 â†’ 34.567, which we should
285                         // really never see in practice).
286                         for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
287                                                  1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
288                                 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
289                                 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
290                                         in_pts_origin += lrint(subsnap_pts) - in_pts;
291                                         in_pts = lrint(subsnap_pts);
292                                         break;
293                                 }
294                         }
295
296                         if (stream_output != FILE_STREAM_OUTPUT && 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                                 ++metric_dropped_interpolated_frame;
300                                 continue;
301                         }
302
303                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
304                         auto display_func = [this](shared_ptr<Frame> frame) {
305                                 if (destination != nullptr) {
306                                         destination->setFrame(frame);
307                                 }
308                         };
309                         if (secondary_stream_idx == -1) {
310                                 ++metric_interpolated_frame;
311                         } else {
312                                 ++metric_interpolated_faded_frame;
313                         }
314                         video_stream->schedule_interpolated_frame(
315                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
316                                 frame_lower, frame_upper, alpha,
317                                 secondary_frame, fade_alpha);
318                         last_pts_played = in_pts;  // Not really needed; only previews use last_pts_played.
319                 }
320
321                 // The clip ended.
322                 if (should_quit) {
323                         return;
324                 }
325                 if (done_callback != nullptr) {
326                         done_callback();
327                 }
328
329                 // Start the next clip from the point where the fade went out.
330                 if (next_clip != nullptr) {
331                         origin = next_frame_start;
332                         in_pts_origin = next_clip->pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
333                 }
334         }
335
336         if (done_callback != nullptr) {
337                 done_callback();
338         }
339 }
340
341 void Player::display_single_frame(int primary_stream_idx, const FrameOnDisk &primary_frame, int secondary_stream_idx, const FrameOnDisk &secondary_frame, double fade_alpha, steady_clock::time_point frame_start, bool snapped)
342 {
343         auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha] {
344                 if (destination != nullptr) {
345                         destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
346                 }
347         };
348         if (video_stream == nullptr) {
349                 display_func();
350         } else {
351                 if (secondary_stream_idx == -1) {
352                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
353                         if (snapped) {
354                                 ++metric_original_snapped_frame;
355                         } else {
356                                 ++metric_original_frame;
357                         }
358                         video_stream->schedule_original_frame(
359                                 frame_start, pts, display_func, QueueSpotHolder(this),
360                                 primary_frame);
361                 } else {
362                         assert(secondary_frame.pts != -1);
363                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
364                         if (snapped) {
365                                 ++metric_faded_snapped_frame;
366                         } else {
367                                 ++metric_faded_frame;
368                         }
369                         video_stream->schedule_faded_frame(frame_start, pts, display_func,
370                                                            QueueSpotHolder(this), primary_frame,
371                                                            secondary_frame, fade_alpha);
372                 }
373         }
374         last_pts_played = primary_frame.pts;
375 }
376
377 // Find the frame immediately before and after this point.
378 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
379 {
380         lock_guard<mutex> lock(frame_mu);
381
382         // Find the first frame such that frame.pts >= pts.
383         auto it = find_last_frame_before(frames[stream_idx], pts);
384         if (it == frames[stream_idx].end()) {
385                 return false;
386         }
387         *frame_upper = *it;
388
389         // Find the last frame such that in_pts <= frame.pts (if any).
390         if (it == frames[stream_idx].begin()) {
391                 *frame_lower = *it;
392         } else {
393                 *frame_lower = *(it - 1);
394         }
395         assert(pts >= frame_lower->pts);
396         assert(pts <= frame_upper->pts);
397         return true;
398 }
399
400 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
401         : destination(destination), stream_output(stream_output)
402 {
403         player_thread = thread(&Player::thread_func, this, file_avctx);
404
405         if (stream_output == HTTPD_STREAM_OUTPUT) {
406                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_original_frame);
407                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_faded_frame);
408                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "snapped" } }, &metric_original_snapped_frame);
409                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "snapped" } }, &metric_faded_snapped_frame);
410                 global_metrics.add("http_output_frames", { { "type", "interpolated" } }, &metric_interpolated_frame);
411                 global_metrics.add("http_output_frames", { { "type", "interpolated_faded" } }, &metric_interpolated_faded_frame);
412                 global_metrics.add("http_output_frames", { { "type", "refresh" } }, &metric_refresh_frame);
413                 global_metrics.add("http_dropped_frames", { { "type", "interpolated" } }, &metric_dropped_interpolated_frame);
414                 global_metrics.add("http_dropped_frames", { { "type", "unconditional" } }, &metric_dropped_unconditional_frame);
415         }
416 }
417
418 Player::~Player()
419 {
420         should_quit = true;
421         if (video_stream != nullptr) {
422                 video_stream->stop();
423         }
424         new_clip_changed.notify_all();
425         player_thread.join();
426 }
427
428 void Player::play(const vector<Player::ClipWithRow> &clips)
429 {
430         lock_guard<mutex> lock(queue_state_mu);
431         new_clip_ready = true;
432         queued_clip_list = clips;
433         override_stream_idx = -1;
434         new_clip_changed.notify_all();
435 }
436
437 void Player::override_angle(unsigned stream_idx)
438 {
439         int64_t last_pts;
440
441         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
442         {
443                 lock_guard<mutex> lock(queue_state_mu);
444                 if (new_clip_ready) {
445                         assert(queued_clip_list.size() == 1);
446                         queued_clip_list[0].clip.stream_idx = stream_idx;
447                         return;
448                 }
449
450                 // If we are playing a clip, set override_stream_idx, and the player thread will
451                 // pick it up and change its internal index.
452                 if (playing) {
453                         override_stream_idx = stream_idx;
454                         new_clip_changed.notify_all();
455                         return;
456                 }
457
458                 // OK, so we're standing still, presumably at the end of a clip.
459                 // Look at the last frame played (if it exists), and show the closest
460                 // thing we've got.
461                 if (last_pts_played < 0) {
462                         return;
463                 }
464                 last_pts = last_pts_played;
465         }
466
467         lock_guard<mutex> lock(frame_mu);
468         auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
469         if (it == frames[stream_idx].end()) {
470                 return;
471         }
472         destination->setFrame(stream_idx, *it);
473 }
474
475 void Player::take_queue_spot()
476 {
477         lock_guard<mutex> lock(queue_state_mu);
478         ++num_queued_frames;
479 }
480
481 void Player::release_queue_spot()
482 {
483         lock_guard<mutex> lock(queue_state_mu);
484         assert(num_queued_frames > 0);
485         --num_queued_frames;
486         new_clip_changed.notify_all();
487 }
488
489 double compute_time_left(const vector<Player::ClipWithRow> &clips, size_t currently_playing_idx, double progress_currently_playing) 
490 {
491         // Look at the last clip and then start counting from there.
492         double remaining = 0.0;
493         double last_fade_time_seconds = 0.0;
494         for (size_t row = currently_playing_idx; row < clips.size(); ++row) {
495                 const Clip &clip = clips[row].clip;
496                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
497                 if (row == currently_playing_idx) {
498                         // A clip we're playing: Subtract the part we've already played.
499                         remaining = clip_length * (1.0 - progress_currently_playing);
500                 } else {
501                         // A clip we haven't played yet: Subtract the part that's overlapping
502                         // with a previous clip (due to fade).
503                         remaining += max(clip_length - last_fade_time_seconds, 0.0);
504                 }
505                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
506         }
507         return remaining;
508 }