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