Fix options for libx264.
[dcpomatic.git] / src / lib / ffmpeg_encoder.cc
1 /*
2     Copyright (C) 2017 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 "compose.hpp"
29 #include <iostream>
30
31 #include "i18n.h"
32
33 using std::string;
34 using std::runtime_error;
35 using std::cout;
36 using boost::shared_ptr;
37 using boost::bind;
38 using boost::weak_ptr;
39
40 static AVPixelFormat
41 force_pixel_format (AVPixelFormat, AVPixelFormat out)
42 {
43         return out;
44 }
45
46 FFmpegEncoder::FFmpegEncoder (shared_ptr<const Film> film, weak_ptr<Job> job, boost::filesystem::path output, Format format)
47         : Encoder (film, job)
48         , _options (0)
49         , _history (1000)
50         , _output (output)
51 {
52         switch (format) {
53         case FORMAT_PRORES:
54                 _pixel_format = AV_PIX_FMT_YUV422P10;
55                 _codec_name = "prores_ks";
56                 av_dict_set (&_options, "profile", "3", 0);
57                 av_dict_set (&_options, "threads", "auto", 0);
58                 break;
59         case FORMAT_H264:
60                 _pixel_format = AV_PIX_FMT_YUV420P;
61                 _codec_name = "libx264";
62                 break;
63         }
64 }
65
66 void
67 FFmpegEncoder::go ()
68 {
69         AVCodec* codec = avcodec_find_encoder_by_name (_codec_name.c_str());
70         if (!codec) {
71                 throw runtime_error (String::compose ("could not find FFmpeg encoder %1", _codec_name));
72         }
73
74         _codec_context = avcodec_alloc_context3 (codec);
75         if (!_codec_context) {
76                 throw runtime_error ("could not allocate FFmpeg context");
77         }
78
79         avcodec_get_context_defaults3 (_codec_context, codec);
80
81         /* Variable quantisation */
82         _codec_context->global_quality = 0;
83         _codec_context->width = _film->frame_size().width;
84         _codec_context->height = _film->frame_size().height;
85         _codec_context->time_base = (AVRational) { 1, _film->video_frame_rate() };
86         _codec_context->pix_fmt = _pixel_format;
87         _codec_context->flags |= CODEC_FLAG_QSCALE | CODEC_FLAG_GLOBAL_HEADER;
88
89         avformat_alloc_output_context2 (&_format_context, 0, 0, _output.string().c_str());
90         if (!_format_context) {
91                 throw runtime_error ("could not allocate FFmpeg format context");
92         }
93
94         _video_stream = avformat_new_stream (_format_context, codec);
95         if (!_video_stream) {
96                 throw runtime_error ("could not create FFmpeg output video stream");
97         }
98
99         /* Note: needs to increment with each stream */
100         _video_stream->id = 0;
101         _video_stream->codec = _codec_context;
102
103         if (avcodec_open2 (_codec_context, codec, &_options) < 0) {
104                 throw runtime_error ("could not open FFmpeg codec");
105         }
106
107         if (avio_open (&_format_context->pb, _output.c_str(), AVIO_FLAG_WRITE) < 0) {
108                 throw runtime_error ("could not open FFmpeg output file");
109         }
110
111         if (avformat_write_header (_format_context, &_options) < 0) {
112                 throw runtime_error ("could not write header to FFmpeg output file");
113         }
114
115         {
116                 shared_ptr<Job> job = _job.lock ();
117                 DCPOMATIC_ASSERT (job);
118                 job->sub (_("Encoding"));
119         }
120
121         while (!_player->pass ()) {}
122
123         while (true) {
124                 AVPacket packet;
125                 av_init_packet (&packet);
126                 packet.data = 0;
127                 packet.size = 0;
128
129                 int got_packet;
130                 avcodec_encode_video2 (_codec_context, &packet, 0, &got_packet);
131                 if (!got_packet) {
132                         break;
133                 }
134
135                 packet.stream_index = 0;
136                 av_interleaved_write_frame (_format_context, &packet);
137                 av_packet_unref (&packet);
138         }
139
140         av_write_trailer (_format_context);
141
142         avcodec_close (_codec_context);
143         avio_close (_format_context->pb);
144         avformat_free_context (_format_context);
145 }
146
147 void
148 FFmpegEncoder::video (shared_ptr<PlayerVideo> video, DCPTime time)
149 {
150         shared_ptr<Image> image = video->image (
151                 bind (&Log::dcp_log, _film->log().get(), _1, _2),
152                 bind (&force_pixel_format, _1, _pixel_format),
153                 true,
154                 false
155                 );
156
157         AVFrame* frame = av_frame_alloc ();
158
159         for (int i = 0; i < 3; ++i) {
160                 size_t const size = image->stride()[i] * image->size().height;
161                 AVBufferRef* buffer = av_buffer_alloc (size);
162                 /* XXX: inefficient */
163                 memcpy (buffer->data, image->data()[i], size);
164                 frame->buf[i] = av_buffer_ref (buffer);
165                 frame->data[i] = buffer->data;
166                 frame->linesize[i] = image->stride()[i];
167                 av_buffer_unref (&buffer);
168         }
169
170         frame->width = image->size().width;
171         frame->height = image->size().height;
172         frame->format = _pixel_format;
173         frame->pts = time.seconds() / av_q2d (_video_stream->time_base);
174
175         AVPacket packet;
176         av_init_packet (&packet);
177         packet.data = 0;
178         packet.size = 0;
179
180         int got_packet;
181         if (avcodec_encode_video2 (_codec_context, &packet, frame, &got_packet) < 0) {
182                 throw EncodeError ("FFmpeg video encode failed");
183         }
184
185         if (got_packet && packet.size) {
186                 /* XXX: this should not be hard-wired */
187                 packet.stream_index = 0;
188                 av_interleaved_write_frame (_format_context, &packet);
189                 av_packet_unref (&packet);
190         }
191
192         av_frame_free (&frame);
193
194         _history.event ();
195
196         {
197                 boost::mutex::scoped_lock lm (_mutex);
198                 _last_time = time;
199         }
200
201         shared_ptr<Job> job = _job.lock ();
202         if (job) {
203                 job->set_progress (float(time.get()) / _film->length().get());
204         }
205 }
206
207 void
208 FFmpegEncoder::audio (shared_ptr<AudioBuffers> audio, DCPTime time)
209 {
210
211 }
212
213 void
214 FFmpegEncoder::subtitle (PlayerSubtitles subs, DCPTimePeriod period)
215 {
216
217 }
218
219 float
220 FFmpegEncoder::current_rate () const
221 {
222         return _history.rate ();
223 }
224
225 Frame
226 FFmpegEncoder::frames_done () const
227 {
228         boost::mutex::scoped_lock lm (_mutex);
229         return _last_time.frames_round (_film->video_frame_rate ());
230 }