]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
Move from unique_lock to lock_guard everywhere we can. Perhaps ever so slightly clear...
[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         while (!should_quit) {
53 wait_for_clip:
54                 vector<Clip> clip_list;
55                 bool clip_ready;
56                 steady_clock::time_point before_sleep = steady_clock::now();
57
58                 // Wait until we're supposed to play something.
59                 {
60                         unique_lock<mutex> lock(queue_state_mu);
61                         playing = false;
62                         clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
63                                 return should_quit || new_clip_ready;
64                         });
65                         if (should_quit) {
66                                 return;
67                         }
68                         if (clip_ready) {
69                                 new_clip_ready = false;
70                                 playing = true;
71                                 clip_list = move(queued_clip_list);
72                                 queued_clip_list.clear();
73                                 assert(!clip_list.empty());
74                         }
75                 }
76
77                 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
78                 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
79
80                 if (!clip_ready) {
81                         if (video_stream != nullptr) {
82                                 ++metric_refresh_frame;
83                                 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
84                         }
85                         continue;
86                 }
87
88                 steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
89                 int64_t in_pts_origin = clip_list[0].pts_in;
90                 for (size_t clip_idx = 0; clip_idx < clip_list.size(); ++clip_idx) {
91                         const Clip &clip = clip_list[clip_idx];
92                         const Clip *next_clip = (clip_idx + 1 < clip_list.size()) ? &clip_list[clip_idx + 1] : nullptr;
93                         int64_t out_pts_origin = pts;
94
95                         double next_clip_fade_time = -1.0;
96                         if (next_clip != nullptr) {
97                                 double duration_this_clip = double(clip.pts_out - in_pts_origin) / TIMEBASE / clip.speed;
98                                 double duration_next_clip = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / clip.speed;
99                                 next_clip_fade_time = min(min(duration_this_clip, duration_next_clip), clip.fade_time_seconds);
100                         }
101
102                         int stream_idx = clip.stream_idx;
103
104                         // Start playing exactly at a frame.
105                         // TODO: Snap secondary (fade-to) clips in the same fashion
106                         // so that we don't get jank here).
107                         {
108                                 lock_guard<mutex> lock(frame_mu);
109
110                                 // Find the first frame such that frame.pts <= in_pts.
111                                 auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
112                                 if (it != frames[stream_idx].end()) {
113                                         in_pts_origin = it->pts;
114                                 }
115                         }
116
117                         steady_clock::time_point next_frame_start;
118                         for (int frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
119                                 double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
120                                 next_frame_start =
121                                         origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
122                                 int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * clip.speed / global_flags.output_framerate);
123                                 pts = lrint(out_pts);
124
125                                 if (in_pts >= clip.pts_out) {
126                                         break;
127                                 }
128
129                                 steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
130                                 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
131                                         fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
132                                                 lrint(1e3 * duration<double>(time_behind).count()));
133                                         ++metric_dropped_unconditional_frame;
134                                         continue;
135                                 }
136
137
138                                 // pts not affected by the swapping below.
139                                 int64_t in_pts_for_progress = in_pts, in_pts_secondary_for_progress = -1;
140
141                                 int primary_stream_idx = stream_idx;
142                                 FrameOnDisk secondary_frame;
143                                 int secondary_stream_idx = -1;
144                                 float fade_alpha = 0.0f;
145                                 double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / clip.speed;
146                                 if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
147                                         // We're in a fade to the next clip.
148                                         secondary_stream_idx = next_clip->stream_idx;
149                                         int64_t in_pts_secondary = lrint(next_clip->pts_in + (next_clip_fade_time - time_left_this_clip) * TIMEBASE * clip.speed);
150                                         in_pts_secondary_for_progress = in_pts_secondary;
151                                         fade_alpha = 1.0f - time_left_this_clip / next_clip_fade_time;
152
153                                         // If more than half-way through the fade, interpolate the next clip
154                                         // instead of the current one, since it's more visible.
155                                         if (fade_alpha >= 0.5f) {
156                                                 swap(primary_stream_idx, secondary_stream_idx);
157                                                 swap(in_pts, in_pts_secondary);
158                                                 fade_alpha = 1.0f - fade_alpha;
159                                         }
160
161                                         FrameOnDisk frame_lower, frame_upper;
162                                         bool ok = find_surrounding_frames(in_pts_secondary, secondary_stream_idx, &frame_lower, &frame_upper);
163                                         if (ok) {
164                                                 secondary_frame = frame_lower;
165                                         }
166                                 }
167
168                                 if (progress_callback != nullptr) {
169                                         // NOTE: None of this will take into account any snapping done below.
170                                         double played_this_clip = double(in_pts_for_progress - clip.pts_in) / TIMEBASE / clip.speed;
171                                         double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
172                                         map<size_t, double> progress{{ clip_idx, played_this_clip / total_length }};
173
174                                         if (next_clip != nullptr && time_left_this_clip <= next_clip_fade_time) {
175                                                 double played_next_clip = double(in_pts_secondary_for_progress - next_clip->pts_in) / TIMEBASE / next_clip->speed;
176                                                 double total_next_length = double(next_clip->pts_out - next_clip->pts_in) / TIMEBASE / next_clip->speed;
177                                                 progress[clip_idx + 1] = played_next_clip / total_next_length;
178                                         }
179                                         progress_callback(progress);
180                                 }
181
182                                 FrameOnDisk frame_lower, frame_upper;
183                                 bool ok = find_surrounding_frames(in_pts, primary_stream_idx, &frame_lower, &frame_upper);
184                                 if (!ok) {
185                                         break;
186                                 }
187
188                                 // Wait until we should, or (given buffering) can, output the frame.
189                                 {
190                                         unique_lock<mutex> lock(queue_state_mu);
191                                         if (video_stream == nullptr) {
192                                                 // No queue, just wait until the right time and then show the frame.
193                                                 new_clip_changed.wait_until(lock, next_frame_start, [this]{
194                                                         return should_quit || new_clip_ready || override_stream_idx != -1;
195                                                 });
196                                                 if (should_quit) {
197                                                         return;
198                                                 }
199                                         } else {
200                                                 // If the queue is full (which is really the state we'd like to be in),
201                                                 // wait until there's room for one more frame (ie., one was output from
202                                                 // VideoStream), or until or until there's a new clip we're supposed to play.
203                                                 //
204                                                 // In this case, we don't sleep until next_frame_start; the displaying is
205                                                 // done by the queue.
206                                                 new_clip_changed.wait(lock, [this]{
207                                                         if (num_queued_frames < max_queued_frames) {
208                                                                 return true;
209                                                         }
210                                                         return should_quit || new_clip_ready || override_stream_idx != -1;
211                                                 });
212                                         }
213                                         if (should_quit) {
214                                                 return;
215                                         }
216                                         if (new_clip_ready) {
217                                                 if (video_stream != nullptr) {
218                                                         lock.unlock();  // Urg.
219                                                         video_stream->clear_queue();
220                                                         lock.lock();
221                                                 }
222                                                 goto wait_for_clip;
223                                         }
224                                         // Honor if we got an override request for the camera.
225                                         if (override_stream_idx != -1) {
226                                                 stream_idx = override_stream_idx;
227                                                 override_stream_idx = -1;
228                                                 continue;
229                                         }
230                                 }
231
232                                 if (frame_lower.pts == frame_upper.pts || global_flags.interpolation_quality == 0) {
233                                         auto display_func = [this, primary_stream_idx, frame_lower, secondary_frame, fade_alpha]{
234                                                 if (destination != nullptr) {
235                                                         destination->setFrame(primary_stream_idx, frame_lower, secondary_frame, fade_alpha);
236                                                 }
237                                         };
238                                         if (video_stream == nullptr) {
239                                                 display_func();
240                                         } else {
241                                                 if (secondary_stream_idx == -1) {
242                                                         ++metric_original_frame;
243                                                         video_stream->schedule_original_frame(
244                                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
245                                                                 frame_lower);
246                                                 } else {
247                                                         assert(secondary_frame.pts != -1);
248                                                         ++metric_faded_frame;
249                                                         video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
250                                                                 QueueSpotHolder(this), frame_lower,
251                                                                 secondary_frame, fade_alpha);
252                                                 }
253                                         }
254                                         last_pts_played = frame_lower.pts;
255                                         continue;
256                                 }
257
258                                 // Snap to input frame: If we can do so with less than 1% jitter
259                                 // (ie., move less than 1% of an _output_ frame), do so.
260                                 // TODO: Snap secondary (fade-to) clips in the same fashion.
261                                 double pts_snap_tolerance = 0.01 * double(TIMEBASE) / global_flags.output_framerate;
262                                 bool snapped = false;
263                                 for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
264                                         if (fabs(snap_frame.pts - in_pts) < pts_snap_tolerance) {
265                                                 auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
266                                                         if (destination != nullptr) {
267                                                                 destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
268                                                         }
269                                                 };
270                                                 if (video_stream == nullptr) {
271                                                         display_func();
272                                                 } else {
273                                                         if (secondary_stream_idx == -1) {
274                                                                 ++metric_original_snapped_frame;
275                                                                 video_stream->schedule_original_frame(
276                                                                         next_frame_start, pts, display_func,
277                                                                         QueueSpotHolder(this), snap_frame);
278                                                         } else {
279                                                                 assert(secondary_frame.pts != -1);
280                                                                 ++metric_faded_snapped_frame;
281                                                                 video_stream->schedule_faded_frame(
282                                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
283                                                                         snap_frame, secondary_frame, fade_alpha);
284                                                         }
285                                                 }
286                                                 in_pts_origin += snap_frame.pts - in_pts;
287                                                 snapped = true;
288                                                 last_pts_played = snap_frame.pts;
289                                                 break;
290                                         }
291                                 }
292                                 if (snapped) {
293                                         continue;
294                                 }
295
296                                 // The snapping above makes us lock to the input framerate, even in the presence
297                                 // of pts drift, for most typical cases where it's needed, like converting 60 â†’ 2x60
298                                 // or 60 â†’ 2x59.94. However, there are some corner cases like 25 â†’ 2x59.94, where we'd
299                                 // get a snap very rarely (in the given case, once every 24 output frames), and by
300                                 // that time, we'd have drifted out. We could have solved this by changing the overall
301                                 // speed ever so slightly, but it requires that we know the actual frame rate (which
302                                 // is difficult in the presence of jitter and missed frames), or at least do some kind
303                                 // of matching/clustering. Instead, we take the opportunity to lock to in-between rational
304                                 // points if we can. E.g., if we are converting 60 â†’ 2x60, we would not only snap to
305                                 // an original frame every other frame; we would also snap to exactly alpha=0.5 every
306                                 // in-between frame. Of course, we will still need to interpolate, but we get a lot
307                                 // closer when we actually get close to an original frame. In other words: Snap more
308                                 // often, but snap less each time. Unless the input and output frame rates are completely
309                                 // decorrelated with no common factor, of course (e.g. 12.345 â†’ 34.567, which we should
310                                 // really never see in practice).
311                                 for (double fraction : { 1.0 / 2.0, 1.0 / 3.0, 2.0 / 3.0, 1.0 / 4.0, 3.0 / 4.0,
312                                                          1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0 }) {
313                                         double subsnap_pts = frame_lower.pts + fraction * (frame_upper.pts - frame_lower.pts);
314                                         if (fabs(subsnap_pts - in_pts) < pts_snap_tolerance) {
315                                                 in_pts_origin += lrint(subsnap_pts) - in_pts;
316                                                 in_pts = lrint(subsnap_pts);
317                                                 break;
318                                         }
319                                 }
320
321                                 if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
322                                         fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
323                                                 lrint(1e3 * duration<double>(time_behind).count()));
324                                         ++metric_dropped_interpolated_frame;
325                                         continue;
326                                 }
327
328                                 double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
329
330                                 if (video_stream == nullptr) {
331                                         // Previews don't do any interpolation.
332                                         assert(secondary_stream_idx == -1);
333                                         if (destination != nullptr) {
334                                                 destination->setFrame(primary_stream_idx, frame_lower);
335                                         }
336                                         last_pts_played = frame_lower.pts;
337                                 } else {
338                                         auto display_func = [this](shared_ptr<Frame> frame) {
339                                                 if (destination != nullptr) {
340                                                         destination->setFrame(frame);
341                                                 }
342                                         };
343                                         if (secondary_stream_idx == -1) {
344                                                 ++metric_interpolated_frame;
345                                         } else {
346                                                 ++metric_interpolated_faded_frame;
347                                         }
348                                         video_stream->schedule_interpolated_frame(
349                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
350                                                 frame_lower, frame_upper, alpha,
351                                                 secondary_frame, fade_alpha);
352                                         last_pts_played = in_pts;  // Not really needed; only previews use last_pts_played.
353                                 }
354                         }
355
356                         // The clip ended.
357                         if (should_quit) {
358                                 return;
359                         }
360                         if (done_callback != nullptr) {
361                                 done_callback();
362                         }
363
364                         // Start the next clip from the point where the fade went out.
365                         if (next_clip != nullptr) {
366                                 origin = next_frame_start;
367                                 in_pts_origin = next_clip->pts_in + lrint(next_clip_fade_time * TIMEBASE * clip.speed);
368                         }
369                 }
370
371                 if (done_callback != nullptr) {
372                         done_callback();
373                 }
374         }
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)
402 {
403         player_thread = thread(&Player::thread_func, this, stream_output, 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<Clip> &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].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<Clip> &clips, const map<size_t, double> &progress)
490 {
491         // Look at the last clip and then start counting from there.
492         assert(!progress.empty());
493         auto last_it = progress.end();
494         --last_it;
495         double remaining = 0.0;
496         double last_fade_time_seconds = 0.0;
497         for (size_t row = last_it->first; row < clips.size(); ++row) {
498                 const Clip &clip = clips[row];
499                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / clip.speed;
500                 if (row == last_it->first) {
501                         // A clip we're playing: Subtract the part we've already played.
502                         remaining = clip_length * (1.0 - last_it->second);
503                 } else {
504                         // A clip we haven't played yet: Subtract the part that's overlapping
505                         // with a previous clip (due to fade).
506                         remaining += max(clip_length - last_fade_time_seconds, 0.0);
507                 }
508                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
509         }
510         return remaining;
511 }