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