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