swaroop: add --kdm option to dcpomatic2_ecinema.
[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 <dcp/key.h>
26 extern "C" {
27 #include <libavformat/avformat.h>
28 #include <libavutil/aes_ctr.h>
29 }
30 #include <boost/filesystem.hpp>
31 #include <boost/optional.hpp>
32 #include <openssl/rand.h>
33 #include <getopt.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <string>
37 #include <iostream>
38
39 using std::string;
40 using std::cerr;
41 using std::cout;
42 using std::ofstream;
43 using boost::optional;
44
45 static void
46 help (string n)
47 {
48         cerr << "Syntax: " << n << " [OPTION] <FILE>\n"
49              << "  -v, --version        show DCP-o-matic version\n"
50              << "  -h, --help           show this help\n"
51              << "  -o, --output         output directory\n"
52              << "  -f, --format         output format (mov or mp4; defaults to mov)\n"
53              << "  -k, --kdm            KDM output filename (defaults to stdout)\n"
54              << "\n"
55              << "<FILE> is the unencrypted .mp4 file.\n";
56 }
57
58 int
59 main (int argc, char* argv[])
60 {
61         optional<boost::filesystem::path> output;
62         optional<boost::filesystem::path> format;
63         optional<boost::filesystem::path> kdm;
64
65         int option_index = 0;
66         while (true) {
67                 static struct option long_options[] = {
68                         { "version", no_argument, 0, 'v' },
69                         { "help", no_argument, 0, 'h' },
70                         { "output", required_argument, 0, 'o' },
71                         { "format", required_argument, 0, 'f' },
72                         { "kdm", required_argument, 0, 'k' },
73                 };
74
75                 int c = getopt_long (argc, argv, "vho:f:k:", long_options, &option_index);
76
77                 if (c == -1) {
78                         break;
79                 }
80
81                 switch (c) {
82                 case 'v':
83                         cout << "dcpomatic version " << dcpomatic_version << " " << dcpomatic_git_commit << "\n";
84                         exit (EXIT_SUCCESS);
85                 case 'h':
86                         help (argv[0]);
87                         exit (EXIT_SUCCESS);
88                 case 'o':
89                         output = optarg;
90                         break;
91                 case 'f':
92                         format = optarg;
93                         break;
94                 case 'k':
95                         kdm = optarg;
96                         break;
97                 }
98         }
99
100         if (optind >= argc) {
101                 help (argv[0]);
102                 exit (EXIT_FAILURE);
103         }
104
105         if (!output) {
106                 cerr << "You must specify --output-media or -o\n";
107                 exit (EXIT_FAILURE);
108         }
109
110         if (!format) {
111                 format = "mov";
112         }
113
114         if (*format != "mov" && *format != "mp4") {
115                 cerr << "Invalid format specified: must be mov or mp4\n";
116                 exit (EXIT_FAILURE);
117         }
118
119         boost::filesystem::path input = argv[optind];
120         boost::filesystem::path output_file = *output / (input.filename().string() + ".ecinema");
121
122         if (!boost::filesystem::is_directory(*output)) {
123                 boost::filesystem::create_directory (*output);
124         }
125
126         av_register_all ();
127
128         AVFormatContext* input_fc = avformat_alloc_context ();
129         if (avformat_open_input(&input_fc, input.string().c_str(), 0, 0) < 0) {
130                 cerr << "Could not open input file\n";
131                 exit (EXIT_FAILURE);
132         }
133
134         if (avformat_find_stream_info (input_fc, 0) < 0) {
135                 cerr << "Could not read stream information\n";
136                 exit (EXIT_FAILURE);
137         }
138
139         AVFormatContext* output_fc;
140         avformat_alloc_output_context2 (&output_fc, av_guess_format(format->c_str(), 0, 0), 0, 0);
141
142         for (uint32_t i = 0; i < input_fc->nb_streams; ++i) {
143                 AVStream* is = input_fc->streams[i];
144                 AVStream* os = avformat_new_stream (output_fc, is->codec->codec);
145                 if (avcodec_parameters_copy (os->codecpar, is->codecpar) < 0) {
146                         cerr << "Could not set up output stream.\n";
147                         exit (EXIT_FAILURE);
148                 }
149
150                 os->avg_frame_rate = is->avg_frame_rate;
151
152                 switch (is->codec->codec_type) {
153                 case AVMEDIA_TYPE_VIDEO:
154                         os->time_base = is->time_base;
155                         os->r_frame_rate = is->r_frame_rate;
156                         os->sample_aspect_ratio = is->sample_aspect_ratio;
157                         os->codec->time_base = is->codec->time_base;
158                         os->codec->framerate = is->codec->framerate;
159                         os->codec->pix_fmt = is->codec->pix_fmt;
160                         break;
161                 case AVMEDIA_TYPE_AUDIO:
162                         os->codec->sample_fmt = is->codec->sample_fmt;
163                         os->codec->bits_per_raw_sample = is->codec->bits_per_raw_sample;
164                         os->codec->sample_rate = is->codec->sample_rate;
165                         os->codec->channel_layout = is->codec->channel_layout;
166                         os->codec->channels = is->codec->channels;
167                         if (is->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE) {
168                                 /* XXX: fix incoming 24-bit files labelled lpcm, which apparently isn't allowed */
169                                 os->codecpar->codec_tag = MKTAG('i', 'n', '2', '4');
170                         }
171                         break;
172                 default:
173                         /* XXX */
174                         break;
175                 }
176         }
177
178         if (avio_open2 (&output_fc->pb, output_file.string().c_str(), AVIO_FLAG_WRITE, 0, 0) < 0) {
179                 cerr << "Could not open output file `" << output_file.string() << "'\n";
180                 exit (EXIT_FAILURE);
181         }
182
183         dcp::Key key (AES_CTR_KEY_SIZE);
184         AVDictionary* options = 0;
185         av_dict_set (&options, "encryption_key", key.hex().c_str(), 0);
186         /* XXX: is this OK? */
187         av_dict_set (&options, "encryption_kid", "00000000000000000000000000000000", 0);
188         av_dict_set (&options, "encryption_scheme", "cenc-aes-ctr", 0);
189
190         string id = dcp::make_uuid ();
191         if (av_dict_set(&output_fc->metadata, SWAROOP_ID_TAG, id.c_str(), 0) < 0) {
192                 cerr << "Could not write ID to output.\n";
193                 exit (EXIT_FAILURE);
194         }
195
196         if (avformat_write_header (output_fc, &options) < 0) {
197                 cerr << "Could not write header to output.\n";
198                 exit (EXIT_FAILURE);
199         }
200
201         AVPacket packet;
202         while (av_read_frame(input_fc, &packet) >= 0) {
203                 AVStream* is = input_fc->streams[packet.stream_index];
204                 AVStream* os = output_fc->streams[packet.stream_index];
205                 packet.pts = av_rescale_q_rnd(packet.pts, is->time_base, os->time_base, (AVRounding) (AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
206                 packet.dts = av_rescale_q_rnd(packet.dts, is->time_base, os->time_base, (AVRounding) (AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
207                 packet.duration = av_rescale_q(packet.duration, is->time_base, os->time_base);
208                 packet.pos = -1;
209                 if (av_interleaved_write_frame (output_fc, &packet) < 0) {
210                         cerr << "Could not write frame to output.\n";
211                         exit (EXIT_FAILURE);
212                 }
213         }
214
215         av_write_trailer (output_fc);
216
217         avformat_free_context (input_fc);
218         avformat_free_context (output_fc);
219
220         DecryptedECinemaKDM decrypted_kdm (id, output_file.filename().string(), key, optional<dcp::LocalTime>(), optional<dcp::LocalTime>());
221         EncryptedECinemaKDM encrypted_kdm = decrypted_kdm.encrypt (Config::instance()->decryption_chain()->leaf());
222
223         if (kdm) {
224                 ofstream f(kdm->c_str());
225                 f << encrypted_kdm.as_xml() << "\n";
226         } else {
227                 cout << encrypted_kdm.as_xml() << "\n";
228         }
229 }