Merge branch 'prefs' of ssh://carlh.dyndns.org/home/carl/git/dcpomatic into prefs
[dcpomatic.git] / src / lib / ffmpeg_content.cc
1 /*
2     Copyright (C) 2013-2014 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 extern "C" {
21 #include <libavformat/avformat.h>
22 }
23 #include <libcxml/cxml.h>
24 #include "ffmpeg_content.h"
25 #include "ffmpeg_examiner.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
34 #include "i18n.h"
35
36 using std::string;
37 using std::stringstream;
38 using std::vector;
39 using std::list;
40 using std::cout;
41 using std::pair;
42 using boost::shared_ptr;
43 using boost::lexical_cast;
44 using boost::dynamic_pointer_cast;
45
46 int const FFmpegContentProperty::SUBTITLE_STREAMS = 100;
47 int const FFmpegContentProperty::SUBTITLE_STREAM = 101;
48 int const FFmpegContentProperty::AUDIO_STREAMS = 102;
49 int const FFmpegContentProperty::AUDIO_STREAM = 103;
50 int const FFmpegContentProperty::FILTERS = 104;
51
52 FFmpegContent::FFmpegContent (shared_ptr<const Film> f, boost::filesystem::path p)
53         : Content (f, p)
54         , VideoContent (f, p)
55         , AudioContent (f, p)
56         , SubtitleContent (f, p)
57 {
58
59 }
60
61 FFmpegContent::FFmpegContent (shared_ptr<const Film> f, shared_ptr<const cxml::Node> node, int version, list<string>& notes)
62         : Content (f, node)
63         , VideoContent (f, node, version)
64         , AudioContent (f, node)
65         , SubtitleContent (f, node, version)
66 {
67         list<cxml::NodePtr> c = node->node_children ("SubtitleStream");
68         for (list<cxml::NodePtr>::const_iterator i = c.begin(); i != c.end(); ++i) {
69                 _subtitle_streams.push_back (shared_ptr<FFmpegSubtitleStream> (new FFmpegSubtitleStream (*i)));
70                 if ((*i)->optional_number_child<int> ("Selected")) {
71                         _subtitle_stream = _subtitle_streams.back ();
72                 }
73         }
74
75         c = node->node_children ("AudioStream");
76         for (list<cxml::NodePtr>::const_iterator i = c.begin(); i != c.end(); ++i) {
77                 _audio_streams.push_back (shared_ptr<FFmpegAudioStream> (new FFmpegAudioStream (*i, version)));
78                 if ((*i)->optional_number_child<int> ("Selected")) {
79                         _audio_stream = _audio_streams.back ();
80                 }
81         }
82
83         c = node->node_children ("Filter");
84         for (list<cxml::NodePtr>::iterator i = c.begin(); i != c.end(); ++i) {
85                 Filter const * f = Filter::from_id ((*i)->content ());
86                 if (f) {
87                         _filters.push_back (f);
88                 } else {
89                         notes.push_back (String::compose (_("DCP-o-matic no longer supports the `%1' filter, so it has been turned off."), (*i)->content()));
90                 }
91         }
92
93         _first_video = node->optional_number_child<double> ("FirstVideo");
94 }
95
96 FFmpegContent::FFmpegContent (shared_ptr<const Film> f, vector<boost::shared_ptr<Content> > c)
97         : Content (f, c)
98         , VideoContent (f, c)
99         , AudioContent (f, c)
100         , SubtitleContent (f, c)
101 {
102         shared_ptr<FFmpegContent> ref = dynamic_pointer_cast<FFmpegContent> (c[0]);
103         assert (ref);
104
105         for (size_t i = 0; i < c.size(); ++i) {
106                 shared_ptr<FFmpegContent> fc = dynamic_pointer_cast<FFmpegContent> (c[i]);
107                 if (f->with_subtitles() && *(fc->_subtitle_stream.get()) != *(ref->_subtitle_stream.get())) {
108                         throw JoinError (_("Content to be joined must use the same subtitle stream."));
109                 }
110
111                 if (*(fc->_audio_stream.get()) != *(ref->_audio_stream.get())) {
112                         throw JoinError (_("Content to be joined must use the same audio stream."));
113                 }
114         }
115
116         _subtitle_streams = ref->subtitle_streams ();
117         _subtitle_stream = ref->subtitle_stream ();
118         _audio_streams = ref->audio_streams ();
119         _audio_stream = ref->audio_stream ();
120         _first_video = ref->_first_video;
121 }
122
123 void
124 FFmpegContent::as_xml (xmlpp::Node* node) const
125 {
126         node->add_child("Type")->add_child_text ("FFmpeg");
127         Content::as_xml (node);
128         VideoContent::as_xml (node);
129         AudioContent::as_xml (node);
130         SubtitleContent::as_xml (node);
131
132         boost::mutex::scoped_lock lm (_mutex);
133
134         for (vector<shared_ptr<FFmpegSubtitleStream> >::const_iterator i = _subtitle_streams.begin(); i != _subtitle_streams.end(); ++i) {
135                 xmlpp::Node* t = node->add_child("SubtitleStream");
136                 if (_subtitle_stream && *i == _subtitle_stream) {
137                         t->add_child("Selected")->add_child_text("1");
138                 }
139                 (*i)->as_xml (t);
140         }
141
142         for (vector<shared_ptr<FFmpegAudioStream> >::const_iterator i = _audio_streams.begin(); i != _audio_streams.end(); ++i) {
143                 xmlpp::Node* t = node->add_child("AudioStream");
144                 if (_audio_stream && *i == _audio_stream) {
145                         t->add_child("Selected")->add_child_text("1");
146                 }
147                 (*i)->as_xml (t);
148         }
149
150         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
151                 node->add_child("Filter")->add_child_text ((*i)->id ());
152         }
153
154         if (_first_video) {
155                 node->add_child("FirstVideo")->add_child_text (lexical_cast<string> (_first_video.get ()));
156         }
157 }
158
159 void
160 FFmpegContent::examine (shared_ptr<Job> job)
161 {
162         job->set_progress_unknown ();
163
164         Content::examine (job);
165
166         shared_ptr<const Film> film = _film.lock ();
167         assert (film);
168
169         shared_ptr<FFmpegExaminer> examiner (new FFmpegExaminer (shared_from_this ()));
170
171         VideoContent::Frame video_length = 0;
172         video_length = examiner->video_length ();
173         film->log()->log (String::compose ("Video length obtained from header as %1 frames", video_length));
174
175         {
176                 boost::mutex::scoped_lock lm (_mutex);
177
178                 _video_length = video_length;
179
180                 _subtitle_streams = examiner->subtitle_streams ();
181                 if (!_subtitle_streams.empty ()) {
182                         _subtitle_stream = _subtitle_streams.front ();
183                 }
184                 
185                 _audio_streams = examiner->audio_streams ();
186                 if (!_audio_streams.empty ()) {
187                         _audio_stream = _audio_streams.front ();
188                 }
189
190                 _first_video = examiner->first_video ();
191         }
192
193         take_from_video_examiner (examiner);
194
195         signal_changed (ContentProperty::LENGTH);
196         signal_changed (FFmpegContentProperty::SUBTITLE_STREAMS);
197         signal_changed (FFmpegContentProperty::SUBTITLE_STREAM);
198         signal_changed (FFmpegContentProperty::AUDIO_STREAMS);
199         signal_changed (FFmpegContentProperty::AUDIO_STREAM);
200         signal_changed (AudioContentProperty::AUDIO_CHANNELS);
201 }
202
203 string
204 FFmpegContent::summary () const
205 {
206         /* Get the string() here so that the name does not have quotes around it */
207         return String::compose (_("%1 [movie]"), path_summary ());
208 }
209
210 string
211 FFmpegContent::technical_summary () const
212 {
213         string as = "none";
214         if (_audio_stream) {
215                 as = _audio_stream->technical_summary ();
216         }
217
218         string ss = "none";
219         if (_subtitle_stream) {
220                 ss = _subtitle_stream->technical_summary ();
221         }
222
223         string filt = Filter::ffmpeg_string (_filters);
224         
225         return Content::technical_summary() + " - "
226                 + VideoContent::technical_summary() + " - "
227                 + AudioContent::technical_summary() + " - "
228                 + String::compose (
229                         "ffmpeg: audio %1, subtitle %2, filters %3", as, ss, filt
230                         );
231 }
232
233 string
234 FFmpegContent::information () const
235 {
236         if (video_length() == 0 || video_frame_rate() == 0) {
237                 return "";
238         }
239         
240         stringstream s;
241         
242         s << String::compose (_("%1 frames; %2 frames per second"), video_length(), video_frame_rate()) << "\n";
243         s << VideoContent::information ();
244
245         return s.str ();
246 }
247
248 void
249 FFmpegContent::set_subtitle_stream (shared_ptr<FFmpegSubtitleStream> s)
250 {
251         {
252                 boost::mutex::scoped_lock lm (_mutex);
253                 _subtitle_stream = s;
254         }
255
256         signal_changed (FFmpegContentProperty::SUBTITLE_STREAM);
257 }
258
259 void
260 FFmpegContent::set_audio_stream (shared_ptr<FFmpegAudioStream> s)
261 {
262         {
263                 boost::mutex::scoped_lock lm (_mutex);
264                 _audio_stream = s;
265         }
266
267         signal_changed (FFmpegContentProperty::AUDIO_STREAM);
268 }
269
270 AudioContent::Frame
271 FFmpegContent::audio_length () const
272 {
273         int const cafr = content_audio_frame_rate ();
274         int const vfr  = video_frame_rate ();
275         VideoContent::Frame const vl = video_length ();
276
277         boost::mutex::scoped_lock lm (_mutex);
278         if (!_audio_stream) {
279                 return 0;
280         }
281         
282         return video_frames_to_audio_frames (vl, cafr, vfr);
283 }
284
285 int
286 FFmpegContent::audio_channels () const
287 {
288         boost::mutex::scoped_lock lm (_mutex);
289         
290         if (!_audio_stream) {
291                 return 0;
292         }
293
294         return _audio_stream->channels;
295 }
296
297 int
298 FFmpegContent::content_audio_frame_rate () const
299 {
300         boost::mutex::scoped_lock lm (_mutex);
301
302         if (!_audio_stream) {
303                 return 0;
304         }
305
306         return _audio_stream->frame_rate;
307 }
308
309 int
310 FFmpegContent::output_audio_frame_rate () const
311 {
312         shared_ptr<const Film> film = _film.lock ();
313         assert (film);
314         
315         /* Resample to a DCI-approved sample rate */
316         double t = dcp_audio_frame_rate (content_audio_frame_rate ());
317
318         FrameRateConversion frc (video_frame_rate(), film->video_frame_rate());
319
320         /* Compensate if the DCP is being run at a different frame rate
321            to the source; that is, if the video is run such that it will
322            look different in the DCP compared to the source (slower or faster).
323            skip/repeat doesn't come into effect here.
324         */
325
326         if (frc.change_speed) {
327                 t *= video_frame_rate() * frc.factor() / film->video_frame_rate();
328         }
329
330         return rint (t);
331 }
332
333 bool
334 operator== (FFmpegStream const & a, FFmpegStream const & b)
335 {
336         return a._id == b._id;
337 }
338
339 bool
340 operator!= (FFmpegStream const & a, FFmpegStream const & b)
341 {
342         return a._id != b._id;
343 }
344
345 FFmpegStream::FFmpegStream (shared_ptr<const cxml::Node> node)
346         : name (node->string_child ("Name"))
347         , _id (node->number_child<int> ("Id"))
348 {
349
350 }
351
352 void
353 FFmpegStream::as_xml (xmlpp::Node* root) const
354 {
355         root->add_child("Name")->add_child_text (name);
356         root->add_child("Id")->add_child_text (lexical_cast<string> (_id));
357 }
358
359 FFmpegAudioStream::FFmpegAudioStream (shared_ptr<const cxml::Node> node, int version)
360         : FFmpegStream (node)
361         , mapping (node->node_child ("Mapping"), version)
362 {
363         frame_rate = node->number_child<int> ("FrameRate");
364         channels = node->number_child<int64_t> ("Channels");
365         first_audio = node->optional_number_child<double> ("FirstAudio");
366 }
367
368 void
369 FFmpegAudioStream::as_xml (xmlpp::Node* root) const
370 {
371         FFmpegStream::as_xml (root);
372         root->add_child("FrameRate")->add_child_text (lexical_cast<string> (frame_rate));
373         root->add_child("Channels")->add_child_text (lexical_cast<string> (channels));
374         if (first_audio) {
375                 root->add_child("FirstAudio")->add_child_text (lexical_cast<string> (first_audio.get ()));
376         }
377         mapping.as_xml (root->add_child("Mapping"));
378 }
379
380 bool
381 FFmpegStream::uses_index (AVFormatContext const * fc, int index) const
382 {
383         size_t i = 0;
384         while (i < fc->nb_streams) {
385                 if (fc->streams[i]->id == _id) {
386                         return int (i) == index;
387                 }
388                 ++i;
389         }
390
391         return false;
392 }
393
394 AVStream *
395 FFmpegStream::stream (AVFormatContext const * fc) const
396 {
397         size_t i = 0;
398         while (i < fc->nb_streams) {
399                 if (fc->streams[i]->id == _id) {
400                         return fc->streams[i];
401                 }
402                 ++i;
403         }
404
405         assert (false);
406         return 0;
407 }
408
409 /** Construct a SubtitleStream from a value returned from to_string().
410  *  @param t String returned from to_string().
411  *  @param v State file version.
412  */
413 FFmpegSubtitleStream::FFmpegSubtitleStream (shared_ptr<const cxml::Node> node)
414         : FFmpegStream (node)
415 {
416         
417 }
418
419 void
420 FFmpegSubtitleStream::as_xml (xmlpp::Node* root) const
421 {
422         FFmpegStream::as_xml (root);
423 }
424
425 Time
426 FFmpegContent::full_length () const
427 {
428         shared_ptr<const Film> film = _film.lock ();
429         assert (film);
430         
431         FrameRateConversion frc (video_frame_rate (), film->video_frame_rate ());
432         return video_length() * frc.factor() * TIME_HZ / film->video_frame_rate ();
433 }
434
435 AudioMapping
436 FFmpegContent::audio_mapping () const
437 {
438         boost::mutex::scoped_lock lm (_mutex);
439
440         if (!_audio_stream) {
441                 return AudioMapping ();
442         }
443
444         return _audio_stream->mapping;
445 }
446
447 void
448 FFmpegContent::set_filters (vector<Filter const *> const & filters)
449 {
450         {
451                 boost::mutex::scoped_lock lm (_mutex);
452                 _filters = filters;
453         }
454
455         signal_changed (FFmpegContentProperty::FILTERS);
456 }
457
458 void
459 FFmpegContent::set_audio_mapping (AudioMapping m)
460 {
461         audio_stream()->mapping = m;
462         signal_changed (AudioContentProperty::AUDIO_MAPPING);
463 }
464
465 string
466 FFmpegContent::identifier () const
467 {
468         stringstream s;
469
470         s << VideoContent::identifier();
471
472         boost::mutex::scoped_lock lm (_mutex);
473
474         if (_subtitle_stream) {
475                 s << "_" << _subtitle_stream->identifier ();
476         }
477
478         for (vector<Filter const *>::const_iterator i = _filters.begin(); i != _filters.end(); ++i) {
479                 s << "_" << (*i)->id ();
480         }
481
482         return s.str ();
483 }
484
485 boost::filesystem::path
486 FFmpegContent::audio_analysis_path () const
487 {
488         shared_ptr<const Film> film = _film.lock ();
489         if (!film) {
490                 return boost::filesystem::path ();
491         }
492
493         /* We need to include the stream ID in this path so that we get different
494            analyses for each stream.
495         */
496
497         boost::filesystem::path p = film->audio_analysis_dir ();
498         string name = digest ();
499         if (audio_stream ()) {
500                 name += "_" + audio_stream()->identifier ();
501         }
502         p /= name;
503         return p;
504 }