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