Some allowances for video/audio/subtitle possibly being null.
[dcpomatic.git] / src / lib / ffmpeg_content.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 "ffmpeg_content.h"
21 #include "video_content.h"
22 #include "audio_content.h"
23 #include "ffmpeg_examiner.h"
24 #include "ffmpeg_subtitle_stream.h"
25 #include "ffmpeg_audio_stream.h"
26 #include "compose.hpp"
27 #include "job.h"
28 #include "util.h"
29 #include "filter.h"
30 #include "film.h"
31 #include "log.h"
32 #include "exceptions.h"
33 #include "frame_rate_change.h"
34 #include "safe_stringstream.h"
35 #include "raw_convert.h"
36 #include "subtitle_content.h"
37 #include <libcxml/cxml.h>
38 extern "C" {
39 #include <libavformat/avformat.h>
40 #include <libavutil/pixdesc.h>
41 }
42 #include <libxml++/libxml++.h>
43 #include <boost/foreach.hpp>
44 #include <iostream>
45
46 #include "i18n.h"
47
48 #define LOG_GENERAL(...) film->log()->log (String::compose (__VA_ARGS__), LogEntry::TYPE_GENERAL);
49
50 using std::string;
51 using std::vector;
52 using std::list;
53 using std::cout;
54 using std::pair;
55 using std::make_pair;
56 using boost::shared_ptr;
57 using boost::dynamic_pointer_cast;
58 using boost::optional;
59
60 int const FFmpegContentProperty::SUBTITLE_STREAMS = 100;
61 int const FFmpegContentProperty::SUBTITLE_STREAM = 101;
62 int const FFmpegContentProperty::FILTERS = 102;
63
64 FFmpegContent::FFmpegContent (shared_ptr<const Film> film, boost::filesystem::path p)
65         : Content (film, p)
66 {
67         video.reset (new VideoContent (this, film));
68         audio.reset (new AudioContent (this, film));
69         subtitle.reset (new SubtitleContent (this, film));
70
71         set_default_colour_conversion ();
72 }
73
74 FFmpegContent::FFmpegContent (shared_ptr<const Film> film, cxml::ConstNodePtr node, int version, list<string>& notes)
75         : Content (film, node)
76 {
77         video = VideoContent::from_xml (this, film, node, version);
78         audio = AudioContent::from_xml (this, film, node);
79         subtitle = SubtitleContent::from_xml (this, film, node, version);
80
81         list<cxml::NodePtr> c = node->node_children ("SubtitleStream");
82         for (list<cxml::NodePtr>::const_iterator i = c.begin(); i != c.end(); ++i) {
83                 _subtitle_streams.push_back (shared_ptr<FFmpegSubtitleStream> (new FFmpegSubtitleStream (*i, version)));
84                 if ((*i)->optional_number_child<int> ("Selected")) {
85                         _subtitle_stream = _subtitle_streams.back ();
86                 }
87         }
88
89         c = node->node_children ("AudioStream");
90         for (list<cxml::NodePtr>::const_iterator i = c.begin(); i != c.end(); ++i) {
91                 shared_ptr<FFmpegAudioStream> as (new FFmpegAudioStream (*i, version));
92                 audio->add_stream (as);
93                 if (version < 11 && !(*i)->optional_node_child ("Selected")) {
94                         /* This is an old file and this stream is not selected, so un-map it */
95                         as->set_mapping (AudioMapping (as->channels (), MAX_DCP_AUDIO_CHANNELS));
96                 }
97         }
98
99         c = node->node_children ("Filter");
100         for (list<cxml::NodePtr>::iterator i = c.begin(); i != c.end(); ++i) {
101                 Filter const * f = Filter::from_id ((*i)->content ());
102                 if (f) {
103                         _filters.push_back (f);
104                 } else {
105                         notes.push_back (String::compose (_("DCP-o-matic no longer supports the `%1' filter, so it has been turned off."), (*i)->content()));
106                 }
107         }
108
109         optional<ContentTime::Type> const f = node->optional_number_child<ContentTime::Type> ("FirstVideo");
110         if (f) {
111                 _first_video = ContentTime (f.get ());
112         }
113
114         _color_range = static_cast<AVColorRange> (node->optional_number_child<int>("ColorRange").get_value_or (AVCOL_RANGE_UNSPECIFIED));
115         _color_primaries = static_cast<AVColorPrimaries> (node->optional_number_child<int>("ColorPrimaries").get_value_or (AVCOL_PRI_UNSPECIFIED));
116         _color_trc = static_cast<AVColorTransferCharacteristic> (
117                 node->optional_number_child<int>("ColorTransferCharacteristic").get_value_or (AVCOL_TRC_UNSPECIFIED)
118                 );
119         _colorspace = static_cast<AVColorSpace> (node->optional_number_child<int>("Colorspace").get_value_or (AVCOL_SPC_UNSPECIFIED));
120         _bits_per_pixel = node->optional_number_child<int> ("BitsPerPixel");
121
122 }
123
124 FFmpegContent::FFmpegContent (shared_ptr<const Film> film, vector<boost::shared_ptr<Content> > c)
125         : Content (film, c)
126 {
127         video.reset (new VideoContent (this, film, c));
128         audio.reset (new AudioContent (this, film, c));
129         subtitle.reset (new SubtitleContent (this, film, c));
130
131         shared_ptr<FFmpegContent> ref = dynamic_pointer_cast<FFmpegContent> (c[0]);
132         DCPOMATIC_ASSERT (ref);
133
134         for (size_t i = 0; i < c.size(); ++i) {
135                 shared_ptr<FFmpegContent> fc = dynamic_pointer_cast<FFmpegContent> (c[i]);
136                 if (fc->subtitle->use() && *(fc->_subtitle_stream.get()) != *(ref->_subtitle_stream.get())) {
137                         throw JoinError (_("Content to be joined must use the same subtitle stream."));
138                 }
139         }
140
141         /* XXX: should probably check that more of the stuff below is the same in *this and ref */
142
143         _subtitle_streams = ref->subtitle_streams ();
144         _subtitle_stream = ref->subtitle_stream ();
145         _first_video = ref->_first_video;
146         _filters = ref->_filters;
147         _color_range = ref->_color_range;
148         _color_primaries = ref->_color_primaries;
149         _color_trc = ref->_color_trc;
150         _colorspace = ref->_colorspace;
151         _bits_per_pixel = ref->_bits_per_pixel;
152 }
153
154 void
155 FFmpegContent::as_xml (xmlpp::Node* node) const
156 {
157         node->add_child("Type")->add_child_text ("FFmpeg");
158         Content::as_xml (node);
159
160         if (video) {
161                 video->as_xml (node);
162         }
163
164         if (audio) {
165                 audio->as_xml (node);
166         }
167
168         if (subtitle) {
169                 subtitle->as_xml (node);
170         }
171
172         boost::mutex::scoped_lock lm (_mutex);
173
174         for (vector<shared_ptr<FFmpegSubtitleStream> >::const_iterator i = _subtitle_streams.begin(); i != _subtitle_streams.end(); ++i) {
175                 xmlpp::Node* t = node->add_child("SubtitleStream");
176                 if (_subtitle_stream && *i == _subtitle_stream) {
177                         t->add_child("Selected")->add_child_text("1");
178                 }
179                 (*i)->as_xml (t);
180         }
181
182         BOOST_FOREACH (AudioStreamPtr i, audio->streams ()) {
183                 shared_ptr<FFmpegAudioStream> f = dynamic_pointer_cast<FFmpegAudioStream> (i);
184                 DCPOMATIC_ASSERT (f);
185                 f->as_xml (node->add_child("AudioStream"));
186         }
187
188         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
189                 node->add_child("Filter")->add_child_text ((*i)->id ());
190         }
191
192         if (_first_video) {
193                 node->add_child("FirstVideo")->add_child_text (raw_convert<string> (_first_video.get().get()));
194         }
195
196         node->add_child("ColorRange")->add_child_text (raw_convert<string> (_color_range));
197         node->add_child("ColorPrimaries")->add_child_text (raw_convert<string> (_color_primaries));
198         node->add_child("ColorTransferCharacteristic")->add_child_text (raw_convert<string> (_color_trc));
199         node->add_child("Colorspace")->add_child_text (raw_convert<string> (_colorspace));
200         if (_bits_per_pixel) {
201                 node->add_child("BitsPerPixel")->add_child_text (raw_convert<string> (_bits_per_pixel.get ()));
202         }
203 }
204
205 void
206 FFmpegContent::examine (shared_ptr<Job> job)
207 {
208         job->set_progress_unknown ();
209
210         Content::examine (job);
211
212         shared_ptr<FFmpegExaminer> examiner (new FFmpegExaminer (shared_from_this (), job));
213         video->take_from_examiner (examiner);
214         set_default_colour_conversion ();
215
216         {
217                 boost::mutex::scoped_lock lm (_mutex);
218
219                 _subtitle_streams = examiner->subtitle_streams ();
220                 if (!_subtitle_streams.empty ()) {
221                         _subtitle_stream = _subtitle_streams.front ();
222                 }
223
224                 BOOST_FOREACH (shared_ptr<FFmpegAudioStream> i, examiner->audio_streams ()) {
225                         audio->add_stream (i);
226                 }
227
228                 if (!audio->streams().empty ()) {
229                         AudioStreamPtr as = audio->streams().front();
230                         AudioMapping m = as->mapping ();
231                         film()->make_audio_mapping_default (m);
232                         as->set_mapping (m);
233                 }
234
235                 _first_video = examiner->first_video ();
236
237                 _color_range = examiner->color_range ();
238                 _color_primaries = examiner->color_primaries ();
239                 _color_trc = examiner->color_trc ();
240                 _colorspace = examiner->colorspace ();
241                 _bits_per_pixel = examiner->bits_per_pixel ();
242         }
243
244         signal_changed (FFmpegContentProperty::SUBTITLE_STREAMS);
245         signal_changed (FFmpegContentProperty::SUBTITLE_STREAM);
246 }
247
248 string
249 FFmpegContent::summary () const
250 {
251         /* Get the string() here so that the name does not have quotes around it */
252         return String::compose (_("%1 [movie]"), path_summary ());
253 }
254
255 string
256 FFmpegContent::technical_summary () const
257 {
258         string as = "";
259         BOOST_FOREACH (shared_ptr<FFmpegAudioStream> i, ffmpeg_audio_streams ()) {
260                 as += i->technical_summary () + " " ;
261         }
262
263         if (as.empty ()) {
264                 as = "none";
265         }
266
267         string ss = "none";
268         if (_subtitle_stream) {
269                 ss = _subtitle_stream->technical_summary ();
270         }
271
272         string filt = Filter::ffmpeg_string (_filters);
273
274         return Content::technical_summary() + " - "
275                 + video->technical_summary() + " - "
276                 + audio->technical_summary() + " - "
277                 + String::compose (
278                         "ffmpeg: audio %1 subtitle %2 filters %3", as, ss, filt
279                         );
280 }
281
282 void
283 FFmpegContent::set_subtitle_stream (shared_ptr<FFmpegSubtitleStream> s)
284 {
285         {
286                 boost::mutex::scoped_lock lm (_mutex);
287                 _subtitle_stream = s;
288         }
289
290         signal_changed (FFmpegContentProperty::SUBTITLE_STREAM);
291 }
292
293 bool
294 operator== (FFmpegStream const & a, FFmpegStream const & b)
295 {
296         return a._id == b._id;
297 }
298
299 bool
300 operator!= (FFmpegStream const & a, FFmpegStream const & b)
301 {
302         return a._id != b._id;
303 }
304
305 DCPTime
306 FFmpegContent::full_length () const
307 {
308         FrameRateChange const frc (active_video_frame_rate (), film()->video_frame_rate ());
309         return DCPTime::from_frames (llrint (video->length_after_3d_combine() * frc.factor()), film()->video_frame_rate());
310 }
311
312 void
313 FFmpegContent::set_filters (vector<Filter const *> const & filters)
314 {
315         {
316                 boost::mutex::scoped_lock lm (_mutex);
317                 _filters = filters;
318         }
319
320         signal_changed (FFmpegContentProperty::FILTERS);
321 }
322
323 string
324 FFmpegContent::identifier () const
325 {
326         SafeStringStream s;
327
328         s << Content::identifier() << "_"
329           << video->identifier() << "_"
330           << subtitle->identifier();
331
332         boost::mutex::scoped_lock lm (_mutex);
333
334         if (_subtitle_stream) {
335                 s << "_" << _subtitle_stream->identifier ();
336         }
337
338         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
339                 s << "_" << (*i)->id ();
340         }
341
342         return s.str ();
343 }
344
345 list<ContentTimePeriod>
346 FFmpegContent::image_subtitles_during (ContentTimePeriod period, bool starting) const
347 {
348         shared_ptr<FFmpegSubtitleStream> stream = subtitle_stream ();
349         if (!stream) {
350                 return list<ContentTimePeriod> ();
351         }
352
353         return stream->image_subtitles_during (period, starting);
354 }
355
356 list<ContentTimePeriod>
357 FFmpegContent::text_subtitles_during (ContentTimePeriod period, bool starting) const
358 {
359         shared_ptr<FFmpegSubtitleStream> stream = subtitle_stream ();
360         if (!stream) {
361                 return list<ContentTimePeriod> ();
362         }
363
364         return stream->text_subtitles_during (period, starting);
365 }
366
367 void
368 FFmpegContent::set_default_colour_conversion ()
369 {
370         dcp::Size const s = video->size ();
371
372         boost::mutex::scoped_lock lm (_mutex);
373
374         if (s.width < 1080) {
375                 video->set_colour_conversion (PresetColourConversion::from_id ("rec601").conversion);
376         } else {
377                 video->set_colour_conversion (PresetColourConversion::from_id ("rec709").conversion);
378         }
379 }
380
381 void
382 FFmpegContent::add_properties (list<UserProperty>& p) const
383 {
384         Content::add_properties (p);
385         video->add_properties (p);
386         audio->add_properties (p);
387
388         if (_bits_per_pixel) {
389                 int const sub = 219 * pow (2, _bits_per_pixel.get() - 8);
390                 int const total = pow (2, _bits_per_pixel.get());
391
392                 switch (_color_range) {
393                 case AVCOL_RANGE_UNSPECIFIED:
394                         /// TRANSLATORS: this means that the range of pixel values used in this
395                         /// file is unknown (not specified in the file).
396                         p.push_back (UserProperty (_("Video"), _("Colour range"), _("Unspecified")));
397                         break;
398                 case AVCOL_RANGE_MPEG:
399                         /// TRANSLATORS: this means that the range of pixel values used in this
400                         /// file is limited, so that not all possible values are valid.
401                         p.push_back (
402                                 UserProperty (
403                                         _("Video"), _("Colour range"), String::compose (_("Limited (%1-%2)"), (total - sub) / 2, (total + sub) / 2)
404                                         )
405                                 );
406                         break;
407                 case AVCOL_RANGE_JPEG:
408                         /// TRANSLATORS: this means that the range of pixel values used in this
409                         /// file is full, so that all possible pixel values are valid.
410                         p.push_back (UserProperty (_("Video"), _("Colour range"), String::compose (_("Full (0-%1)"), total)));
411                         break;
412                 default:
413                         DCPOMATIC_ASSERT (false);
414                 }
415         } else {
416                 switch (_color_range) {
417                 case AVCOL_RANGE_UNSPECIFIED:
418                         /// TRANSLATORS: this means that the range of pixel values used in this
419                         /// file is unknown (not specified in the file).
420                         p.push_back (UserProperty (_("Video"), _("Colour range"), _("Unspecified")));
421                         break;
422                 case AVCOL_RANGE_MPEG:
423                         /// TRANSLATORS: this means that the range of pixel values used in this
424                         /// file is limited, so that not all possible values are valid.
425                         p.push_back (UserProperty (_("Video"), _("Colour range"), _("Limited")));
426                         break;
427                 case AVCOL_RANGE_JPEG:
428                         /// TRANSLATORS: this means that the range of pixel values used in this
429                         /// file is full, so that all possible pixel values are valid.
430                         p.push_back (UserProperty (_("Video"), _("Colour range"), _("Full")));
431                         break;
432                 default:
433                         DCPOMATIC_ASSERT (false);
434                 }
435         }
436
437         char const * primaries[] = {
438                 _("Unspecified"),
439                 _("BT709"),
440                 _("Unspecified"),
441                 _("Unspecified"),
442                 _("BT470M"),
443                 _("BT470BG"),
444                 _("SMPTE 170M (BT601)"),
445                 _("SMPTE 240M"),
446                 _("Film"),
447                 _("BT2020"),
448                 _("SMPTE ST 428-1 (CIE 1931 XYZ)")
449         };
450
451         DCPOMATIC_ASSERT (AVCOL_PRI_NB == 11);
452         p.push_back (UserProperty (_("Video"), _("Colour primaries"), primaries[_color_primaries]));
453
454         char const * transfers[] = {
455                 _("Unspecified"),
456                 _("BT709"),
457                 _("Unspecified"),
458                 _("Unspecified"),
459                 _("Gamma 22 (BT470M)"),
460                 _("Gamma 28 (BT470BG)"),
461                 _("SMPTE 170M (BT601)"),
462                 _("SMPTE 240M"),
463                 _("Linear"),
464                 _("Logarithmic (100:1 range)"),
465                 _("Logarithmic (316:1 range)"),
466                 _("IEC61966-2-4"),
467                 _("BT1361 extended colour gamut"),
468                 _("IEC61966-2-1 (sRGB or sYCC)"),
469                 _("BT2020 for a 10-bit system"),
470                 _("BT2020 for a 12-bit system"),
471                 _("SMPTE ST 2084 for 10, 12, 14 and 16 bit systems"),
472                 _("SMPTE ST 428-1")
473         };
474
475         DCPOMATIC_ASSERT (AVCOL_TRC_NB == 18);
476         p.push_back (UserProperty (_("Video"), _("Colour transfer characteristic"), transfers[_color_trc]));
477
478         char const * spaces[] = {
479                 _("RGB / sRGB (IEC61966-2-1)"),
480                 _("BT709"),
481                 _("Unspecified"),
482                 _("Unspecified"),
483                 _("FCC"),
484                 _("BT470BG (BT601-6)"),
485                 _("SMPTE 170M (BT601-6)"),
486                 _("SMPTE 240M"),
487                 _("YCOCG"),
488                 _("BT2020 non-constant luminance"),
489                 _("BT2020 constant luminance"),
490         };
491
492         DCPOMATIC_ASSERT (AVCOL_SPC_NB == 11);
493         p.push_back (UserProperty (_("Video"), _("Colourspace"), spaces[_colorspace]));
494
495         if (_bits_per_pixel) {
496                 p.push_back (UserProperty (_("Video"), _("Bits per pixel"), raw_convert<string> (_bits_per_pixel.get ())));
497         }
498 }
499
500 /** Our subtitle streams have colour maps, which can be changed, but
501  *  they have no way of signalling that change.  As a hack, we have this
502  *  method which callers can use when they've modified one of our subtitle
503  *  streams.
504  */
505 void
506 FFmpegContent::signal_subtitle_stream_changed ()
507 {
508         signal_changed (FFmpegContentProperty::SUBTITLE_STREAM);
509 }
510
511 vector<shared_ptr<FFmpegAudioStream> >
512 FFmpegContent::ffmpeg_audio_streams () const
513 {
514         vector<shared_ptr<FFmpegAudioStream> > fa;
515         BOOST_FOREACH (AudioStreamPtr i, audio->streams()) {
516                 fa.push_back (dynamic_pointer_cast<FFmpegAudioStream> (i));
517         }
518         return fa;
519 }