]> git.sesse.net Git - nageru/blob - futatabi/player.cpp
Factor out estimated time left calculation into its own function.
[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/mux.h"
12 #include "shared/timebase.h"
13 #include "video_stream.h"
14
15 #include <algorithm>
16 #include <chrono>
17 #include <condition_variable>
18 #include <movit/util.h>
19 #include <mutex>
20 #include <stdio.h>
21 #include <thread>
22 #include <vector>
23
24 using namespace std;
25 using namespace std::chrono;
26
27 extern HTTPD *global_httpd;
28
29 void Player::thread_func(Player::StreamOutput stream_output, AVFormatContext *file_avctx)
30 {
31         pthread_setname_np(pthread_self(), "Player");
32
33         QSurface *surface = create_surface();
34         QOpenGLContext *context = create_context(surface);
35         if (!make_current(context, surface)) {
36                 printf("oops\n");
37                 exit(1);
38         }
39
40         check_error();
41
42         // Create the VideoStream object, now that we have an OpenGL context.
43         if (stream_output != NO_STREAM_OUTPUT) {
44                 video_stream.reset(new VideoStream(file_avctx));
45                 video_stream->start();
46         }
47
48         check_error();
49
50         int64_t pts = 0;
51         Clip next_clip;
52         size_t next_clip_idx = size_t(-1);
53         bool got_next_clip = false;
54         double next_clip_fade_time = -1.0;
55
56         while (!should_quit) {
57 wait_for_clip:
58                 bool clip_ready;
59                 steady_clock::time_point before_sleep = steady_clock::now();
60
61                 // Wait until we're supposed to play something.
62                 {
63                         unique_lock<mutex> lock(queue_state_mu);
64                         clip_ready = new_clip_changed.wait_for(lock, milliseconds(100), [this] {
65                                 return should_quit || (new_clip_ready && current_clip.pts_in != -1);
66                         });
67                         if (should_quit) {
68                                 return;
69                         }
70                         new_clip_ready = false;
71                         playing = true;
72                 }
73
74                 steady_clock::duration time_slept = steady_clock::now() - before_sleep;
75                 pts += duration_cast<duration<size_t, TimebaseRatio>>(time_slept).count();
76
77                 if (!clip_ready) {
78                         if (video_stream != nullptr) {
79                                 video_stream->schedule_refresh_frame(steady_clock::now(), pts, /*display_func=*/nullptr, QueueSpotHolder());
80                         }
81                         continue;
82                 }
83
84                 Clip clip;
85                 size_t clip_idx;
86                 unsigned stream_idx;
87                 {
88                         lock_guard<mutex> lock(mu);
89                         clip = current_clip;
90                         clip_idx = current_clip_idx;
91                         stream_idx = current_stream_idx;
92                 }
93                 steady_clock::time_point origin = steady_clock::now();  // TODO: Add a 100 ms buffer for ramp-up?
94                 int64_t in_pts_origin = clip.pts_in;
95 got_clip:
96                 int64_t out_pts_origin = pts;
97
98                 // Start playing exactly at a frame.
99                 // TODO: Snap secondary (fade-to) clips in the same fashion
100                 // so that we don't get jank here).
101                 {
102                         lock_guard<mutex> lock(frame_mu);
103
104                         // Find the first frame such that frame.pts <= in_pts.
105                         auto it = find_last_frame_before(frames[stream_idx], in_pts_origin);
106                         if (it != frames[stream_idx].end()) {
107                                 in_pts_origin = it->pts;
108                         }
109                 }
110
111                 // TODO: Lock to a rational multiple of the frame rate if possible.
112                 double speed = 0.5;
113
114                 int64_t in_pts_start_next_clip = -1;
115                 steady_clock::time_point next_frame_start;
116                 for (int frameno = 0; !should_quit; ++frameno) {  // Ends when the clip ends.
117                         double out_pts = out_pts_origin + TIMEBASE * frameno / global_flags.output_framerate;
118                         next_frame_start =
119                                 origin + microseconds(lrint((out_pts - out_pts_origin) * 1e6 / TIMEBASE));
120                         int64_t in_pts = lrint(in_pts_origin + TIMEBASE * frameno * speed / global_flags.output_framerate);
121                         pts = lrint(out_pts);
122
123                         if (in_pts >= clip.pts_out) {
124                                 break;
125                         }
126
127                         steady_clock::duration time_behind = steady_clock::now() - next_frame_start;
128                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(200)) {
129                                 fprintf(stderr, "WARNING: %ld ms behind, dropping a frame (no matter the type).\n",
130                                         lrint(1e3 * duration<double>(time_behind).count()));
131                                 continue;
132                         }
133
134                         double time_left_this_clip = double(clip.pts_out - in_pts) / TIMEBASE / 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 = (next_clip.pts_out - next_clip.pts_in) / TIMEBASE / 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 * 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 * 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 / speed;
178                                 double total_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / 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 / speed;
183                                         double total_next_length = double(next_clip.pts_out - next_clip.pts_in) / TIMEBASE / 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                                                 video_stream->schedule_original_frame(
249                                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
250                                                         frame_lower);
251                                         } else {
252                                                 assert(secondary_frame.pts != -1);
253                                                 video_stream->schedule_faded_frame(next_frame_start, pts, display_func,
254                                                         QueueSpotHolder(this), frame_lower,
255                                                         secondary_frame, fade_alpha);
256                                         }
257                                 }
258                                 continue;
259                         }
260
261                         // Snap to input frame: If we can do so with less than 1% jitter
262                         // (ie., move less than 1% of an _output_ frame), do so.
263                         // TODO: Snap secondary (fade-to) clips in the same fashion.
264                         bool snapped = false;
265                         for (FrameOnDisk snap_frame : { frame_lower, frame_upper }) {
266                                 double snap_pts_as_frameno = (snap_frame.pts - in_pts_origin) * global_flags.output_framerate / TIMEBASE / speed;
267                                 if (fabs(snap_pts_as_frameno - frameno) < 0.01) {
268                                         auto display_func = [this, primary_stream_idx, snap_frame, secondary_frame, fade_alpha]{
269                                                 if (destination != nullptr) {
270                                                         destination->setFrame(primary_stream_idx, snap_frame, secondary_frame, fade_alpha);
271                                                 }
272                                         };
273                                         if (video_stream == nullptr) {
274                                                 display_func();
275                                         } else {
276                                                 if (secondary_stream_idx == -1) {
277                                                         video_stream->schedule_original_frame(
278                                                                 next_frame_start, pts, display_func,
279                                                                 QueueSpotHolder(this), snap_frame);
280                                                 } else {
281                                                         assert(secondary_frame.pts != -1);
282                                                         video_stream->schedule_faded_frame(
283                                                                 next_frame_start, pts, display_func, QueueSpotHolder(this),
284                                                                 snap_frame, secondary_frame, fade_alpha);
285                                                 }
286                                         }
287                                         in_pts_origin += snap_frame.pts - in_pts;
288                                         snapped = true;
289                                         break;
290                                 }
291                         }
292                         if (snapped) {
293                                 continue;
294                         }
295
296                         if (stream_output != FILE_STREAM_OUTPUT && time_behind >= milliseconds(100)) {
297                                 fprintf(stderr, "WARNING: %ld ms behind, dropping an interpolated frame.\n",
298                                         lrint(1e3 * duration<double>(time_behind).count()));
299                                 continue;
300                         }
301
302                         double alpha = double(in_pts - frame_lower.pts) / (frame_upper.pts - frame_lower.pts);
303
304                         if (video_stream == nullptr) {
305                                 // Previews don't do any interpolation.
306                                 assert(secondary_stream_idx == -1);
307                                 if (destination != nullptr) {
308                                         destination->setFrame(primary_stream_idx, frame_lower);
309                                 }
310                         } else {
311                                 auto display_func = [this](shared_ptr<Frame> frame) {
312                                         if (destination != nullptr) {
313                                                 destination->setFrame(frame);
314                                         }
315                                 };
316                                 video_stream->schedule_interpolated_frame(
317                                         next_frame_start, pts, display_func, QueueSpotHolder(this),
318                                         frame_lower, frame_upper, alpha,
319                                         secondary_frame, fade_alpha);
320                         }
321                 }
322
323                 if (should_quit) {
324                         return;
325                 }
326
327                 // The clip ended.
328
329                 // Last-ditch effort to get the next clip (if e.g. the fade time was zero seconds).
330                 if (!got_next_clip && next_clip_callback != nullptr) {
331                         tie(next_clip, next_clip_idx) = next_clip_callback();
332                         if (next_clip.pts_in != -1) {
333                                 got_next_clip = true;
334                                 in_pts_start_next_clip = next_clip.pts_in;
335                         }
336                 }
337
338                 // Switch to next clip if we got it.
339                 if (got_next_clip) {
340                         clip = next_clip;
341                         clip_idx = next_clip_idx;
342                         stream_idx = next_clip.stream_idx;  // Override is used for previews only, and next_clip is used for live ony.
343                         if (done_callback != nullptr) {
344                                 done_callback();
345                         }
346                         got_next_clip = false;
347
348                         // Start the next clip from the point where the fade went out.
349                         origin = next_frame_start;
350                         in_pts_origin = in_pts_start_next_clip;
351                         goto got_clip;
352                 }
353
354                 {
355                         unique_lock<mutex> lock(queue_state_mu);
356                         playing = false;
357                 }
358                 if (done_callback != nullptr) {
359                         done_callback();
360                 }
361         }
362 }
363
364 // Find the frame immediately before and after this point.
365 bool Player::find_surrounding_frames(int64_t pts, int stream_idx, FrameOnDisk *frame_lower, FrameOnDisk *frame_upper)
366 {
367         lock_guard<mutex> lock(frame_mu);
368
369         // Find the first frame such that frame.pts >= pts.
370         auto it = find_last_frame_before(frames[stream_idx], pts);
371         if (it == frames[stream_idx].end()) {
372                 return false;
373         }
374         *frame_upper = *it;
375
376         // Find the last frame such that in_pts <= frame.pts (if any).
377         if (it == frames[stream_idx].begin()) {
378                 *frame_lower = *it;
379         } else {
380                 *frame_lower = *(it - 1);
381         }
382         assert(pts >= frame_lower->pts);
383         assert(pts <= frame_upper->pts);
384         return true;
385 }
386
387 Player::Player(JPEGFrameView *destination, Player::StreamOutput stream_output, AVFormatContext *file_avctx)
388         : destination(destination)
389 {
390         player_thread = thread(&Player::thread_func, this, stream_output, file_avctx);
391 }
392
393 Player::~Player()
394 {
395         should_quit = true;
396         if (video_stream != nullptr) {
397                 video_stream->stop();
398         }
399         new_clip_changed.notify_all();
400         player_thread.join();
401 }
402
403 void Player::play_clip(const Clip &clip, size_t clip_idx, unsigned stream_idx)
404 {
405         {
406                 lock_guard<mutex> lock(mu);
407                 current_clip = clip;
408                 current_stream_idx = stream_idx;
409                 current_clip_idx = clip_idx;
410         }
411
412         {
413                 lock_guard<mutex> lock(queue_state_mu);
414                 new_clip_ready = true;
415                 override_stream_idx = -1;
416                 new_clip_changed.notify_all();
417         }
418 }
419
420 void Player::override_angle(unsigned stream_idx)
421 {
422         // Corner case: If a new clip is waiting to be played, change its stream and then we're done.
423         {
424                 unique_lock<mutex> lock(queue_state_mu);
425                 if (new_clip_ready) {
426                         lock_guard<mutex> lock2(mu);
427                         current_stream_idx = stream_idx;
428                         return;
429                 }
430         }
431
432         // If we are playing a clip, set override_stream_idx, and the player thread will
433         // pick it up and change its internal index.
434         {
435                 unique_lock<mutex> lock(queue_state_mu);
436                 if (playing) {
437                         override_stream_idx = stream_idx;
438                         new_clip_changed.notify_all();
439                 }
440         }
441
442         // OK, so we're standing still, presumably at the end of a clip.
443         // Look at the current pts_out (if it exists), and show the closest
444         // thing we've got.
445         int64_t pts_out;
446         {
447                 lock_guard<mutex> lock(mu);
448                 if (current_clip.pts_out < 0) {
449                         return;
450                 }
451                 pts_out = current_clip.pts_out;
452         }
453
454         lock_guard<mutex> lock(frame_mu);
455         auto it = find_first_frame_at_or_after(frames[stream_idx], pts_out);
456         if (it == frames[stream_idx].end()) {
457                 return;
458         }
459         destination->setFrame(stream_idx, *it);
460 }
461
462 void Player::take_queue_spot()
463 {
464         unique_lock<mutex> lock(queue_state_mu);
465         ++num_queued_frames;
466 }
467
468 void Player::release_queue_spot()
469 {
470         unique_lock<mutex> lock(queue_state_mu);
471         assert(num_queued_frames > 0);
472         --num_queued_frames;
473         new_clip_changed.notify_all();
474 }
475
476 double compute_time_left(const vector<Clip> &clips, const map<size_t, double> &progress)
477 {
478         // Look at the last clip and then start counting from there.
479         assert(!progress.empty());
480         auto last_it = progress.end();
481         --last_it;
482         double remaining = 0.0;
483         double last_fade_time_seconds = 0.0;
484         for (size_t row = last_it->first; row < clips.size(); ++row) {
485                 const Clip &clip = clips[row];
486                 double clip_length = double(clip.pts_out - clip.pts_in) / TIMEBASE / 0.5;  // FIXME: stop hardcoding speed.
487                 if (row == last_it->first) {
488                         // A clip we're playing: Subtract the part we've already played.
489                         remaining = clip_length * (1.0 - last_it->second);
490                 } else {
491                         // A clip we haven't played yet: Subtract the part that's overlapping
492                         // with a previous clip (due to fade).
493                         remaining += max(clip_length - last_fade_time_seconds, 0.0);
494                 }
495                 last_fade_time_seconds = min(clip_length, clip.fade_time_seconds);
496         }
497         return remaining;
498 }