Remove Sndfile code and use FFmpeg instead.
[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 "video_content.h"
22 #include "subtitle_content.h"
23 #include "ffmpeg_decoder.h"
24 #include "ffmpeg_content.h"
25 #include "image_decoder.h"
26 #include "content_factory.h"
27 #include "dcp_content.h"
28 #include "job.h"
29 #include "config.h"
30 #include "util.h"
31 #include "md5_digester.h"
32 #include <libcxml/cxml.h>
33 #include <libxml++/libxml++.h>
34 #include <boost/shared_ptr.hpp>
35 #include <boost/foreach.hpp>
36 #include <iostream>
37
38 #include "i18n.h"
39
40 using std::list;
41 using std::cout;
42 using std::vector;
43 using std::min;
44 using std::max;
45 using std::string;
46 using std::pair;
47 using boost::optional;
48 using boost::shared_ptr;
49 using boost::weak_ptr;
50 using boost::dynamic_pointer_cast;
51
52 Playlist::Playlist ()
53         : _sequence (true)
54         , _sequencing (false)
55 {
56
57 }
58
59 Playlist::~Playlist ()
60 {
61         _content.clear ();
62         reconnect ();
63 }
64
65 void
66 Playlist::content_changed (weak_ptr<Content> content, int property, bool frequent)
67 {
68         if (property == ContentProperty::LENGTH || property == VideoContentProperty::FRAME_TYPE) {
69                 /* Don't respond to position changes here, as:
70                    - sequencing after earlier/later changes is handled by move_earlier/move_later
71                    - any other position changes will be timeline drags which should not result in content
72                    being sequenced.
73                 */
74                 maybe_sequence ();
75         }
76
77         if (
78                 property == ContentProperty::POSITION ||
79                 property == ContentProperty::LENGTH ||
80                 property == ContentProperty::TRIM_START ||
81                 property == ContentProperty::TRIM_END) {
82
83                 ContentList old = _content;
84                 sort (_content.begin(), _content.end(), ContentSorter ());
85                 if (_content != old) {
86                         OrderChanged ();
87                 }
88         }
89
90         ContentChanged (content, property, frequent);
91 }
92
93 void
94 Playlist::maybe_sequence ()
95 {
96         if (!_sequence || _sequencing) {
97                 return;
98         }
99
100         _sequencing = true;
101
102         /* Keep track of the content that we've set the position of so that we don't
103            do it twice.
104         */
105         ContentList placed;
106
107         /* Video */
108
109         DCPTime next_left;
110         DCPTime next_right;
111         BOOST_FOREACH (shared_ptr<Content> i, _content) {
112                 if (!i->video) {
113                         continue;
114                 }
115
116                 if (i->video->frame_type() == VIDEO_FRAME_TYPE_3D_RIGHT) {
117                         i->set_position (next_right);
118                         next_right = i->end();
119                 } else {
120                         i->set_position (next_left);
121                         next_left = i->end();
122                 }
123
124                 placed.push_back (i);
125         }
126
127         /* Subtitles */
128
129         DCPTime next;
130         BOOST_FOREACH (shared_ptr<Content> i, _content) {
131                 if (!i->subtitle || find (placed.begin(), placed.end(), i) != placed.end()) {
132                         continue;
133                 }
134
135                 i->set_position (next);
136                 next = i->end();
137         }
138
139
140         /* This won't change order, so it does not need a sort */
141
142         _sequencing = false;
143 }
144
145 string
146 Playlist::video_identifier () const
147 {
148         string t;
149
150         BOOST_FOREACH (shared_ptr<const Content> i, _content) {
151                 if (i->video || (i->subtitle && i->subtitle->burn())) {
152                         t += i->identifier ();
153                 }
154         }
155
156         MD5Digester digester;
157         digester.add (t.c_str(), t.length());
158         return digester.get ();
159 }
160
161 /** @param node <Playlist> node */
162 void
163 Playlist::set_from_xml (shared_ptr<const Film> film, cxml::ConstNodePtr node, int version, list<string>& notes)
164 {
165         BOOST_FOREACH (cxml::NodePtr i, node->node_children ("Content")) {
166                 _content.push_back (content_factory (film, i, version, notes));
167         }
168
169         /* This shouldn't be necessary but better safe than sorry (there could be old files) */
170         sort (_content.begin(), _content.end(), ContentSorter ());
171
172         reconnect ();
173 }
174
175 /** @param node <Playlist> node */
176 void
177 Playlist::as_xml (xmlpp::Node* node)
178 {
179         BOOST_FOREACH (shared_ptr<Content> i, _content) {
180                 i->as_xml (node->add_child ("Content"));
181         }
182 }
183
184 void
185 Playlist::add (shared_ptr<Content> c)
186 {
187         _content.push_back (c);
188         sort (_content.begin(), _content.end(), ContentSorter ());
189         reconnect ();
190         Changed ();
191 }
192
193 void
194 Playlist::remove (shared_ptr<Content> c)
195 {
196         ContentList::iterator i = _content.begin ();
197         while (i != _content.end() && *i != c) {
198                 ++i;
199         }
200
201         if (i != _content.end ()) {
202                 _content.erase (i);
203                 Changed ();
204         }
205
206         /* This won't change order, so it does not need a sort */
207 }
208
209 void
210 Playlist::remove (ContentList c)
211 {
212         BOOST_FOREACH (shared_ptr<Content> i, c) {
213                 ContentList::iterator j = _content.begin ();
214                 while (j != _content.end() && *j != i) {
215                         ++j;
216                 }
217
218                 if (j != _content.end ()) {
219                         _content.erase (j);
220                 }
221         }
222
223         /* This won't change order, so it does not need a sort */
224
225         Changed ();
226 }
227
228 class FrameRateCandidate
229 {
230 public:
231         FrameRateCandidate (float source_, int dcp_)
232                 : source (source_)
233                 , dcp (dcp_)
234         {}
235
236         float source;
237         int dcp;
238 };
239
240 int
241 Playlist::best_video_frame_rate () const
242 {
243         list<int> const allowed_dcp_frame_rates = Config::instance()->allowed_dcp_frame_rates ();
244
245         /* Work out what rates we could manage, including those achieved by using skip / repeat */
246         list<FrameRateCandidate> candidates;
247
248         /* Start with the ones without skip / repeat so they will get matched in preference to skipped/repeated ones */
249         for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
250                 candidates.push_back (FrameRateCandidate (*i, *i));
251         }
252
253         /* Then the skip/repeat ones */
254         for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
255                 candidates.push_back (FrameRateCandidate (float (*i) / 2, *i));
256                 candidates.push_back (FrameRateCandidate (float (*i) * 2, *i));
257         }
258
259         /* Pick the best one */
260         float error = std::numeric_limits<float>::max ();
261         optional<FrameRateCandidate> best;
262         list<FrameRateCandidate>::iterator i = candidates.begin();
263         while (i != candidates.end()) {
264
265                 float this_error = 0;
266                 BOOST_FOREACH (shared_ptr<Content> j, _content) {
267                         if (!j->video || !j->video_frame_rate()) {
268                                 continue;
269                         }
270
271                         /* Best error for this content; we could use the content as-is or double its rate */
272                         float best_error = min (
273                                 float (fabs (i->source - j->video_frame_rate().get())),
274                                 float (fabs (i->source - j->video_frame_rate().get() * 2))
275                                 );
276
277                         /* Use the largest difference between DCP and source as the "error" */
278                         this_error = max (this_error, best_error);
279                 }
280
281                 if (this_error < error) {
282                         error = this_error;
283                         best = *i;
284                 }
285
286                 ++i;
287         }
288
289         if (!best) {
290                 return 24;
291         }
292
293         return best->dcp;
294 }
295
296 /** @return length of the playlist from time 0 to the last thing on the playlist */
297 DCPTime
298 Playlist::length () const
299 {
300         DCPTime len;
301         BOOST_FOREACH (shared_ptr<const Content> i, _content) {
302                 len = max (len, i->end());
303         }
304
305         return len;
306 }
307
308 /** @return position of the first thing on the playlist, if it's not empty */
309 optional<DCPTime>
310 Playlist::start () const
311 {
312         if (_content.empty ()) {
313                 return optional<DCPTime> ();
314         }
315
316         DCPTime start = DCPTime::max ();
317         BOOST_FOREACH (shared_ptr<Content> i, _content) {
318                 start = min (start, i->position ());
319         }
320
321         return start;
322 }
323
324 void
325 Playlist::reconnect ()
326 {
327         for (list<boost::signals2::connection>::iterator i = _content_connections.begin(); i != _content_connections.end(); ++i) {
328                 i->disconnect ();
329         }
330
331         _content_connections.clear ();
332
333         BOOST_FOREACH (shared_ptr<Content> i, _content) {
334                 _content_connections.push_back (i->Changed.connect (bind (&Playlist::content_changed, this, _1, _2, _3)));
335         }
336 }
337
338 DCPTime
339 Playlist::video_end () const
340 {
341         DCPTime end;
342         BOOST_FOREACH (shared_ptr<Content> i, _content) {
343                 if (i->video) {
344                         end = max (end, i->end ());
345                 }
346         }
347
348         return end;
349 }
350
351 DCPTime
352 Playlist::subtitle_end () const
353 {
354         DCPTime end;
355         BOOST_FOREACH (shared_ptr<Content> i, _content) {
356                 if (i->subtitle) {
357                         end = max (end, i->end ());
358                 }
359         }
360
361         return end;
362 }
363
364 FrameRateChange
365 Playlist::active_frame_rate_change (DCPTime t, int dcp_video_frame_rate) const
366 {
367         for (ContentList::const_reverse_iterator i = _content.rbegin(); i != _content.rend(); ++i) {
368                 if (!(*i)->video) {
369                         continue;
370                 }
371
372                 if ((*i)->position() <= t) {
373                         /* This is the first piece of content (going backwards...) that starts before t,
374                            so it's the active one.
375                         */
376                         if ((*i)->video_frame_rate ()) {
377                                 /* This content specified a rate, so use it */
378                                 return FrameRateChange ((*i)->video_frame_rate().get(), dcp_video_frame_rate);
379                         } else {
380                                 /* No specified rate so just use the DCP one */
381                                 return FrameRateChange (dcp_video_frame_rate, dcp_video_frame_rate);
382                         }
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 }