]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
a82b16e72e6a527618b7e46f34e518ff9427d962
[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                                 map<size_t, double> progress{ { clip_list[clip_idx].row, calc_progress(clip, in_pts_for_progress) } };
183                                 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
184                                         progress[clip_list[clip_idx + 1].row] = calc_progress(*next_clip, in_pts_secondary_for_progress);
185                                 }
186                                 progress_callback(progress);
187                         }
188
189                         FrameOnDisk frame_lower, frame_upper;
190                         bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
191                         if (!ok) {
192                                 break;
193                         }
194
195                         // Wait until we should, or (given buffering) can, output the frame.
196                         {
197                                 unique_lock<mutex> lock(queue_state_mu);
198                                 if (video_stream == nullptr) {
199                                         // No queue, just wait until the right time and then show the frame.
200                                         new_clip_changed.wait_until(lock, next_frame_start, [this] {
201                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
202                                         });
203                                         if (should_quit) {
204                                                 return;
205                                         }
206                                 } else {
207                                         // If the queue is full (which is really the state we'd like to be in),
208                                         // wait until there's room for one more frame (ie., one was output from
209                                         // VideoStream), or until or until there's a new clip we're supposed to play.
210                                         //
211                                         // In this case, we don't sleep until next_frame_start; the displaying is
212                                         // done by the queue.
213                                         new_clip_changed.wait(lock, [this] {
214                                                 if (num_queued_frames < max_queued_frames) {
215                                                         return true;
216                                                 }
217                                                 return should_quit || new_clip_ready || override_stream_idx != -1;
218                                         });
219                                 }
220                                 if (should_quit) {
221                                         return;
222                                 }
223                                 if (new_clip_ready) {
224                                         if (video_stream != nullptr) {
225                                                 lock.unlock();  // Urg.
226                                                 video_stream->clear_queue();
227                                                 lock.lock();
228                                         }
229                                         return;
230                                 }
231                                 // Honor if we got an override request for the camera.
232                                 if (override_stream_idx != -1) {
233                                         stream_idx = override_stream_idx;
234                                         override_stream_idx = -1;
235                                         continue;
236                                 }
237                         }
238
239                         // If there's nothing to interpolate between, or if interpolation is turned off,
240                         // or we're a preview, then just display the frame.
241                         if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0 || video_stream == nullptr) {
242                                 display_single_frame(primary_stream_idx, frame_lower, secondary_stream_idx,
243                                                      secondary_frame, fade_alpha, next_frame_start, /*snapped=*/false);
244                                 continue;
245                         }
246
247                         // Snap to input frame: If we can do so with less than 1% jitter
248                         // (ie., move less than 1% of an _output_ frame), do so.
249                         // TODO: Snap secondary (fade-to) clips in the same fashion.
250                         double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
251                         bool snapped = false;
252                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
253                                 if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
254                                         display_single_frame(primary_stream_idx, snap_frame, secondary_stream_idx,
255                                                              secondary_frame, fade_alpha, next_frame_start, /*snapped=*/true);
256                                         in_pts_origin += snap_frame.pts - in_pts;
257                                         snapped = true;
258                                         break;
259                                 }
260                         }
261                         if (snapped) {
262                                 continue;
263                         }
264
265                         // The snapping above makes us lock to the input framerate, even in the presence
266                         // of pts drift, for most typical cases where it's needed, like converting 60 â†’ 2x60
267                         // or 60 â†’ 2x59.94. However, there are some corner cases like 25 â†’ 2x59.94, where we'd
268                         // get a snap very rarely (in the given case, once every 24 output frames), and by
269                         // that time, we'd have drifted out. We could have solved this by changing the overall
270                         // speed ever so slightly, but it requires that we know the actual frame rate (which
271                         // is difficult in the presence of jitter and missed frames), or at least do some kind
272                         // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
273                         // points if we can. E.g., if we are converting 60 â†’ 2x60, we would not only snap to
274                         // an original frame every other frame; we would also snap to exactly alpha=0.5 every
275                         // in-between frame. Of course, we will still need to interpolate, but we get a lot
276                         // closer when we actually get close to an original frame. In other words: Snap more
277                         // often, but snap less each time. Unless the input and output frame rates are completely
278                         // decorrelated with no common factor, of course (e.g. 12.345 â†’ 34.567, which we should
279                         // really never see in practice).
280                         for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
281                                                  1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
282                                 double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
283                                 if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
284                                         in_pts_origin += lrint(subsnap_pts) - in_pts;
285                                         in_pts = lrint(subsnap_pts);
286                                         break;
287                                 }
288                         }
289
290                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
291                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
292                                         lrint(1e3 * duration<double>(time_behind).count()));
293                                 ++metric_dropped_interpolated_frame;
294                                 continue;
295                         }
296
297                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
298                         auto display_func = [this](shared_ptr<Frame> frame) {
299                                 if (destination != nullptr) {
300                                         destination->setFrame(frame);
301                                 }
302                         };
303                         if (secondary_stream_idx == -1) {
304                                 ++metric_interpolated_frame;
305                         } else {
306                                 ++metric_interpolated_faded_frame;
307                         }
308                         video_stream->schedule_interpolated_frame(
309                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
310                                 frame_lower, frame_upper, alpha,
311                                 secondary_frame, fade_alpha);
312                         last_pts_played = in_pts;  // Not really needed; only previews use last_pts_played.
313                 }
314
315                 // The clip ended.
316                 if (should_quit) {
317                         return;
318                 }
319                 if (done_callback != nullptr) {
320                         done_callback();
321                 }
322
323                 // Start the next clip from the point where the fade went out.
324                 if (next_clip != nullptr) {
325                         origin = next_frame_start;
326                         in_pts_origin = next_clip->pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
327                 }
328         }
329
330         if (done_callback != nullptr) {
331                 done_callback();
332         }
333 }
334
335 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)
336 {
337         auto display_func = [this, primary_stream_idx, primary_frame, secondary_frame, fade_alpha] {
338                 if (destination != nullptr) {
339                         destination->setFrame(primary_stream_idx, primary_frame, secondary_frame, fade_alpha);
340                 }
341         };
342         if (video_stream == nullptr) {
343                 display_func();
344         } else {
345                 if (secondary_stream_idx == -1) {
346                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
347                         if (snapped) {
348                                 ++metric_original_snapped_frame;
349                         } else {
350                                 ++metric_original_frame;
351                         }
352                         video_stream->schedule_original_frame(
353                                 frame_start, pts, display_func, QueueSpotHolder(this),
354                                 primary_frame);
355                 } else {
356                         assert(secondary_frame.pts != -1);
357                         // NOTE: We could be increasing unused metrics for previews, but that's harmless.
358                         if (snapped) {
359                                 ++metric_faded_snapped_frame;
360                         } else {
361                                 ++metric_faded_frame;
362                         }
363                         video_stream->schedule_faded_frame(frame_start, pts, display_func,
364                                                            QueueSpotHolder(this), primary_frame,
365                                                            secondary_frame, fade_alpha);
366                 }
367         }
368         last_pts_played = primary_frame.pts;
369 }
370
371 // Find the frame immediately before and after this point.
372 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
373 {
374         lock_guard<mutex> lock(frame_mu);
375
376         // Find the first frame such that frame.pts >= pts.
377         auto it = find_last_frame_before(frames[stream_idx], pts);
378         if (it == frames[stream_idx].end()) {
379                 return false;
380         }
381         *frame_upper = *it;
382
383         // Find the last frame such that in_pts <= frame.pts (if any).
384         if (it == frames[stream_idx].begin()) {
385                 *frame_lower = *it;
386         } else {
387                 *frame_lower = *(it - 1);
388         }
389         assert(pts >= frame_lower->pts);
390         assert(pts <= frame_upper->pts);
391         return true;
392 }
393
394 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
395         : destination(destination), stream_output(stream_output)
396 {
397         player_thread = thread(&Player::thread_func, this, file_avctx);
398
399         if (stream_output == HTTPD_STREAM_OUTPUT) {
400                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_original_frame);
401                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "edge_frame_or_no_interpolation" } }, &metric_faded_frame);
402                 global_metrics.add("http_output_frames", { { "type", "original" }, { "reason", "snapped" } }, &metric_original_snapped_frame);
403                 global_metrics.add("http_output_frames", { { "type", "faded" }, { "reason", "snapped" } }, &metric_faded_snapped_frame);
404                 global_metrics.add("http_output_frames", { { "type", "interpolated" } }, &metric_interpolated_frame);
405                 global_metrics.add("http_output_frames", { { "type", "interpolated_faded" } }, &metric_interpolated_faded_frame);
406                 global_metrics.add("http_output_frames", { { "type", "refresh" } }, &metric_refresh_frame);
407                 global_metrics.add("http_dropped_frames", { { "type", "interpolated" } }, &metric_dropped_interpolated_frame);
408                 global_metrics.add("http_dropped_frames", { { "type", "unconditional" } }, &metric_dropped_unconditional_frame);
409         }
410 }
411
412 Player::~Player()
413 {
414         should_quit = true;
415         if (video_stream != nullptr) {
416                 video_stream->stop();
417         }
418         new_clip_changed.notify_all();
419         player_thread.join();
420 }
421
422 void Player::play(const vector<Player::ClipWithRow> &clips)
423 {
424         lock_guard<mutex> lock(queue_state_mu);
425         new_clip_ready = true;
426         queued_clip_list = clips;
427         override_stream_idx = -1;
428         new_clip_changed.notify_all();
429 }
430
431 void Player::override_angle(unsigned stream_idx)
432 {
433         int64_t last_pts;
434
435         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
436         {
437                 lock_guard<mutex> lock(queue_state_mu);
438                 if (new_clip_ready) {
439                         assert(queued_clip_list.size() == 1);
440                         queued_clip_list[0].clip.stream_idx = stream_idx;
441                         return;
442                 }
443
444                 // If we are playing a clip, set override_stream_idx, and the player thread will
445                 // pick it up and change its internal index.
446                 if (playing) {
447                         override_stream_idx = stream_idx;
448                         new_clip_changed.notify_all();
449                         return;
450                 }
451
452                 // OK, so we're standing still, presumably at the end of a clip.
453                 // Look at the last frame played (if it exists), and show the closest
454                 // thing we've got.
455                 if (last_pts_played < 0) {
456                         return;
457                 }
458                 last_pts = last_pts_played;
459         }
460
461         lock_guard<mutex> lock(frame_mu);
462         auto it = find_first_frame_at_or_after(frames[stream_idx], last_pts);
463         if (it == frames[stream_idx].end()) {
464                 return;
465         }
466         destination->setFrame(stream_idx, *it);
467 }
468
469 void Player::take_queue_spot()
470 {
471         lock_guard<mutex> lock(queue_state_mu);
472         ++num_queued_frames;
473 }
474
475 void Player::release_queue_spot()
476 {
477         lock_guard<mutex> lock(queue_state_mu);
478         assert(num_queued_frames > 0);
479         --num_queued_frames;
480         new_clip_changed.notify_all();
481 }
482
483 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
484 {
485         // Look at the last clip and then start counting from there.
486         assert(!progress.empty());
487         auto last_it = progress.end();
488         --last_it;
489         double remaining = 0.0;
490         double last_fade_time_seconds = 0.0;
491         for (size_t row = last_it->first; row < clips.size(); ++row) {
492                 const Clip &clip = clips[row];
493                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
494                 if (row == last_it->first) {
495                         // A clip we're playing: Subtract the part we've already played.
496                         remaining = clip_length * (1.0 - last_it->second);
497                 } else {
498                         // A clip we haven't played yet: Subtract the part that's overlapping
499                         // with a previous clip (due to fade).
500                         remaining += max(clip_length - last_fade_time_seconds, 0.0);
501                 }
502                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
503         }
504         return remaining;
505 }