Move some methods out of util.{cc,h}
[dcpomatic.git] / src / tools / dcpomatic_cli.cc
1 /*
2     Copyright (C) 2012-2022 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
22 #include "lib/audio_content.h"
23 #include "lib/config.h"
24 #include "lib/cross.h"
25 #include "lib/dcpomatic_log.h"
26 #include "lib/encode_server_finder.h"
27 #include "lib/ffmpeg_encoder.h"
28 #include "lib/film.h"
29 #include "lib/filter.h"
30 #include "lib/job_manager.h"
31 #include "lib/json_server.h"
32 #include "lib/log.h"
33 #include "lib/make_dcp.h"
34 #include "lib/ratio.h"
35 #include "lib/signal_manager.h"
36 #include "lib/transcode_job.h"
37 #include "lib/util.h"
38 #include "lib/version.h"
39 #include "lib/video_content.h"
40 #include <dcp/version.h>
41 #include <getopt.h>
42 #include <iostream>
43 #include <iomanip>
44
45
46 using std::cerr;
47 using std::cout;
48 using std::dynamic_pointer_cast;
49 using std::list;
50 using std::pair;
51 using std::runtime_error;
52 using std::setw;
53 using std::shared_ptr;
54 using std::string;
55 using std::vector;
56 using boost::optional;
57
58
59 static void
60 help (string n)
61 {
62         cerr << "Syntax: " << n << " [OPTION] [<FILM>]\n"
63              << "  -v, --version                     show DCP-o-matic version\n"
64              << "  -h, --help                        show this help\n"
65              << "  -f, --flags                       show flags passed to C++ compiler on build\n"
66              << "  -n, --no-progress                 do not print progress to stdout\n"
67              << "  -r, --no-remote                   do not use any remote servers\n"
68              << "  -t, --threads                     specify number of local encoding threads (overriding configuration)\n"
69              << "  -j, --json <port>                 run a JSON server on the specified port\n"
70              << "  -k, --keep-going                  keep running even when the job is complete\n"
71              << "  -s, --servers <file>              specify servers to use in a text file\n"
72              << "  -l, --list-servers                just display a list of encoding servers that DCP-o-matic is configured to use; don't encode\n"
73              << "  -d, --dcp-path                    echo DCP's path to stdout on successful completion (implies -n)\n"
74              << "  -c, --config <dir>                directory containing config.xml and cinemas.xml\n"
75              << "      --dump                        just dump a summary of the film's settings; don't encode\n"
76              << "      --no-check                    don't check project's content files for changes before making the DCP\n"
77              << "      --export-format <format>      export project to a file, rather than making a DCP: specify mov or mp4\n"
78              << "      --export-filename <filename>  filename to export to with --export-format\n"
79              << "\n"
80              << "<FILM> is the film directory.\n";
81 }
82
83
84 static void
85 print_dump (shared_ptr<Film> film)
86 {
87         cout << film->dcp_name (true) << "\n"
88              << film->container()->container_nickname() << " at " << ((film->resolution() == Resolution::TWO_K) ? "2K" : "4K") << "\n"
89              << (film->j2k_bandwidth() / 1000000) << "Mbit/s" << "\n"
90              << "Output " << film->video_frame_rate() << "fps " << (film->three_d() ? "3D" : "2D") << " " << (film->audio_frame_rate() / 1000) << "kHz\n"
91              << (film->interop() ? "Inter-Op" : "SMPTE") << " " << (film->encrypted() ? "encrypted" : "unencrypted") << "\n";
92
93         for (auto c: film->content()) {
94                 cout << "\n"
95                      << c->path(0) << "\n"
96                      << "\tat " << c->position().seconds ()
97                      << " length " << c->full_length(film).seconds ()
98                      << " start trim " << c->trim_start().seconds ()
99                      << " end trim " << c->trim_end().seconds () << "\n";
100
101                 if (c->video) {
102                         cout << "\t" << c->video->size().width << "x" << c->video->size().height << "\n"
103                              << "\t" << c->active_video_frame_rate(film) << "fps\n"
104                              << "\tcrop left " << c->video->requested_left_crop()
105                              << " right " << c->video->requested_right_crop()
106                              << " top " << c->video->requested_top_crop()
107                              << " bottom " << c->video->requested_bottom_crop() << "\n";
108                         if (c->video->custom_ratio()) {
109                                 cout << "\tscale to custom ratio " << *c->video->custom_ratio() << ":1\n";
110                         }
111                         if (c->video->colour_conversion()) {
112                                 if (c->video->colour_conversion().get().preset()) {
113                                         cout << "\tcolour conversion "
114                                              << PresetColourConversion::all()[c->video->colour_conversion().get().preset().get()].name
115                                              << "\n";
116                                 } else {
117                                         cout << "\tcustom colour conversion\n";
118                                 }
119                         } else {
120                                 cout << "\tno colour conversion\n";
121                         }
122
123                 }
124
125                 if (c->audio) {
126                         cout << "\t" << c->audio->delay() << " delay\n"
127                              << "\t" << c->audio->gain() << " gain\n";
128                 }
129         }
130 }
131
132
133 static void
134 list_servers ()
135 {
136         while (true) {
137                 int N = 0;
138                 auto servers = EncodeServerFinder::instance()->servers();
139
140                 /* This is a bit fiddly because we want to list configured servers that are down as well
141                    as all those (configured and found by broadcast) that are up.
142                 */
143
144                 if (servers.empty() && Config::instance()->servers().empty()) {
145                         cout << "No encoding servers found or configured.\n";
146                         ++N;
147                 } else {
148                         cout << std::left << setw(24) << "Host" << " Status Threads\n";
149                         ++N;
150
151                         /* Report the state of configured servers */
152                         for (auto i: Config::instance()->servers()) {
153                                 cout << std::left << setw(24) << i << " ";
154
155                                 /* See if this server is on the active list; if so, remove it and note
156                                    the number of threads it is offering.
157                                 */
158                                 optional<int> threads;
159                                 auto j = servers.begin ();
160                                 while (j != servers.end ()) {
161                                         if (i == j->host_name() && j->current_link_version()) {
162                                                 threads = j->threads();
163                                                 auto tmp = j;
164                                                 ++tmp;
165                                                 servers.erase (j);
166                                                 j = tmp;
167                                         } else {
168                                                 ++j;
169                                         }
170                                 }
171                                 if (static_cast<bool>(threads)) {
172                                         cout << "UP     " << threads.get() << "\n";
173                                 } else {
174                                         cout << "DOWN\n";
175                                 }
176                                 ++N;
177                         }
178
179                         /* Now report any left that have been found by broadcast */
180                         for (auto const& i: servers) {
181                                 if (i.current_link_version()) {
182                                         cout << std::left << setw(24) << i.host_name() << " UP     " << i.threads() << "\n";
183                                 } else {
184                                         cout << std::left << setw(24) << i.host_name() << " bad version\n";
185                                 }
186                                 ++N;
187                         }
188                 }
189
190                 dcpomatic_sleep_seconds (1);
191
192                 for (int i = 0; i < N; ++i) {
193                         cout << "\033[1A\033[2K";
194                 }
195         }
196 }
197
198
199 bool
200 show_jobs_on_console (bool progress)
201 {
202         bool first = true;
203         bool error = false;
204         while (true) {
205
206                 dcpomatic_sleep_seconds (5);
207
208                 auto jobs = JobManager::instance()->get();
209
210                 if (!first && progress) {
211                         for (size_t i = 0; i < jobs.size(); ++i) {
212                                 cout << "\033[1A\033[2K";
213                         }
214                         cout.flush ();
215                 }
216
217                 first = false;
218
219                 for (auto i: jobs) {
220                         if (progress) {
221                                 cout << i->name();
222                                 if (!i->sub_name().empty()) {
223                                         cout << "; " << i->sub_name();
224                                 }
225                                 cout << ": ";
226
227                                 if (i->progress ()) {
228                                         cout << i->status() << "                            \n";
229                                 } else {
230                                         cout << ": Running           \n";
231                                 }
232                         }
233
234                         if (!progress && i->finished_in_error()) {
235                                 /* We won't see this error if we haven't been showing progress,
236                                    so show it now.
237                                 */
238                                 cout << i->status() << "\n";
239                         }
240
241                         if (i->finished_in_error()) {
242                                 error = true;
243                         }
244                 }
245
246                 if (!JobManager::instance()->work_to_do()) {
247                         break;
248                 }
249         }
250
251         return error;
252 }
253
254
255 int
256 main (int argc, char* argv[])
257 {
258         boost::filesystem::path film_dir;
259         bool progress = true;
260         bool no_remote = false;
261         optional<int> threads;
262         optional<int> json_port;
263         bool keep_going = false;
264         bool dump = false;
265         optional<boost::filesystem::path> servers;
266         bool list_servers_ = false;
267         bool dcp_path = false;
268         optional<boost::filesystem::path> config;
269         bool check = true;
270         optional<string> export_format;
271         optional<boost::filesystem::path> export_filename;
272
273         int option_index = 0;
274         while (true) {
275                 static struct option long_options[] = {
276                         { "version", no_argument, 0, 'v'},
277                         { "help", no_argument, 0, 'h'},
278                         { "flags", no_argument, 0, 'f'},
279                         { "no-progress", no_argument, 0, 'n'},
280                         { "no-remote", no_argument, 0, 'r'},
281                         { "threads", required_argument, 0, 't'},
282                         { "json", required_argument, 0, 'j'},
283                         { "keep-going", no_argument, 0, 'k' },
284                         { "servers", required_argument, 0, 's' },
285                         { "list-servers", no_argument, 0, 'l' },
286                         { "dcp-path", no_argument, 0, 'd' },
287                         { "config", required_argument, 0, 'c' },
288                         /* Just using A, B, C ... from here on */
289                         { "dump", no_argument, 0, 'A' },
290                         { "no-check", no_argument, 0, 'B' },
291                         { "export-format", required_argument, 0, 'C' },
292                         { "export-filename", required_argument, 0, 'D' },
293                         { 0, 0, 0, 0 }
294                 };
295
296                 int c = getopt_long (argc, argv, "vhfnrt:j:kAs:ldc:BC:D:", long_options, &option_index);
297
298                 if (c == -1) {
299                         break;
300                 }
301
302                 switch (c) {
303                 case 'v':
304                         cout << "dcpomatic version " << dcpomatic_version << " " << dcpomatic_git_commit << "\n";
305                         exit (EXIT_SUCCESS);
306                 case 'h':
307                         help (argv[0]);
308                         exit (EXIT_SUCCESS);
309                 case 'f':
310                         cout << dcpomatic_cxx_flags << "\n";
311                         exit (EXIT_SUCCESS);
312                 case 'n':
313                         progress = false;
314                         break;
315                 case 'r':
316                         no_remote = true;
317                         break;
318                 case 't':
319                         threads = atoi (optarg);
320                         break;
321                 case 'j':
322                         json_port = atoi (optarg);
323                         break;
324                 case 'k':
325                         keep_going = true;
326                         break;
327                 case 'A':
328                         dump = true;
329                         break;
330                 case 's':
331                         servers = optarg;
332                         break;
333                 case 'l':
334                         list_servers_ = true;
335                         break;
336                 case 'd':
337                         dcp_path = true;
338                         progress = false;
339                         break;
340                 case 'c':
341                         config = optarg;
342                         break;
343                 case 'B':
344                         check = false;
345                         break;
346                 case 'C':
347                         export_format = optarg;
348                         break;
349                 case 'D':
350                         export_filename = optarg;
351                         break;
352                 }
353         }
354
355         if (config) {
356                 State::override_path = *config;
357         }
358
359         if (servers) {
360                 dcp::File f(*servers, "r");
361                 if (!f) {
362                         cerr << "Could not open servers list file " << *servers << "\n";
363                         exit (EXIT_FAILURE);
364                 }
365                 vector<string> servers;
366                 while (!f.eof()) {
367                         char buffer[128];
368                         if (fscanf(f.get(), "%s.127", buffer) == 1) {
369                                 servers.push_back (buffer);
370                         }
371                 }
372                 Config::instance()->set_servers (servers);
373         }
374
375         if (list_servers_) {
376                 list_servers ();
377                 exit (EXIT_SUCCESS);
378         }
379
380         if (optind >= argc) {
381                 help (argv[0]);
382                 exit (EXIT_FAILURE);
383         }
384
385         if (export_format && !export_filename) {
386                 cerr << "Argument --export-filename is required with --export-format\n";
387                 exit (EXIT_FAILURE);
388         }
389
390         if (!export_format && export_filename) {
391                 cerr << "Argument --export-format is required with --export-filename\n";
392                 exit (EXIT_FAILURE);
393         }
394
395         if (export_format && *export_format != "mp4" && *export_format != "mov") {
396                 cerr << "Unrecognised export format: must be mp4 or mov\n";
397                 exit (EXIT_FAILURE);
398         }
399
400         film_dir = argv[optind];
401
402         dcpomatic_setup_path_encoding ();
403         dcpomatic_setup ();
404         signal_manager = new SignalManager ();
405
406         if (no_remote || export_format) {
407                 EncodeServerFinder::instance()->stop ();
408         }
409
410         if (json_port) {
411                 new JSONServer (json_port.get ());
412         }
413
414         if (threads) {
415                 Config::instance()->set_master_encoding_threads (threads.get ());
416         }
417
418         shared_ptr<Film> film;
419         try {
420                 film.reset (new Film (film_dir));
421                 film->read_metadata ();
422         } catch (std::exception& e) {
423                 cerr << argv[0] << ": error reading film `" << film_dir.string() << "' (" << e.what() << ")\n";
424                 exit (EXIT_FAILURE);
425         }
426
427         if (dump) {
428                 print_dump (film);
429                 exit (EXIT_SUCCESS);
430         }
431
432         dcpomatic_log = film->log ();
433
434         for (auto i: film->content()) {
435                 auto paths = i->paths();
436                 for (auto j: paths) {
437                         if (!boost::filesystem::exists(j)) {
438                                 cerr << argv[0] << ": content file " << j << " not found.\n";
439                                 exit (EXIT_FAILURE);
440                         }
441                 }
442         }
443
444         if (progress) {
445                 if (export_format) {
446                         cout << "\nExporting " << film->name() << "\n";
447                 } else {
448                         cout << "\nMaking DCP for " << film->name() << "\n";
449                 }
450         }
451
452         TranscodeJob::ChangedBehaviour const behaviour = check ? TranscodeJob::ChangedBehaviour::STOP : TranscodeJob::ChangedBehaviour::IGNORE;
453
454         if (export_format) {
455                 auto job = std::make_shared<TranscodeJob>(film, behaviour);
456                 job->set_encoder (
457                         std::make_shared<FFmpegEncoder> (
458                                 film, job, *export_filename, *export_format == "mp4" ? ExportFormat::H264_AAC : ExportFormat::PRORES_HQ, false, false, false, 23
459                                 )
460                         );
461                 JobManager::instance()->add (job);
462         } else {
463                 try {
464                         make_dcp (film, behaviour);
465                 } catch (runtime_error& e) {
466                         std::cerr << "Could not make DCP: " << e.what() << "\n";
467                         exit(EXIT_FAILURE);
468                 }
469         }
470
471         bool const error = show_jobs_on_console (progress);
472
473         if (keep_going) {
474                 while (true) {
475                         dcpomatic_sleep_seconds (3600);
476                 }
477         }
478
479         /* This is just to stop valgrind reporting leaks due to JobManager
480            indirectly holding onto codecs.
481         */
482         JobManager::drop ();
483
484         EncodeServerFinder::drop ();
485
486         if (dcp_path && !error) {
487                 cout << film->dir (film->dcp_name (false)).string() << "\n";
488         }
489
490         return error ? EXIT_FAILURE : EXIT_SUCCESS;
491 }