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