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