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