786f97dd706ddec92394dd391df6834812ba7ecd
[dcpomatic.git] / src / lib / ffmpeg_encoder.cc
1 /*
2     Copyright (C) 2017-2018 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_encoder.h"
22 #include "film.h"
23 #include "job.h"
24 #include "player.h"
25 #include "player_video.h"
26 #include "log.h"
27 #include "image.h"
28 #include "cross.h"
29 #include "butler.h"
30 #include "compose.hpp"
31 #include <iostream>
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::runtime_error;
37 using std::cout;
38 using std::pair;
39 using std::list;
40 using std::map;
41 using boost::shared_ptr;
42 using boost::bind;
43 using boost::weak_ptr;
44 using boost::optional;
45 using namespace dcpomatic;
46
47 /** @param key Key to use to encrypt MP4 outputs */
48 FFmpegEncoder::FFmpegEncoder (
49         shared_ptr<const Film> film,
50         weak_ptr<Job> job,
51         boost::filesystem::path output,
52         ExportFormat format,
53         bool mixdown_to_stereo,
54         bool split_reels,
55         bool audio_stream_per_channel,
56         int x264_crf
57 #ifdef DCPOMATIC_VARIANT_SWAROOP
58         , optional<dcp::Key> key
59         , optional<string> id
60 #endif
61         )
62         : Encoder (film, job)
63         , _history (200)
64         , _output (output)
65         , _format (format)
66         , _split_reels (split_reels)
67         , _audio_stream_per_channel (audio_stream_per_channel)
68         , _x264_crf (x264_crf)
69 {
70         _player->set_always_burn_open_subtitles ();
71         _player->set_play_referenced ();
72
73         int const ch = film->audio_channels ();
74
75         AudioMapping map;
76         if (mixdown_to_stereo) {
77                 _output_audio_channels = 2;
78                 map = AudioMapping (ch, 2);
79                 float const overall_gain = 2 / (4 + sqrt(2));
80                 float const minus_3dB = 1 / sqrt(2);
81                 if (ch == 2) {
82                         map.set (dcp::LEFT, 0, 1);
83                         map.set (dcp::RIGHT, 1, 1);
84                 } else if (ch == 4) {
85                         map.set (dcp::LEFT,   0, overall_gain);
86                         map.set (dcp::RIGHT,  1, overall_gain);
87                         map.set (dcp::CENTRE, 0, overall_gain * minus_3dB);
88                         map.set (dcp::CENTRE, 1, overall_gain * minus_3dB);
89                         map.set (dcp::LS,     0, overall_gain);
90                 } else if (ch >= 6) {
91                         map.set (dcp::LEFT,   0, overall_gain);
92                         map.set (dcp::RIGHT,  1, overall_gain);
93                         map.set (dcp::CENTRE, 0, overall_gain * minus_3dB);
94                         map.set (dcp::CENTRE, 1, overall_gain * minus_3dB);
95                         map.set (dcp::LS,     0, overall_gain);
96                         map.set (dcp::RS,     1, overall_gain);
97                 }
98                 /* XXX: maybe we should do something better for >6 channel DCPs */
99         } else {
100                 /* Our encoders don't really want to encode any channel count between 9 and 15 inclusive,
101                  * so let's just use 16 channel exports for any project with more than 8 channels.
102                  */
103                 _output_audio_channels = ch > 8 ? 16 : ch;
104                 map = AudioMapping (ch, _output_audio_channels);
105                 for (int i = 0; i < ch; ++i) {
106                         map.set (i, i, 1);
107                 }
108         }
109
110         _butler.reset (new Butler(_player, map, _output_audio_channels, bind(&PlayerVideo::force, _1, FFmpegFileEncoder::pixel_format(format)), true, false));
111 }
112
113
114 void
115 FFmpegEncoder::go ()
116 {
117         {
118                 shared_ptr<Job> job = _job.lock ();
119                 DCPOMATIC_ASSERT (job);
120                 job->sub (_("Encoding"));
121         }
122
123         Waker waker;
124
125         list<FileEncoderSet> file_encoders;
126
127         int const files = _split_reels ? _film->reels().size() : 1;
128         for (int i = 0; i < files; ++i) {
129
130                 boost::filesystem::path filename = _output;
131                 string extension = boost::filesystem::extension (filename);
132                 filename = boost::filesystem::change_extension (filename, "");
133
134                 if (files > 1) {
135                         /// TRANSLATORS: _reel%1 here is to be added to an export filename to indicate
136                         /// which reel it is.  Preserve the %1; it will be replaced with the reel number.
137                         filename = filename.string() + String::compose(_("_reel%1"), i + 1);
138                 }
139
140                 file_encoders.push_back (
141                         FileEncoderSet (
142                                 _film->frame_size(),
143                                 _film->video_frame_rate(),
144                                 _film->audio_frame_rate(),
145                                 _output_audio_channels,
146                                 _format,
147                                 _audio_stream_per_channel,
148                                 _x264_crf,
149                                 _film->three_d(),
150                                 filename,
151                                 extension
152 #ifdef DCPOMATIC_VARIANT_SWAROOP
153                                 , key
154                                 , id
155 #endif
156                                 )
157                         );
158         }
159
160         list<DCPTimePeriod> reel_periods = _film->reels ();
161         list<DCPTimePeriod>::const_iterator reel = reel_periods.begin ();
162         list<FileEncoderSet>::iterator encoder = file_encoders.begin ();
163
164         DCPTime const video_frame = DCPTime::from_frames (1, _film->video_frame_rate ());
165         int const audio_frames = video_frame.frames_round(_film->audio_frame_rate());
166         float* interleaved = new float[_output_audio_channels * audio_frames];
167         shared_ptr<AudioBuffers> deinterleaved (new AudioBuffers (_output_audio_channels, audio_frames));
168         int const gets_per_frame = _film->three_d() ? 2 : 1;
169         for (DCPTime i; i < _film->length(); i += video_frame) {
170
171                 if (file_encoders.size() > 1 && !reel->contains(i)) {
172                         /* Next reel and file */
173                         ++reel;
174                         ++encoder;
175                         DCPOMATIC_ASSERT (reel != reel_periods.end());
176                         DCPOMATIC_ASSERT (encoder != file_encoders.end());
177                 }
178
179                 for (int j = 0; j < gets_per_frame; ++j) {
180                         Butler::Error e;
181                         pair<shared_ptr<PlayerVideo>, DCPTime> v = _butler->get_video (true, &e);
182                         _butler->rethrow ();
183                         if (!v.first) {
184                                 throw DecodeError(String::compose("Error during decoding: %1", e.summary()));
185                         }
186                         shared_ptr<FFmpegFileEncoder> fe = encoder->get (v.first->eyes());
187                         if (fe) {
188                                 fe->video(v.first, v.second);
189                         }
190                 }
191
192                 _history.event ();
193
194                 {
195                         boost::mutex::scoped_lock lm (_mutex);
196                         _last_time = i;
197                 }
198
199                 shared_ptr<Job> job = _job.lock ();
200                 if (job) {
201                         job->set_progress (float(i.get()) / _film->length().get());
202                 }
203
204                 waker.nudge ();
205
206                 _butler->get_audio (interleaved, audio_frames);
207                 /* XXX: inefficient; butler interleaves and we deinterleave again */
208                 float* p = interleaved;
209                 for (int j = 0; j < audio_frames; ++j) {
210                         for (int k = 0; k < _output_audio_channels; ++k) {
211                                 deinterleaved->data(k)[j] = *p++;
212                         }
213                 }
214                 encoder->audio (deinterleaved);
215         }
216         delete[] interleaved;
217
218         BOOST_FOREACH (FileEncoderSet i, file_encoders) {
219                 i.flush ();
220         }
221 }
222
223 optional<float>
224 FFmpegEncoder::current_rate () const
225 {
226         return _history.rate ();
227 }
228
229 Frame
230 FFmpegEncoder::frames_done () const
231 {
232         boost::mutex::scoped_lock lm (_mutex);
233         return _last_time.frames_round (_film->video_frame_rate ());
234 }
235
236 FFmpegEncoder::FileEncoderSet::FileEncoderSet (
237         dcp::Size video_frame_size,
238         int video_frame_rate,
239         int audio_frame_rate,
240         int channels,
241         ExportFormat format,
242         bool audio_stream_per_channel,
243         int x264_crf,
244         bool three_d,
245         boost::filesystem::path output,
246         string extension
247 #ifdef DCPOMATIC_VARIANT_SWAROOP
248         , optional<dcp::Key> key
249         , optional<string> id
250 #endif
251         )
252 {
253         if (three_d) {
254                 /// TRANSLATORS: L here is an abbreviation for "left", to indicate the left-eye part of a 3D export
255                 _encoders[EYES_LEFT] = shared_ptr<FFmpegFileEncoder>(
256                         new FFmpegFileEncoder(
257                                 video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
258                                 audio_stream_per_channel, x264_crf, String::compose("%1_%2%3", output.string(), _("L"), extension)
259 #ifdef DCPOMATIC_VARIANT_SWAROOP
260                                               , key, id
261 #endif
262                                 )
263                         );
264                 /// TRANSLATORS: R here is an abbreviation for "right", to indicate the right-eye part of a 3D export
265                 _encoders[EYES_RIGHT] = shared_ptr<FFmpegFileEncoder>(
266                         new FFmpegFileEncoder(
267                                 video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
268                                 audio_stream_per_channel, x264_crf, String::compose("%1_%2%3", output.string(), _("R"), extension)
269 #ifdef DCPOMATIC_VARIANT_SWAROOP
270                                               , key, id
271 #endif
272                                 )
273                         );
274         } else {
275                 _encoders[EYES_BOTH]  = shared_ptr<FFmpegFileEncoder>(
276                         new FFmpegFileEncoder(
277                                 video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
278                                 audio_stream_per_channel, x264_crf, String::compose("%1%2", output.string(), extension)
279 #ifdef DCPOMATIC_VARIANT_SWAROOP
280                                               , key, id
281 #endif
282                                 )
283                         );
284         }
285 }
286
287 shared_ptr<FFmpegFileEncoder>
288 FFmpegEncoder::FileEncoderSet::get (Eyes eyes) const
289 {
290         if (_encoders.size() == 1) {
291                 /* We are doing a 2D export... */
292                 if (eyes == EYES_LEFT) {
293                         /* ...but we got some 3D data; put the left eye into the output... */
294                         eyes = EYES_BOTH;
295                 } else if (eyes == EYES_RIGHT) {
296                         /* ...and ignore the right eye.*/
297                         return shared_ptr<FFmpegFileEncoder>();
298                 }
299         }
300
301         map<Eyes, boost::shared_ptr<FFmpegFileEncoder> >::const_iterator i = _encoders.find (eyes);
302         DCPOMATIC_ASSERT (i != _encoders.end());
303         return i->second;
304 }
305
306 void
307 FFmpegEncoder::FileEncoderSet::flush ()
308 {
309         for (map<Eyes, boost::shared_ptr<FFmpegFileEncoder> >::iterator i = _encoders.begin(); i != _encoders.end(); ++i) {
310                 i->second->flush ();
311         }
312 }
313
314 void
315 FFmpegEncoder::FileEncoderSet::audio (shared_ptr<AudioBuffers> a)
316 {
317         for (map<Eyes, boost::shared_ptr<FFmpegFileEncoder> >::iterator i = _encoders.begin(); i != _encoders.end(); ++i) {
318                 i->second->audio (a);
319         }
320 }