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