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