bcf2b82de898b5dd754f431b6533c4661ac3af71
[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
22 #include "butler.h"
23 #include "cross.h"
24 #include "ffmpeg_encoder.h"
25 #include "film.h"
26 #include "image.h"
27 #include "job.h"
28 #include "log.h"
29 #include "player.h"
30 #include "player_video.h"
31 #include "compose.hpp"
32 #include <iostream>
33
34 #include "i18n.h"
35
36
37 using std::cout;
38 using std::list;
39 using std::make_shared;
40 using std::shared_ptr;
41 using std::string;
42 using std::weak_ptr;
43 using boost::bind;
44 using boost::optional;
45 using namespace dcpomatic;
46 #if BOOST_VERSION >= 106100
47 using namespace boost::placeholders;
48 #endif
49
50
51 /** @param key Key to use to encrypt MP4 outputs */
52 FFmpegEncoder::FFmpegEncoder (
53         shared_ptr<const Film> film,
54         weak_ptr<Job> job,
55         boost::filesystem::path output,
56         ExportFormat format,
57         bool mixdown_to_stereo,
58         bool split_reels,
59         bool audio_stream_per_channel,
60         int x264_crf
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::Channel::LEFT, 0, 1);
83                         map.set (dcp::Channel::RIGHT, 1, 1);
84                 } else if (ch == 4) {
85                         map.set (dcp::Channel::LEFT,   0, overall_gain);
86                         map.set (dcp::Channel::RIGHT,  1, overall_gain);
87                         map.set (dcp::Channel::CENTRE, 0, overall_gain * minus_3dB);
88                         map.set (dcp::Channel::CENTRE, 1, overall_gain * minus_3dB);
89                         map.set (dcp::Channel::LS,     0, overall_gain);
90                 } else if (ch >= 6) {
91                         map.set (dcp::Channel::LEFT,   0, overall_gain);
92                         map.set (dcp::Channel::RIGHT,  1, overall_gain);
93                         map.set (dcp::Channel::CENTRE, 0, overall_gain * minus_3dB);
94                         map.set (dcp::Channel::CENTRE, 1, overall_gain * minus_3dB);
95                         map.set (dcp::Channel::LS,     0, overall_gain);
96                         map.set (dcp::Channel::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 = std::make_shared<Butler>(
111                 _film,
112                 _player,
113                 map,
114                 _output_audio_channels,
115                 bind(&PlayerVideo::force, FFmpegFileEncoder::pixel_format(format)),
116                 VideoRange::VIDEO,
117                 Image::Alignment::PADDED,
118                 false,
119                 false,
120                 Butler::Audio::ENABLED
121                 );
122 }
123
124
125 void
126 FFmpegEncoder::go ()
127 {
128         {
129                 auto job = _job.lock ();
130                 DCPOMATIC_ASSERT (job);
131                 job->sub (_("Encoding"));
132         }
133
134         Waker waker;
135
136         list<FileEncoderSet> file_encoders;
137
138         int const files = _split_reels ? _film->reels().size() : 1;
139         for (int i = 0; i < files; ++i) {
140
141                 boost::filesystem::path filename = _output;
142                 string extension = boost::filesystem::extension (filename);
143                 filename = boost::filesystem::change_extension (filename, "");
144
145                 if (files > 1) {
146                         /// TRANSLATORS: _reel%1 here is to be added to an export filename to indicate
147                         /// which reel it is.  Preserve the %1; it will be replaced with the reel number.
148                         filename = filename.string() + String::compose(_("_reel%1"), i + 1);
149                 }
150
151                 file_encoders.push_back (
152                         FileEncoderSet (
153                                 _film->frame_size(),
154                                 _film->video_frame_rate(),
155                                 _film->audio_frame_rate(),
156                                 _output_audio_channels,
157                                 _format,
158                                 _audio_stream_per_channel,
159                                 _x264_crf,
160                                 _film->three_d(),
161                                 filename,
162                                 extension
163                                 )
164                         );
165         }
166
167         auto reel_periods = _film->reels ();
168         auto reel = reel_periods.begin ();
169         auto encoder = file_encoders.begin ();
170
171         auto const video_frame = DCPTime::from_frames (1, _film->video_frame_rate ());
172         int const audio_frames = video_frame.frames_round(_film->audio_frame_rate());
173         std::vector<float> interleaved(_output_audio_channels * audio_frames);
174         auto deinterleaved = make_shared<AudioBuffers>(_output_audio_channels, audio_frames);
175         int const gets_per_frame = _film->three_d() ? 2 : 1;
176         for (DCPTime i; i < _film->length(); i += video_frame) {
177
178                 if (file_encoders.size() > 1 && !reel->contains(i)) {
179                         /* Next reel and file */
180                         ++reel;
181                         ++encoder;
182                         DCPOMATIC_ASSERT (reel != reel_periods.end());
183                         DCPOMATIC_ASSERT (encoder != file_encoders.end());
184                 }
185
186                 for (int j = 0; j < gets_per_frame; ++j) {
187                         Butler::Error e;
188                         auto v = _butler->get_video (Butler::Behaviour::BLOCKING, &e);
189                         _butler->rethrow ();
190                         if (v.first) {
191                                 auto fe = encoder->get (v.first->eyes());
192                                 if (fe) {
193                                         fe->video(v.first, v.second - reel->from);
194                                 }
195                         } else {
196                                 if (e.code != Butler::Error::Code::FINISHED) {
197                                         throw DecodeError(String::compose("Error during decoding: %1", e.summary()));
198                                 }
199                         }
200                 }
201
202                 _history.event ();
203
204                 {
205                         boost::mutex::scoped_lock lm (_mutex);
206                         _last_time = i;
207                 }
208
209                 auto job = _job.lock ();
210                 if (job) {
211                         job->set_progress (float(i.get()) / _film->length().get());
212                 }
213
214                 waker.nudge ();
215
216                 _butler->get_audio (Butler::Behaviour::BLOCKING, interleaved.data(), audio_frames);
217                 /* XXX: inefficient; butler interleaves and we deinterleave again */
218                 float* p = interleaved.data();
219                 for (int j = 0; j < audio_frames; ++j) {
220                         for (int k = 0; k < _output_audio_channels; ++k) {
221                                 deinterleaved->data(k)[j] = *p++;
222                         }
223                 }
224                 encoder->audio (deinterleaved);
225         }
226
227         for (auto i: file_encoders) {
228                 i.flush ();
229         }
230 }
231
232 optional<float>
233 FFmpegEncoder::current_rate () const
234 {
235         return _history.rate ();
236 }
237
238 Frame
239 FFmpegEncoder::frames_done () const
240 {
241         boost::mutex::scoped_lock lm (_mutex);
242         return _last_time.frames_round (_film->video_frame_rate ());
243 }
244
245 FFmpegEncoder::FileEncoderSet::FileEncoderSet (
246         dcp::Size video_frame_size,
247         int video_frame_rate,
248         int audio_frame_rate,
249         int channels,
250         ExportFormat format,
251         bool audio_stream_per_channel,
252         int x264_crf,
253         bool three_d,
254         boost::filesystem::path output,
255         string extension
256         )
257 {
258         if (three_d) {
259                 /// TRANSLATORS: L here is an abbreviation for "left", to indicate the left-eye part of a 3D export
260                 _encoders[Eyes::LEFT] = make_shared<FFmpegFileEncoder>(
261                         video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
262                         audio_stream_per_channel, x264_crf, String::compose("%1_%2%3", output.string(), _("L"), extension)
263                         );
264                 /// TRANSLATORS: R here is an abbreviation for "right", to indicate the right-eye part of a 3D export
265                 _encoders[Eyes::RIGHT] = make_shared<FFmpegFileEncoder>(
266                         video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
267                         audio_stream_per_channel, x264_crf, String::compose("%1_%2%3", output.string(), _("R"), extension)
268                         );
269         } else {
270                 _encoders[Eyes::BOTH] = make_shared<FFmpegFileEncoder>(
271                         video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
272                         audio_stream_per_channel, x264_crf, String::compose("%1%2", output.string(), extension)
273                         );
274         }
275 }
276
277 shared_ptr<FFmpegFileEncoder>
278 FFmpegEncoder::FileEncoderSet::get (Eyes eyes) const
279 {
280         if (_encoders.size() == 1) {
281                 /* We are doing a 2D export... */
282                 if (eyes == Eyes::LEFT) {
283                         /* ...but we got some 3D data; put the left eye into the output... */
284                         eyes = Eyes::BOTH;
285                 } else if (eyes == Eyes::RIGHT) {
286                         /* ...and ignore the right eye.*/
287                         return {};
288                 }
289         }
290
291         auto i = _encoders.find (eyes);
292         DCPOMATIC_ASSERT (i != _encoders.end());
293         return i->second;
294 }
295
296 void
297 FFmpegEncoder::FileEncoderSet::flush ()
298 {
299         for (auto& i: _encoders) {
300                 i.second->flush ();
301         }
302 }
303
304 void
305 FFmpegEncoder::FileEncoderSet::audio (shared_ptr<AudioBuffers> a)
306 {
307         for (auto& i: _encoders) {
308                 i.second->audio (a);
309         }
310 }