Use dcp::file_to_string().
[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::cout;
36 using std::list;
37 using std::make_shared;
38 using std::map;
39 using std::pair;
40 using std::runtime_error;
41 using std::shared_ptr;
42 using std::string;
43 using std::weak_ptr;
44 using boost::bind;
45 using boost::optional;
46 using namespace dcpomatic;
47 #if BOOST_VERSION >= 106100
48 using namespace boost::placeholders;
49 #endif
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, _player, map, _output_audio_channels, bind(&PlayerVideo::force, _1, FFmpegFileEncoder::pixel_format(format)), VideoRange::VIDEO, true, false
112                 );
113 }
114
115
116 void
117 FFmpegEncoder::go ()
118 {
119         {
120                 auto job = _job.lock ();
121                 DCPOMATIC_ASSERT (job);
122                 job->sub (_("Encoding"));
123         }
124
125         Waker waker;
126
127         list<FileEncoderSet> file_encoders;
128
129         int const files = _split_reels ? _film->reels().size() : 1;
130         for (int i = 0; i < files; ++i) {
131
132                 boost::filesystem::path filename = _output;
133                 string extension = boost::filesystem::extension (filename);
134                 filename = boost::filesystem::change_extension (filename, "");
135
136                 if (files > 1) {
137                         /// TRANSLATORS: _reel%1 here is to be added to an export filename to indicate
138                         /// which reel it is.  Preserve the %1; it will be replaced with the reel number.
139                         filename = filename.string() + String::compose(_("_reel%1"), i + 1);
140                 }
141
142                 file_encoders.push_back (
143                         FileEncoderSet (
144                                 _film->frame_size(),
145                                 _film->video_frame_rate(),
146                                 _film->audio_frame_rate(),
147                                 _output_audio_channels,
148                                 _format,
149                                 _audio_stream_per_channel,
150                                 _x264_crf,
151                                 _film->three_d(),
152                                 filename,
153                                 extension
154                                 )
155                         );
156         }
157
158         auto reel_periods = _film->reels ();
159         auto reel = reel_periods.begin ();
160         auto encoder = file_encoders.begin ();
161
162         auto const video_frame = DCPTime::from_frames (1, _film->video_frame_rate ());
163         int const audio_frames = video_frame.frames_round(_film->audio_frame_rate());
164         float* interleaved = new float[_output_audio_channels * audio_frames];
165         auto deinterleaved = make_shared<AudioBuffers>(_output_audio_channels, audio_frames);
166         int const gets_per_frame = _film->three_d() ? 2 : 1;
167         for (DCPTime i; i < _film->length(); i += video_frame) {
168
169                 if (file_encoders.size() > 1 && !reel->contains(i)) {
170                         /* Next reel and file */
171                         ++reel;
172                         ++encoder;
173                         DCPOMATIC_ASSERT (reel != reel_periods.end());
174                         DCPOMATIC_ASSERT (encoder != file_encoders.end());
175                 }
176
177                 for (int j = 0; j < gets_per_frame; ++j) {
178                         Butler::Error e;
179                         auto v = _butler->get_video (true, &e);
180                         _butler->rethrow ();
181                         if (!v.first) {
182                                 throw DecodeError(String::compose("Error during decoding: %1", e.summary()));
183                         }
184                         auto fe = encoder->get (v.first->eyes());
185                         if (fe) {
186                                 fe->video(v.first, v.second - reel->from);
187                         }
188                 }
189
190                 _history.event ();
191
192                 {
193                         boost::mutex::scoped_lock lm (_mutex);
194                         _last_time = i;
195                 }
196
197                 auto job = _job.lock ();
198                 if (job) {
199                         job->set_progress (float(i.get()) / _film->length().get());
200                 }
201
202                 waker.nudge ();
203
204                 _butler->get_audio (interleaved, audio_frames);
205                 /* XXX: inefficient; butler interleaves and we deinterleave again */
206                 float* p = interleaved;
207                 for (int j = 0; j < audio_frames; ++j) {
208                         for (int k = 0; k < _output_audio_channels; ++k) {
209                                 deinterleaved->data(k)[j] = *p++;
210                         }
211                 }
212                 encoder->audio (deinterleaved);
213         }
214         delete[] interleaved;
215
216         for (auto i: file_encoders) {
217                 i.flush ();
218         }
219 }
220
221 optional<float>
222 FFmpegEncoder::current_rate () const
223 {
224         return _history.rate ();
225 }
226
227 Frame
228 FFmpegEncoder::frames_done () const
229 {
230         boost::mutex::scoped_lock lm (_mutex);
231         return _last_time.frames_round (_film->video_frame_rate ());
232 }
233
234 FFmpegEncoder::FileEncoderSet::FileEncoderSet (
235         dcp::Size video_frame_size,
236         int video_frame_rate,
237         int audio_frame_rate,
238         int channels,
239         ExportFormat format,
240         bool audio_stream_per_channel,
241         int x264_crf,
242         bool three_d,
243         boost::filesystem::path output,
244         string extension
245         )
246 {
247         if (three_d) {
248                 /// TRANSLATORS: L here is an abbreviation for "left", to indicate the left-eye part of a 3D export
249                 _encoders[Eyes::LEFT] = make_shared<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] = make_shared<FFmpegFileEncoder>(
255                         video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
256                         audio_stream_per_channel, x264_crf, String::compose("%1_%2%3", output.string(), _("R"), extension)
257                         );
258         } else {
259                 _encoders[Eyes::BOTH] = make_shared<FFmpegFileEncoder>(
260                         video_frame_size, video_frame_rate, audio_frame_rate, channels, format,
261                         audio_stream_per_channel, x264_crf, String::compose("%1%2", output.string(), extension)
262                         );
263         }
264 }
265
266 shared_ptr<FFmpegFileEncoder>
267 FFmpegEncoder::FileEncoderSet::get (Eyes eyes) const
268 {
269         if (_encoders.size() == 1) {
270                 /* We are doing a 2D export... */
271                 if (eyes == Eyes::LEFT) {
272                         /* ...but we got some 3D data; put the left eye into the output... */
273                         eyes = Eyes::BOTH;
274                 } else if (eyes == Eyes::RIGHT) {
275                         /* ...and ignore the right eye.*/
276                         return shared_ptr<FFmpegFileEncoder>();
277                 }
278         }
279
280         auto i = _encoders.find (eyes);
281         DCPOMATIC_ASSERT (i != _encoders.end());
282         return i->second;
283 }
284
285 void
286 FFmpegEncoder::FileEncoderSet::flush ()
287 {
288         for (auto& i: _encoders) {
289                 i.second->flush ();
290         }
291 }
292
293 void
294 FFmpegEncoder::FileEncoderSet::audio (shared_ptr<AudioBuffers> a)
295 {
296         for (auto& i: _encoders) {
297                 i.second->audio (a);
298         }
299 }