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