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