152194c482f415560320a4feaae9fb0816770431
[dcpomatic.git] / src / tools / dcpomatic_ecinema.cc
1 /*
2     Copyright (C) 2018-2019 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 "lib/version.h"
22 #include "lib/decrypted_ecinema_kdm.h"
23 #include "lib/config.h"
24 #include "lib/util.h"
25 #include "lib/film.h"
26 #include "lib/dcp_content.h"
27 #include "lib/job_manager.h"
28 #include "lib/cross.h"
29 #include "lib/transcode_job.h"
30 #include "lib/ffmpeg_encoder.h"
31 #include "lib/signal_manager.h"
32 #include "lib/video_content.h"
33 #include "lib/ratio.h"
34 #include <dcp/key.h>
35 extern "C" {
36 #include <libavformat/avformat.h>
37 #include <libavutil/aes_ctr.h>
38 }
39 #include <boost/filesystem.hpp>
40 #include <boost/optional.hpp>
41 #include <openssl/rand.h>
42 #include <getopt.h>
43 #include <sys/stat.h>
44 #include <sys/types.h>
45 #include <string>
46 #include <iostream>
47
48 using std::string;
49 using std::cerr;
50 using std::cout;
51 using std::ofstream;
52 using boost::optional;
53 using boost::shared_ptr;
54
55 static void convert_dcp (
56         boost::filesystem::path input,
57         boost::filesystem::path output_file,
58         boost::optional<boost::filesystem::path> kdm,
59         int crf
60         );
61 static void convert_ffmpeg (boost::filesystem::path input, boost::filesystem::path output_file, string format);
62 static void write_kdm (string id, boost::filesystem::path name, dcp::Key key);
63
64 static void
65 help (string n)
66 {
67         cerr << "Syntax: " << n << " [OPTION] <FILE>|<DIRECTORY>\n"
68              << "  -v, --version        show DCP-o-matic version\n"
69              << "  -h, --help           show this help\n"
70              << "  -o, --output         output directory\n"
71              << "  -f, --format         output format (mov or mp4; defaults to mov)\n"
72              << "  -k, --kdm            DCP KDM filename (if required)\n"
73              << "  -c, --crf            quality (CRF) when transcoding from DCP (0 is best, 51 is worst, defaults to 23)\n"
74              << "\n"
75              << "<FILE> is an unencrypted .mp4 file; <DIRECTORY> is a DCP directory.\n";
76 }
77
78 int
79 main (int argc, char* argv[])
80 {
81         optional<boost::filesystem::path> output;
82         optional<string> format;
83         optional<boost::filesystem::path> kdm;
84         int crf = 23;
85
86         int option_index = 0;
87         while (true) {
88                 static struct option long_options[] = {
89                         { "version", no_argument, 0, 'v' },
90                         { "help", no_argument, 0, 'h' },
91                         { "output", required_argument, 0, 'o' },
92                         { "format", required_argument, 0, 'f' },
93                         { "kdm", required_argument, 0, 'k' },
94                         { "crf", required_argument, 0, 'c' },
95                 };
96
97                 int c = getopt_long (argc, argv, "vho:f:k:c:", long_options, &option_index);
98
99                 if (c == -1) {
100                         break;
101                 }
102
103                 switch (c) {
104                 case 'v':
105                         cout << "dcpomatic version " << dcpomatic_version << " " << dcpomatic_git_commit << "\n";
106                         exit (EXIT_SUCCESS);
107                 case 'h':
108                         help (argv[0]);
109                         exit (EXIT_SUCCESS);
110                 case 'o':
111                         output = optarg;
112                         break;
113                 case 'f':
114                         format = optarg;
115                         break;
116                 case 'k':
117                         kdm = optarg;
118                         break;
119                 case 'c':
120                         crf = atoi(optarg);
121                         break;
122                 }
123         }
124
125         if (optind >= argc) {
126                 help (argv[0]);
127                 exit (EXIT_FAILURE);
128         }
129
130         if (!output) {
131                 cerr << "You must specify --output-media or -o\n";
132                 exit (EXIT_FAILURE);
133         }
134
135         if (!format) {
136                 format = "mov";
137         }
138
139         if (*format != "mov" && *format != "mp4") {
140                 cerr << "Invalid format specified: must be mov or mp4\n";
141                 exit (EXIT_FAILURE);
142         }
143
144         dcpomatic_setup_path_encoding ();
145         dcpomatic_setup ();
146         signal_manager = new SignalManager ();
147
148         boost::filesystem::path input = argv[optind];
149         boost::filesystem::path output_file;
150         if (boost::filesystem::is_directory(input)) {
151                 output_file = *output / (input.parent_path().filename().string() + ".ecinema");
152         } else {
153                 output_file = *output / (input.filename().string() + ".ecinema");
154         }
155
156         if (!boost::filesystem::is_directory(*output)) {
157                 boost::filesystem::create_directory (*output);
158         }
159
160         av_register_all ();
161
162         if (boost::filesystem::is_directory(input)) {
163                 /* Assume input is a DCP */
164                 convert_dcp (input, output_file, kdm, crf);
165         } else {
166                 convert_ffmpeg (input, output_file, *format);
167         }
168 }
169
170 static void
171 convert_ffmpeg (boost::filesystem::path input, boost::filesystem::path output_file, string format)
172 {
173         AVFormatContext* input_fc = avformat_alloc_context ();
174         if (avformat_open_input(&input_fc, input.string().c_str(), 0, 0) < 0) {
175                 cerr << "Could not open input file\n";
176                 exit (EXIT_FAILURE);
177         }
178
179         if (avformat_find_stream_info (input_fc, 0) < 0) {
180                 cerr << "Could not read stream information\n";
181                 exit (EXIT_FAILURE);
182         }
183
184         AVFormatContext* output_fc;
185         avformat_alloc_output_context2 (&output_fc, av_guess_format(format.c_str(), 0, 0), 0, 0);
186
187         for (uint32_t i = 0; i < input_fc->nb_streams; ++i) {
188                 AVStream* is = input_fc->streams[i];
189                 AVStream* os = avformat_new_stream (output_fc, is->codec->codec);
190                 if (avcodec_parameters_copy (os->codecpar, is->codecpar) < 0) {
191                         cerr << "Could not set up output stream.\n";
192                         exit (EXIT_FAILURE);
193                 }
194
195                 os->avg_frame_rate = is->avg_frame_rate;
196
197                 switch (is->codec->codec_type) {
198                 case AVMEDIA_TYPE_VIDEO:
199                         os->time_base = is->time_base;
200                         os->r_frame_rate = is->r_frame_rate;
201                         os->sample_aspect_ratio = is->sample_aspect_ratio;
202                         os->codec->time_base = is->codec->time_base;
203                         os->codec->framerate = is->codec->framerate;
204                         os->codec->pix_fmt = is->codec->pix_fmt;
205                         break;
206                 case AVMEDIA_TYPE_AUDIO:
207                         os->codec->sample_fmt = is->codec->sample_fmt;
208                         os->codec->bits_per_raw_sample = is->codec->bits_per_raw_sample;
209                         os->codec->sample_rate = is->codec->sample_rate;
210                         os->codec->channel_layout = is->codec->channel_layout;
211                         os->codec->channels = is->codec->channels;
212                         if (is->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
213                                 /* XXX: fix incoming 24-bit files labelled lpcm, which apparently isn't allowed */
214                                 os->codecpar->codec_tag = MKTAG('i', 'n', '2', '4');
215                         }
216                         break;
217                 default:
218                         /* XXX */
219                         break;
220                 }
221         }
222
223         if (avio_open2 (&output_fc->pb, output_file.string().c_str(), AVIO_FLAG_WRITE, 0, 0) < 0) {
224                 cerr << "Could not open output file `" << output_file.string() << "'\n";
225                 exit (EXIT_FAILURE);
226         }
227
228         dcp::Key key (AES_CTR_KEY_SIZE);
229         AVDictionary* options = 0;
230         av_dict_set (&options, "encryption_key", key.hex().c_str(), 0);
231         /* XXX: is this OK? */
232         av_dict_set (&options, "encryption_kid", "00000000000000000000000000000000", 0);
233         av_dict_set (&options, "encryption_scheme", "cenc-aes-ctr", 0);
234
235         string id = dcp::make_uuid ();
236         if (av_dict_set(&output_fc->metadata, SWAROOP_ID_TAG, id.c_str(), 0) < 0) {
237                 cerr << "Could not write ID to output.\n";
238                 exit (EXIT_FAILURE);
239         }
240
241         if (avformat_write_header (output_fc, &options) < 0) {
242                 cerr << "Could not write header to output.\n";
243                 exit (EXIT_FAILURE);
244         }
245
246         AVPacket packet;
247         while (av_read_frame(input_fc, &packet) >= 0) {
248                 AVStream* is = input_fc->streams[packet.stream_index];
249                 AVStream* os = output_fc->streams[packet.stream_index];
250                 packet.pts = av_rescale_q_rnd(packet.pts, is->time_base, os->time_base, (AVRounding) (AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
251                 packet.dts = av_rescale_q_rnd(packet.dts, is->time_base, os->time_base, (AVRounding) (AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
252                 packet.duration = av_rescale_q(packet.duration, is->time_base, os->time_base);
253                 packet.pos = -1;
254                 if (av_interleaved_write_frame (output_fc, &packet) < 0) {
255                         cerr << "Could not write frame to output.\n";
256                         exit (EXIT_FAILURE);
257                 }
258         }
259
260         av_write_trailer (output_fc);
261
262         avformat_free_context (input_fc);
263         avformat_free_context (output_fc);
264
265         write_kdm (id, output_file, key);
266 }
267
268 static void
269 write_kdm (string id, boost::filesystem::path name, dcp::Key key)
270 {
271         DecryptedECinemaKDM decrypted_kdm (id, name.filename().string(), key, optional<dcp::LocalTime>(), optional<dcp::LocalTime>());
272         EncryptedECinemaKDM encrypted_kdm = decrypted_kdm.encrypt (Config::instance()->decryption_chain()->leaf());
273
274         ofstream f(string(name.string() + ".xml").c_str());
275         f << encrypted_kdm.as_xml() << "\n";
276 }
277
278 static void
279 convert_dcp (
280         boost::filesystem::path input, boost::filesystem::path output_file, optional<boost::filesystem::path> kdm, int crf
281         )
282 {
283         shared_ptr<Film> film (new Film(boost::optional<boost::filesystem::path>()));
284         shared_ptr<DCPContent> dcp (new DCPContent(input));
285         film->examine_and_add_content (dcp);
286         if (kdm) {
287                 dcp->add_kdm (dcp::EncryptedKDM(dcp::file_to_string(*kdm)));
288         }
289
290         JobManager* jm = JobManager::instance ();
291         while (jm->work_to_do ()) {
292                 while (signal_manager->ui_idle ()) {}
293                 dcpomatic_sleep_seconds (1);
294         }
295         DCPOMATIC_ASSERT (!jm->errors());
296
297         film->set_container (Ratio::nearest_from_ratio(dcp->video->size().ratio()));
298         
299         string id = dcp::make_uuid ();
300         dcp::Key key (AES_CTR_KEY_SIZE);
301
302         shared_ptr<TranscodeJob> job (new TranscodeJob(film));
303         job->set_encoder (
304                 shared_ptr<FFmpegEncoder>(
305                         new FFmpegEncoder(film, job, output_file, EXPORT_FORMAT_H264_PCM, false, false, crf, key, id)
306                         )
307                 );
308         jm->add (job);
309         show_jobs_on_console (true);
310
311         write_kdm (id, output_file, key);
312 }