68575d11adc072c69b9a2bc1e16f93a223fd1b0f
[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
45 FFmpegEncoder::FFmpegEncoder (
46         shared_ptr<const Film> film,
47         weak_ptr<Job> job,
48         boost::filesystem::path output,
49         ExportFormat format,
50         bool mixdown_to_stereo,
51         bool split_reels,
52         int x264_crf
53         )
54         : Encoder (film, job)
55         , _history (1000)
56 {
57         int const files = split_reels ? film->reels().size() : 1;
58         for (int i = 0; i < files; ++i) {
59
60                 boost::filesystem::path filename = output;
61                 string extension = boost::filesystem::extension (filename);
62                 filename = boost::filesystem::change_extension (filename, "");
63
64                 if (files > 1) {
65                         /// TRANSLATORS: _reel%1 here is to be added to an export filename to indicate
66                         /// which reel it is.  Preserve the %1; it will be replaced with the reel number.
67                         filename = filename.string() + String::compose(_("_reel%1"), i + 1);
68                 }
69
70                 _file_encoders.push_back (
71                         FileEncoderSet (
72                                 _film->frame_size(),
73                                 _film->video_frame_rate(),
74                                 _film->audio_frame_rate(),
75                                 mixdown_to_stereo ? 2 : film->audio_channels(),
76                                 format,
77                                 x264_crf,
78                                 _film->three_d(),
79                                 filename,
80                                 extension
81                                 )
82                         );
83         }
84
85         _player->set_always_burn_open_subtitles ();
86         _player->set_play_referenced ();
87
88         int const ch = film->audio_channels ();
89
90         AudioMapping map;
91         if (mixdown_to_stereo) {
92                 _output_audio_channels = 2;
93                 map = AudioMapping (ch, 2);
94                 float const overall_gain = 2 / (4 + sqrt(2));
95                 float const minus_3dB = 1 / sqrt(2);
96                 map.set (dcp::LEFT,   0, overall_gain);
97                 map.set (dcp::RIGHT,  1, overall_gain);
98                 map.set (dcp::CENTRE, 0, overall_gain * minus_3dB);
99                 map.set (dcp::CENTRE, 1, overall_gain * minus_3dB);
100                 map.set (dcp::LS,     0, overall_gain);
101                 map.set (dcp::RS,     1, overall_gain);
102         } else {
103                 _output_audio_channels = ch;
104                 map = AudioMapping (ch, ch);
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 void
114 FFmpegEncoder::go ()
115 {
116         {
117                 shared_ptr<Job> job = _job.lock ();
118                 DCPOMATIC_ASSERT (job);
119                 job->sub (_("Encoding"));
120         }
121
122         Waker waker;
123
124         list<DCPTimePeriod> reel_periods = _film->reels ();
125         list<DCPTimePeriod>::const_iterator reel = reel_periods.begin ();
126         list<FileEncoderSet>::iterator encoder = _file_encoders.begin ();
127
128         DCPTime const video_frame = DCPTime::from_frames (1, _film->video_frame_rate ());
129         int const audio_frames = video_frame.frames_round(_film->audio_frame_rate());
130         float* interleaved = new float[_output_audio_channels * audio_frames];
131         shared_ptr<AudioBuffers> deinterleaved (new AudioBuffers (_output_audio_channels, audio_frames));
132         int const gets_per_frame = _film->three_d() ? 2 : 1;
133         for (DCPTime i; i < _film->length(); i += video_frame) {
134
135                 if (_file_encoders.size() > 1 && !reel->contains(i)) {
136                         /* Next reel and file */
137                         ++reel;
138                         ++encoder;
139                         DCPOMATIC_ASSERT (reel != reel_periods.end());
140                         DCPOMATIC_ASSERT (encoder != _file_encoders.end());
141                 }
142
143                 for (int j = 0; j < gets_per_frame; ++j) {
144                         Butler::Error e;
145                         pair<shared_ptr<PlayerVideo>, DCPTime> v = _butler->get_video (&e);
146                         if (!v.first) {
147                                 throw ProgrammingError(__FILE__, __LINE__, String::compose("butler returned no video; error was %1", static_cast<int>(e)));
148                         }
149                         shared_ptr<FFmpegFileEncoder> fe = encoder->get (v.first->eyes());
150                         if (fe) {
151                                 fe->video(v.first, v.second);
152                         }
153                 }
154
155                 _history.event ();
156
157                 {
158                         boost::mutex::scoped_lock lm (_mutex);
159                         _last_time = i;
160                 }
161
162                 shared_ptr<Job> job = _job.lock ();
163                 if (job) {
164                         job->set_progress (float(i.get()) / _film->length().get());
165                 }
166
167                 waker.nudge ();
168
169                 _butler->get_audio (interleaved, audio_frames);
170                 /* XXX: inefficient; butler interleaves and we deinterleave again */
171                 float* p = interleaved;
172                 for (int j = 0; j < audio_frames; ++j) {
173                         for (int k = 0; k < _output_audio_channels; ++k) {
174                                 deinterleaved->data(k)[j] = *p++;
175                         }
176                 }
177                 encoder->audio (deinterleaved);
178         }
179         delete[] interleaved;
180
181         BOOST_FOREACH (FileEncoderSet i, _file_encoders) {
182                 i.flush ();
183         }
184
185         _butler->rethrow ();
186 }
187
188 float
189 FFmpegEncoder::current_rate () const
190 {
191         return _history.rate ();
192 }
193
194 Frame
195 FFmpegEncoder::frames_done () const
196 {
197         boost::mutex::scoped_lock lm (_mutex);
198         return _last_time.frames_round (_film->video_frame_rate ());
199 }
200
201 FFmpegEncoder::FileEncoderSet::FileEncoderSet (
202         dcp::Size video_frame_size,
203         int video_frame_rate,
204         int audio_frame_rate,
205         int channels,
206         ExportFormat format,
207         int x264_crf,
208         bool three_d,
209         boost::filesystem::path output,
210         string extension
211         )
212 {
213         if (three_d) {
214                 /// TRANSLATORS: L here is an abbreviation for "left", to indicate the left-eye part of a 3D export
215                 _encoders[EYES_LEFT] = shared_ptr<FFmpegFileEncoder>(
216                         new FFmpegFileEncoder(video_frame_size, video_frame_rate, audio_frame_rate, channels, format, x264_crf, String::compose("%1_%2%3", output.string(), _("L"), extension))
217                         );
218                 /// TRANSLATORS: R here is an abbreviation for "left", to indicate the left-eye part of a 3D export
219                 _encoders[EYES_RIGHT] = shared_ptr<FFmpegFileEncoder>(
220                         new FFmpegFileEncoder(video_frame_size, video_frame_rate, audio_frame_rate, channels, format, x264_crf, String::compose("%1_%2%3", output.string(), _("R"), extension))
221                         );
222         } else {
223                 _encoders[EYES_BOTH]  = shared_ptr<FFmpegFileEncoder>(
224                         new FFmpegFileEncoder(video_frame_size, video_frame_rate, audio_frame_rate, channels, format, x264_crf, String::compose("%1%2", output.string(), extension))
225                         );
226         }
227 }
228
229 shared_ptr<FFmpegFileEncoder>
230 FFmpegEncoder::FileEncoderSet::get (Eyes eyes) const
231 {
232         if (_encoders.size() == 1) {
233                 /* We are doing a 2D export... */
234                 if (eyes == EYES_LEFT) {
235                         /* ...but we got some 3D data; put the left eye into the output... */
236                         eyes = EYES_BOTH;
237                 } else if (eyes == EYES_RIGHT) {
238                         /* ...and ignore the right eye.*/
239                         return shared_ptr<FFmpegFileEncoder>();
240                 }
241         }
242
243         map<Eyes, boost::shared_ptr<FFmpegFileEncoder> >::const_iterator i = _encoders.find (eyes);
244         DCPOMATIC_ASSERT (i != _encoders.end());
245         return i->second;
246 }
247
248 void
249 FFmpegEncoder::FileEncoderSet::flush ()
250 {
251         for (map<Eyes, boost::shared_ptr<FFmpegFileEncoder> >::iterator i = _encoders.begin(); i != _encoders.end(); ++i) {
252                 i->second->flush ();
253         }
254 }
255
256 void
257 FFmpegEncoder::FileEncoderSet::audio (shared_ptr<AudioBuffers> a)
258 {
259         for (map<Eyes, boost::shared_ptr<FFmpegFileEncoder> >::iterator i = _encoders.begin(); i != _encoders.end(); ++i) {
260                 i->second->audio (a);
261         }
262 }