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