Make terminate_threads() less likely to leave _threads containing invalid pointers.
[dcpomatic.git] / src / lib / ffmpeg.cc
1 /*
2     Copyright (C) 2013-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "ffmpeg.h"
22 #include "ffmpeg_content.h"
23 #include "film.h"
24 #include "exceptions.h"
25 #include "util.h"
26 #include "log.h"
27 #include "dcpomatic_log.h"
28 #include "ffmpeg_subtitle_stream.h"
29 #include "ffmpeg_audio_stream.h"
30 #include "digester.h"
31 #include "compose.hpp"
32 #include <dcp/raw_convert.h>
33 extern "C" {
34 #include <libavcodec/avcodec.h>
35 #include <libavformat/avformat.h>
36 #include <libswscale/swscale.h>
37 }
38 #include <boost/algorithm/string.hpp>
39 #include <boost/foreach.hpp>
40 #include <iostream>
41
42 #include "i18n.h"
43
44 using std::string;
45 using std::cout;
46 using std::cerr;
47 using std::vector;
48 using boost::shared_ptr;
49 using boost::optional;
50 using dcp::raw_convert;
51
52 boost::mutex FFmpeg::_mutex;
53
54 FFmpeg::FFmpeg (boost::shared_ptr<const FFmpegContent> c)
55         : _ffmpeg_content (c)
56         , _avio_buffer (0)
57         , _avio_buffer_size (4096)
58         , _avio_context (0)
59         , _format_context (0)
60         , _frame (0)
61 {
62         setup_general ();
63         setup_decoders ();
64 }
65
66 FFmpeg::~FFmpeg ()
67 {
68         boost::mutex::scoped_lock lm (_mutex);
69
70         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
71                 avcodec_close (_format_context->streams[i]->codec);
72         }
73
74         av_frame_free (&_frame);
75         avformat_close_input (&_format_context);
76 }
77
78 static int
79 avio_read_wrapper (void* data, uint8_t* buffer, int amount)
80 {
81         return reinterpret_cast<FFmpeg*>(data)->avio_read (buffer, amount);
82 }
83
84 static int64_t
85 avio_seek_wrapper (void* data, int64_t offset, int whence)
86 {
87         return reinterpret_cast<FFmpeg*>(data)->avio_seek (offset, whence);
88 }
89
90 void
91 FFmpeg::ffmpeg_log_callback (void* ptr, int level, const char* fmt, va_list vl)
92 {
93         if (level > AV_LOG_WARNING) {
94                 return;
95         }
96
97         char line[1024];
98         static int prefix = 0;
99         av_log_format_line (ptr, level, fmt, vl, line, sizeof (line), &prefix);
100         string str (line);
101         boost::algorithm::trim (str);
102         dcpomatic_log->log (String::compose ("FFmpeg: %1", str), LogEntry::TYPE_GENERAL);
103 }
104
105 void
106 FFmpeg::setup_general ()
107 {
108         /* This might not work too well in some cases of multiple FFmpeg decoders,
109            but it's probably good enough.
110         */
111         av_log_set_callback (FFmpeg::ffmpeg_log_callback);
112
113         _file_group.set_paths (_ffmpeg_content->paths ());
114         _avio_buffer = static_cast<uint8_t*> (wrapped_av_malloc (_avio_buffer_size));
115         _avio_context = avio_alloc_context (_avio_buffer, _avio_buffer_size, 0, this, avio_read_wrapper, 0, avio_seek_wrapper);
116         _format_context = avformat_alloc_context ();
117         _format_context->pb = _avio_context;
118
119         AVDictionary* options = 0;
120         /* These durations are in microseconds, and represent how far into the content file
121            we will look for streams.
122         */
123         av_dict_set (&options, "analyzeduration", raw_convert<string> (5 * 60 * 1000000).c_str(), 0);
124         av_dict_set (&options, "probesize", raw_convert<string> (5 * 60 * 1000000).c_str(), 0);
125         if (_ffmpeg_content->decryption_key()) {
126                 av_dict_set (&options, "decryption_key", _ffmpeg_content->decryption_key()->c_str(), 0);
127         }
128
129         int e = avformat_open_input (&_format_context, 0, 0, &options);
130         if (e < 0) {
131                 throw OpenFileError (_ffmpeg_content->path(0).string(), e, OpenFileError::READ);
132         }
133
134         if (avformat_find_stream_info (_format_context, 0) < 0) {
135                 throw DecodeError (_("could not find stream information"));
136         }
137
138         /* Find video stream */
139
140         optional<int> video_stream_undefined_frame_rate;
141
142         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
143                 AVStream* s = _format_context->streams[i];
144                 if (s->codec->codec_type == AVMEDIA_TYPE_VIDEO && avcodec_find_decoder(s->codec->codec_id)) {
145                         if (s->avg_frame_rate.num > 0 && s->avg_frame_rate.den > 0) {
146                                 /* This is definitely our video stream */
147                                 _video_stream = i;
148                         } else {
149                                 /* This is our video stream if we don't get a better offer */
150                                 video_stream_undefined_frame_rate = i;
151                         }
152                 }
153         }
154
155         /* Files from iTunes sometimes have two video streams, one with the avg_frame_rate.num and .den set
156            to zero.  Only use such a stream if there is no alternative.
157         */
158         if (!_video_stream && video_stream_undefined_frame_rate) {
159                 _video_stream = video_stream_undefined_frame_rate.get();
160         }
161
162         /* Ignore video streams with crazy frame rates.  These are usually things like album art on MP3s. */
163         if (_video_stream && av_q2d(av_guess_frame_rate(_format_context, _format_context->streams[_video_stream.get()], 0)) > 1000) {
164                 _video_stream = optional<int>();
165         }
166
167         /* Hack: if the AVStreams have duplicate IDs, replace them with our
168            own.  We use the IDs so that we can cope with VOBs, in which streams
169            move about in index but remain with the same ID in different
170            VOBs.  However, some files have duplicate IDs, hence this hack.
171         */
172
173         bool duplicates = false;
174         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
175                 for (uint32_t j = i + 1; j < _format_context->nb_streams; ++j) {
176                         if (_format_context->streams[i]->id == _format_context->streams[j]->id) {
177                                 duplicates = true;
178                         }
179                 }
180         }
181
182         if (duplicates) {
183                 /* Put in our own IDs */
184                 for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
185                         _format_context->streams[i]->id = i;
186                 }
187         }
188
189         _frame = av_frame_alloc ();
190         if (_frame == 0) {
191                 throw DecodeError (N_("could not allocate frame"));
192         }
193 }
194
195 void
196 FFmpeg::setup_decoders ()
197 {
198         boost::mutex::scoped_lock lm (_mutex);
199
200         for (uint32_t i = 0; i < _format_context->nb_streams; ++i) {
201                 AVCodecContext* context = _format_context->streams[i]->codec;
202
203                 AVCodec* codec = avcodec_find_decoder (context->codec_id);
204                 if (codec) {
205
206                         AVDictionary* options = 0;
207                         /* This option disables decoding of DCA frame footers in our patched version
208                            of FFmpeg.  I believe these footers are of no use to us, and they can cause
209                            problems when FFmpeg fails to decode them (mantis #352).
210                         */
211                         av_dict_set (&options, "disable_footer", "1", 0);
212                         /* This allows decoding of some DNxHR 444 and HQX files; see
213                            https://trac.ffmpeg.org/ticket/5681
214                         */
215                         av_dict_set_int (&options, "strict", FF_COMPLIANCE_EXPERIMENTAL, 0);
216                         /* Enable following of links in files */
217                         av_dict_set_int (&options, "enable_drefs", 1, 0);
218
219                         if (avcodec_open2 (context, codec, &options) < 0) {
220                                 throw DecodeError (N_("could not open decoder"));
221                         }
222                 } else {
223                         dcpomatic_log->log (String::compose ("No codec found for stream %1", i), LogEntry::TYPE_WARNING);
224                 }
225         }
226 }
227
228 AVCodecContext *
229 FFmpeg::video_codec_context () const
230 {
231         if (!_video_stream) {
232                 return 0;
233         }
234
235         return _format_context->streams[_video_stream.get()]->codec;
236 }
237
238 AVCodecContext *
239 FFmpeg::subtitle_codec_context () const
240 {
241         if (!_ffmpeg_content->subtitle_stream ()) {
242                 return 0;
243         }
244
245         return _ffmpeg_content->subtitle_stream()->stream(_format_context)->codec;
246 }
247
248 int
249 FFmpeg::avio_read (uint8_t* buffer, int const amount)
250 {
251         return _file_group.read (buffer, amount);
252 }
253
254 int64_t
255 FFmpeg::avio_seek (int64_t const pos, int whence)
256 {
257         if (whence == AVSEEK_SIZE) {
258                 return _file_group.length ();
259         }
260
261         return _file_group.seek (pos, whence);
262 }
263
264 FFmpegSubtitlePeriod
265 FFmpeg::subtitle_period (AVSubtitle const & sub)
266 {
267         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
268
269         if (sub.end_display_time == static_cast<uint32_t> (-1)) {
270                 /* End time is not known */
271                 return FFmpegSubtitlePeriod (packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3));
272         }
273
274         return FFmpegSubtitlePeriod (
275                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
276                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
277                 );
278 }
279
280 /** Compute the pts offset to use given a set of audio streams and some video details.
281  *  Sometimes these parameters will have just been determined by an Examiner, sometimes
282  *  they will have been retrieved from a piece of Content, hence the need for this method
283  *  in FFmpeg.
284  */
285 ContentTime
286 FFmpeg::pts_offset (vector<shared_ptr<FFmpegAudioStream> > audio_streams, optional<ContentTime> first_video, double video_frame_rate) const
287 {
288         /* Audio and video frame PTS values may not start with 0.  We want
289            to fiddle them so that:
290
291            1.  One of them starts at time 0.
292            2.  The first video PTS value ends up on a frame boundary.
293
294            Then we remove big initial gaps in PTS and we allow our
295            insertion of black frames to work.
296
297            We will do:
298              audio_pts_to_use = audio_pts_from_ffmpeg + pts_offset;
299              video_pts_to_use = video_pts_from_ffmpeg + pts_offset;
300         */
301
302         /* First, make one of them start at 0 */
303
304         ContentTime po = ContentTime::min ();
305
306         if (first_video) {
307                 po = - first_video.get ();
308         }
309
310         BOOST_FOREACH (shared_ptr<FFmpegAudioStream> i, audio_streams) {
311                 if (i->first_audio) {
312                         po = max (po, - i->first_audio.get ());
313                 }
314         }
315
316         /* If the offset is positive we would be pushing things from a -ve PTS to be played.
317            I don't think we ever want to do that, as it seems things at -ve PTS are not meant
318            to be seen (use for alignment bars etc.); see mantis #418.
319         */
320         if (po > ContentTime ()) {
321                 po = ContentTime ();
322         }
323
324         /* Now adjust so that the video pts starts on a frame */
325         if (first_video) {
326                 ContentTime const fvc = first_video.get() + po;
327                 po += fvc.ceil (video_frame_rate) - fvc;
328         }
329
330         return po;
331 }