Fix sequencing when there is video+subtitle content.
[dcpomatic.git] / src / lib / playlist.cc
1 /*
2     Copyright (C) 2013-2016 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "playlist.h"
21 #include "sndfile_content.h"
22 #include "sndfile_decoder.h"
23 #include "video_content.h"
24 #include "ffmpeg_decoder.h"
25 #include "ffmpeg_content.h"
26 #include "image_decoder.h"
27 #include "content_factory.h"
28 #include "dcp_content.h"
29 #include "job.h"
30 #include "config.h"
31 #include "util.h"
32 #include "md5_digester.h"
33 #include <libcxml/cxml.h>
34 #include <libxml++/libxml++.h>
35 #include <boost/shared_ptr.hpp>
36 #include <boost/foreach.hpp>
37 #include <iostream>
38
39 #include "i18n.h"
40
41 using std::list;
42 using std::cout;
43 using std::vector;
44 using std::min;
45 using std::max;
46 using std::string;
47 using std::pair;
48 using boost::optional;
49 using boost::shared_ptr;
50 using boost::weak_ptr;
51 using boost::dynamic_pointer_cast;
52
53 Playlist::Playlist ()
54         : _sequence (true)
55         , _sequencing (false)
56 {
57
58 }
59
60 Playlist::~Playlist ()
61 {
62         _content.clear ();
63         reconnect ();
64 }
65
66 void
67 Playlist::content_changed (weak_ptr<Content> content, int property, bool frequent)
68 {
69         if (property == ContentProperty::LENGTH || property == VideoContentProperty::VIDEO_FRAME_TYPE) {
70                 /* Don't respond to position changes here, as:
71                    - sequencing after earlier/later changes is handled by move_earlier/move_later
72                    - any other position changes will be timeline drags which should not result in content
73                    being sequenced.
74                 */
75                 maybe_sequence ();
76         }
77
78         if (
79                 property == ContentProperty::POSITION ||
80                 property == ContentProperty::LENGTH ||
81                 property == ContentProperty::TRIM_START ||
82                 property == ContentProperty::TRIM_END) {
83
84                 ContentList old = _content;
85                 sort (_content.begin(), _content.end(), ContentSorter ());
86                 if (_content != old) {
87                         OrderChanged ();
88                 }
89         }
90
91         ContentChanged (content, property, frequent);
92 }
93
94 void
95 Playlist::maybe_sequence ()
96 {
97         if (!_sequence || _sequencing) {
98                 return;
99         }
100
101         _sequencing = true;
102
103         /* Keep track of the content that we've set the position of so that we don't
104            do it twice.
105         */
106         ContentList placed;
107
108         /* Video */
109
110         DCPTime next_left;
111         DCPTime next_right;
112         BOOST_FOREACH (shared_ptr<Content> i, _content) {
113                 shared_ptr<VideoContent> vc = dynamic_pointer_cast<VideoContent> (i);
114                 if (!vc) {
115                         continue;
116                 }
117
118                 if (vc->video_frame_type() == VIDEO_FRAME_TYPE_3D_RIGHT) {
119                         vc->set_position (next_right);
120                         next_right = vc->end();
121                 } else {
122                         vc->set_position (next_left);
123                         next_left = vc->end();
124                 }
125
126                 placed.push_back (vc);
127         }
128
129         /* Subtitles */
130
131         DCPTime next;
132         BOOST_FOREACH (shared_ptr<Content> i, _content) {
133                 shared_ptr<SubtitleContent> sc = dynamic_pointer_cast<SubtitleContent> (i);
134                 if (!sc || !sc->has_subtitles() || find (placed.begin(), placed.end(), i) != placed.end()) {
135                         continue;
136                 }
137
138                 sc->set_position (next);
139                 next = sc->end();
140         }
141
142
143         /* This won't change order, so it does not need a sort */
144
145         _sequencing = false;
146 }
147
148 string
149 Playlist::video_identifier () const
150 {
151         string t;
152
153         BOOST_FOREACH (shared_ptr<const Content> i, _content) {
154                 shared_ptr<const VideoContent> vc = dynamic_pointer_cast<const VideoContent> (i);
155                 shared_ptr<const SubtitleContent> sc = dynamic_pointer_cast<const SubtitleContent> (i);
156                 if (vc) {
157                         t += vc->identifier ();
158                 } else if (sc && sc->burn_subtitles ()) {
159                         t += sc->identifier ();
160                 }
161         }
162
163         MD5Digester digester;
164         digester.add (t.c_str(), t.length());
165         return digester.get ();
166 }
167
168 /** @param node <Playlist> node */
169 void
170 Playlist::set_from_xml (shared_ptr<const Film> film, cxml::ConstNodePtr node, int version, list<string>& notes)
171 {
172         BOOST_FOREACH (cxml::NodePtr i, node->node_children ("Content")) {
173                 _content.push_back (content_factory (film, i, version, notes));
174         }
175
176         /* This shouldn't be necessary but better safe than sorry (there could be old files) */
177         sort (_content.begin(), _content.end(), ContentSorter ());
178
179         reconnect ();
180 }
181
182 /** @param node <Playlist> node */
183 void
184 Playlist::as_xml (xmlpp::Node* node)
185 {
186         BOOST_FOREACH (shared_ptr<Content> i, _content) {
187                 i->as_xml (node->add_child ("Content"));
188         }
189 }
190
191 void
192 Playlist::add (shared_ptr<Content> c)
193 {
194         _content.push_back (c);
195         sort (_content.begin(), _content.end(), ContentSorter ());
196         reconnect ();
197         Changed ();
198 }
199
200 void
201 Playlist::remove (shared_ptr<Content> c)
202 {
203         ContentList::iterator i = _content.begin ();
204         while (i != _content.end() && *i != c) {
205                 ++i;
206         }
207
208         if (i != _content.end ()) {
209                 _content.erase (i);
210                 Changed ();
211         }
212
213         /* This won't change order, so it does not need a sort */
214 }
215
216 void
217 Playlist::remove (ContentList c)
218 {
219         BOOST_FOREACH (shared_ptr<Content> i, c) {
220                 ContentList::iterator j = _content.begin ();
221                 while (j != _content.end() && *j != i) {
222                         ++j;
223                 }
224
225                 if (j != _content.end ()) {
226                         _content.erase (j);
227                 }
228         }
229
230         /* This won't change order, so it does not need a sort */
231
232         Changed ();
233 }
234
235 class FrameRateCandidate
236 {
237 public:
238         FrameRateCandidate (float source_, int dcp_)
239                 : source (source_)
240                 , dcp (dcp_)
241         {}
242
243         float source;
244         int dcp;
245 };
246
247 int
248 Playlist::best_dcp_frame_rate () const
249 {
250         list<int> const allowed_dcp_frame_rates = Config::instance()->allowed_dcp_frame_rates ();
251
252         /* Work out what rates we could manage, including those achieved by using skip / repeat */
253         list<FrameRateCandidate> candidates;
254
255         /* Start with the ones without skip / repeat so they will get matched in preference to skipped/repeated ones */
256         for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
257                 candidates.push_back (FrameRateCandidate (*i, *i));
258         }
259
260         /* Then the skip/repeat ones */
261         for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
262                 candidates.push_back (FrameRateCandidate (float (*i) / 2, *i));
263                 candidates.push_back (FrameRateCandidate (float (*i) * 2, *i));
264         }
265
266         /* Pick the best one */
267         float error = std::numeric_limits<float>::max ();
268         optional<FrameRateCandidate> best;
269         list<FrameRateCandidate>::iterator i = candidates.begin();
270         while (i != candidates.end()) {
271
272                 float this_error = 0;
273                 BOOST_FOREACH (shared_ptr<Content> j, _content) {
274                         shared_ptr<VideoContent> vc = dynamic_pointer_cast<VideoContent> (j);
275                         if (!vc || !vc->has_own_video_frame_rate()) {
276                                 continue;
277                         }
278
279                         /* Best error for this content; we could use the content as-is or double its rate */
280                         float best_error = min (
281                                 float (fabs (i->source - vc->video_frame_rate ())),
282                                 float (fabs (i->source - vc->video_frame_rate () * 2))
283                                 );
284
285                         /* Use the largest difference between DCP and source as the "error" */
286                         this_error = max (this_error, best_error);
287                 }
288
289                 if (this_error < error) {
290                         error = this_error;
291                         best = *i;
292                 }
293
294                 ++i;
295         }
296
297         if (!best) {
298                 return 24;
299         }
300
301         return best->dcp;
302 }
303
304 /** @return length of the playlist from time 0 to the last thing on the playlist */
305 DCPTime
306 Playlist::length () const
307 {
308         DCPTime len;
309         BOOST_FOREACH (shared_ptr<const Content> i, _content) {
310                 len = max (len, i->end());
311         }
312
313         return len;
314 }
315
316 /** @return position of the first thing on the playlist, if it's not empty */
317 optional<DCPTime>
318 Playlist::start () const
319 {
320         if (_content.empty ()) {
321                 return optional<DCPTime> ();
322         }
323
324         DCPTime start = DCPTime::max ();
325         BOOST_FOREACH (shared_ptr<Content> i, _content) {
326                 start = min (start, i->position ());
327         }
328
329         return start;
330 }
331
332 void
333 Playlist::reconnect ()
334 {
335         for (list<boost::signals2::connection>::iterator i = _content_connections.begin(); i != _content_connections.end(); ++i) {
336                 i->disconnect ();
337         }
338
339         _content_connections.clear ();
340
341         BOOST_FOREACH (shared_ptr<Content> i, _content) {
342                 _content_connections.push_back (i->Changed.connect (bind (&Playlist::content_changed, this, _1, _2, _3)));
343         }
344 }
345
346 DCPTime
347 Playlist::video_end () const
348 {
349         DCPTime end;
350         BOOST_FOREACH (shared_ptr<Content> i, _content) {
351                 if (dynamic_pointer_cast<const VideoContent> (i)) {
352                         end = max (end, i->end ());
353                 }
354         }
355
356         return end;
357 }
358
359 DCPTime
360 Playlist::subtitle_end () const
361 {
362         DCPTime end;
363         BOOST_FOREACH (shared_ptr<Content> i, _content) {
364                 if (dynamic_pointer_cast<const SubtitleContent> (i)) {
365                         end = max (end, i->end ());
366                 }
367         }
368
369         return end;
370 }
371
372 FrameRateChange
373 Playlist::active_frame_rate_change (DCPTime t, int dcp_video_frame_rate) const
374 {
375         for (ContentList::const_reverse_iterator i = _content.rbegin(); i != _content.rend(); ++i) {
376                 shared_ptr<const VideoContent> vc = dynamic_pointer_cast<const VideoContent> (*i);
377                 if (!vc) {
378                         continue;
379                 }
380
381                 if (vc->position() <= t) {
382                         /* This is the first piece of content (going backwards...) that starts before t,
383                            so it's the active one.
384                         */
385                         return FrameRateChange (vc->video_frame_rate(), dcp_video_frame_rate);
386                 }
387         }
388
389         return FrameRateChange (dcp_video_frame_rate, dcp_video_frame_rate);
390 }
391
392 void
393 Playlist::set_sequence (bool s)
394 {
395         _sequence = s;
396 }
397
398 bool
399 ContentSorter::operator() (shared_ptr<Content> a, shared_ptr<Content> b)
400 {
401         if (a->position() != b->position()) {
402                 return a->position() < b->position();
403         }
404
405         /* Put video before audio if they start at the same time */
406         if (dynamic_pointer_cast<VideoContent>(a) && !dynamic_pointer_cast<VideoContent>(b)) {
407                 return true;
408         } else if (!dynamic_pointer_cast<VideoContent>(a) && dynamic_pointer_cast<VideoContent>(b)) {
409                 return false;
410         }
411
412         /* Last resort */
413         return a->digest() < b->digest();
414 }
415
416 /** @return content in ascending order of position */
417 ContentList
418 Playlist::content () const
419 {
420         return _content;
421 }
422
423 void
424 Playlist::repeat (ContentList c, int n)
425 {
426         pair<DCPTime, DCPTime> range (DCPTime::max (), DCPTime ());
427         BOOST_FOREACH (shared_ptr<Content> i, c) {
428                 range.first = min (range.first, i->position ());
429                 range.second = max (range.second, i->position ());
430                 range.first = min (range.first, i->end ());
431                 range.second = max (range.second, i->end ());
432         }
433
434         DCPTime pos = range.second;
435         for (int i = 0; i < n; ++i) {
436                 BOOST_FOREACH (shared_ptr<Content> j, c) {
437                         shared_ptr<Content> copy = j->clone ();
438                         copy->set_position (pos + copy->position() - range.first);
439                         _content.push_back (copy);
440                 }
441                 pos += range.second - range.first;
442         }
443
444         sort (_content.begin(), _content.end(), ContentSorter ());
445
446         reconnect ();
447         Changed ();
448 }
449
450 void
451 Playlist::move_earlier (shared_ptr<Content> c)
452 {
453         ContentList::iterator previous = _content.end ();
454         ContentList::iterator i = _content.begin();
455         while (i != _content.end() && *i != c) {
456                 previous = i;
457                 ++i;
458         }
459
460         DCPOMATIC_ASSERT (i != _content.end ());
461         if (previous == _content.end ()) {
462                 return;
463         }
464
465         shared_ptr<Content> previous_c = *previous;
466
467         DCPTime const p = previous_c->position ();
468         previous_c->set_position (p + c->length_after_trim ());
469         c->set_position (p);
470 }
471
472 void
473 Playlist::move_later (shared_ptr<Content> c)
474 {
475         ContentList::iterator i = _content.begin();
476         while (i != _content.end() && *i != c) {
477                 ++i;
478         }
479
480         DCPOMATIC_ASSERT (i != _content.end ());
481
482         ContentList::iterator next = i;
483         ++next;
484
485         if (next == _content.end ()) {
486                 return;
487         }
488
489         shared_ptr<Content> next_c = *next;
490
491         next_c->set_position (c->position ());
492         c->set_position (c->position() + next_c->length_after_trim ());
493 }
494
495 int64_t
496 Playlist::required_disk_space (int j2k_bandwidth, int audio_channels, int audio_frame_rate) const
497 {
498         int64_t video = uint64_t (j2k_bandwidth / 8) * length().seconds ();
499         int64_t audio = uint64_t (audio_channels * audio_frame_rate * 3) * length().seconds ();
500
501         BOOST_FOREACH (shared_ptr<Content> i, _content) {
502                 shared_ptr<DCPContent> d = dynamic_pointer_cast<DCPContent> (i);
503                 if (d) {
504                         if (d->reference_video()) {
505                                 video -= uint64_t (j2k_bandwidth / 8) * d->length_after_trim().seconds();
506                         }
507                         if (d->reference_audio()) {
508                                 audio -= uint64_t (audio_channels * audio_frame_rate * 3) * d->length_after_trim().seconds();
509                         }
510                 }
511         }
512
513         /* Add on 64k for bits and pieces (metadata, subs etc) */
514         return video + audio + 65536;
515 }