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