891d832a24c6575a6e4b1130bb149334416e673b
[dcpomatic.git] / src / lib / config.cc
1 /*
2     Copyright (C) 2012-2016 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 #include "config.h"
22 #include "filter.h"
23 #include "ratio.h"
24 #include "types.h"
25 #include "log.h"
26 #include "dcp_content_type.h"
27 #include "cinema_sound_processor.h"
28 #include "colour_conversion.h"
29 #include "cinema.h"
30 #include "util.h"
31 #include "cross.h"
32 #include "raw_convert.h"
33 #include <dcp/colour_matrix.h>
34 #include <dcp/certificate_chain.h>
35 #include <libcxml/cxml.h>
36 #include <glib.h>
37 #include <libxml++/libxml++.h>
38 #include <boost/filesystem.hpp>
39 #include <boost/algorithm/string.hpp>
40 #include <boost/foreach.hpp>
41 #include <boost/thread.hpp>
42 #include <cstdlib>
43 #include <fstream>
44 #include <iostream>
45
46 #include "i18n.h"
47
48 using std::vector;
49 using std::cout;
50 using std::ifstream;
51 using std::string;
52 using std::list;
53 using std::max;
54 using std::remove;
55 using std::exception;
56 using std::cerr;
57 using boost::shared_ptr;
58 using boost::optional;
59 using boost::algorithm::trim;
60
61 Config* Config::_instance = 0;
62
63 /** Construct default configuration */
64 Config::Config ()
65 {
66         set_defaults ();
67 }
68
69 void
70 Config::set_defaults ()
71 {
72         _num_local_encoding_threads = max (2U, boost::thread::hardware_concurrency ());
73         _server_port_base = 6192;
74         _use_any_servers = true;
75         _servers.clear ();
76         _only_servers_encode = false;
77         _tms_protocol = PROTOCOL_SCP;
78         _tms_ip = "";
79         _tms_path = ".";
80         _tms_user = "";
81         _tms_password = "";
82         _cinema_sound_processor = CinemaSoundProcessor::from_id (N_("dolby_cp750"));
83         _allow_any_dcp_frame_rate = false;
84         _language = optional<string> ();
85         _default_still_length = 10;
86         _default_container = Ratio::from_id ("185");
87         _default_dcp_content_type = DCPContentType::from_isdcf_name ("FTR");
88         _default_dcp_audio_channels = 6;
89         _default_j2k_bandwidth = 100000000;
90         _default_audio_delay = 0;
91         _default_interop = false;
92         _mail_server = "";
93         _mail_port = 25;
94         _mail_user = "";
95         _mail_password = "";
96         _kdm_from = "";
97         _kdm_cc.clear ();
98         _kdm_bcc = "";
99         _check_for_updates = false;
100         _check_for_test_updates = false;
101         _maximum_j2k_bandwidth = 250000000;
102         _log_types = LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR;
103         _analyse_ebur128 = true;
104         _automatic_audio_analysis = false;
105 #ifdef DCPOMATIC_WINDOWS
106         _win32_console = false;
107 #endif
108         _cinemas_file = path ("cinemas.xml");
109
110         _allowed_dcp_frame_rates.clear ();
111         _allowed_dcp_frame_rates.push_back (24);
112         _allowed_dcp_frame_rates.push_back (25);
113         _allowed_dcp_frame_rates.push_back (30);
114         _allowed_dcp_frame_rates.push_back (48);
115         _allowed_dcp_frame_rates.push_back (50);
116         _allowed_dcp_frame_rates.push_back (60);
117
118         set_kdm_email_to_default ();
119 }
120
121 void
122 Config::restore_defaults ()
123 {
124         Config::instance()->set_defaults ();
125         Config::instance()->changed ();
126 }
127
128 shared_ptr<dcp::CertificateChain>
129 Config::create_certificate_chain ()
130 {
131         return shared_ptr<dcp::CertificateChain> (
132                 new dcp::CertificateChain (
133                         openssl_path(),
134                         "dcpomatic.com",
135                         "dcpomatic.com",
136                         ".dcpomatic.smpte-430-2.ROOT",
137                         ".dcpomatic.smpte-430-2.INTERMEDIATE",
138                         "CS.dcpomatic.smpte-430-2.LEAF"
139                         )
140                 );
141 }
142
143 void
144 Config::read ()
145 {
146         if (!have_existing ("config.xml")) {
147                 cout << "No existing config.xml; creating chains.\n";
148                 /* Make a new set of signing certificates and key */
149                 _signer_chain = create_certificate_chain ();
150                 /* And similar for decryption of KDMs */
151                 _decryption_chain = create_certificate_chain ();
152                 cout << "Writing config.\n";
153                 write ();
154                 return;
155         }
156
157         cxml::Document f ("Config");
158         f.read_file (path ("config.xml"));
159         optional<string> c;
160
161         optional<int> version = f.optional_number_child<int> ("Version");
162
163         _num_local_encoding_threads = f.number_child<int> ("NumLocalEncodingThreads");
164         _default_directory = f.string_child ("DefaultDirectory");
165
166         boost::optional<int> b = f.optional_number_child<int> ("ServerPort");
167         if (!b) {
168                 b = f.optional_number_child<int> ("ServerPortBase");
169         }
170         _server_port_base = b.get ();
171
172         boost::optional<bool> u = f.optional_bool_child ("UseAnyServers");
173         _use_any_servers = u.get_value_or (true);
174
175         list<cxml::NodePtr> servers = f.node_children ("Server");
176         for (list<cxml::NodePtr>::iterator i = servers.begin(); i != servers.end(); ++i) {
177                 if ((*i)->node_children("HostName").size() == 1) {
178                         _servers.push_back ((*i)->string_child ("HostName"));
179                 } else {
180                         _servers.push_back ((*i)->content ());
181                 }
182         }
183
184         _only_servers_encode = f.optional_bool_child ("OnlyServersEncode").get_value_or (false);
185         _tms_protocol = static_cast<Protocol> (f.optional_number_child<int> ("TMSProtocol").get_value_or (static_cast<int> (PROTOCOL_SCP)));
186         _tms_ip = f.string_child ("TMSIP");
187         _tms_path = f.string_child ("TMSPath");
188         _tms_user = f.string_child ("TMSUser");
189         _tms_password = f.string_child ("TMSPassword");
190
191         c = f.optional_string_child ("SoundProcessor");
192         if (c) {
193                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
194         }
195         c = f.optional_string_child ("CinemaSoundProcessor");
196         if (c) {
197                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
198         }
199
200         _language = f.optional_string_child ("Language");
201
202         c = f.optional_string_child ("DefaultContainer");
203         if (c) {
204                 _default_container = Ratio::from_id (c.get ());
205         }
206
207         c = f.optional_string_child ("DefaultDCPContentType");
208         if (c) {
209                 _default_dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
210         }
211
212         _default_dcp_audio_channels = f.optional_number_child<int>("DefaultDCPAudioChannels").get_value_or (6);
213
214         if (f.optional_string_child ("DCPMetadataIssuer")) {
215                 _dcp_issuer = f.string_child ("DCPMetadataIssuer");
216         } else if (f.optional_string_child ("DCPIssuer")) {
217                 _dcp_issuer = f.string_child ("DCPIssuer");
218         }
219
220         _dcp_creator = f.optional_string_child ("DCPCreator").get_value_or ("");
221
222         if (version && version.get() >= 2) {
223                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
224         } else {
225                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
226         }
227
228         _default_still_length = f.optional_number_child<int>("DefaultStillLength").get_value_or (10);
229         _default_j2k_bandwidth = f.optional_number_child<int>("DefaultJ2KBandwidth").get_value_or (200000000);
230         _default_audio_delay = f.optional_number_child<int>("DefaultAudioDelay").get_value_or (0);
231         _default_interop = f.optional_bool_child("DefaultInterop").get_value_or (false);
232
233         /* Load any cinemas from config.xml */
234         read_cinemas (f);
235
236         _mail_server = f.string_child ("MailServer");
237         _mail_port = f.optional_number_child<int> ("MailPort").get_value_or (25);
238         _mail_user = f.optional_string_child("MailUser").get_value_or ("");
239         _mail_password = f.optional_string_child("MailPassword").get_value_or ("");
240         _kdm_subject = f.optional_string_child ("KDMSubject").get_value_or (_("KDM delivery: $CPL_NAME"));
241         _kdm_from = f.string_child ("KDMFrom");
242         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("KDMCC")) {
243                 if (!i->content().empty()) {
244                         _kdm_cc.push_back (i->content ());
245                 }
246         }
247         _kdm_bcc = f.optional_string_child ("KDMBCC").get_value_or ("");
248         _kdm_email = f.string_child ("KDMEmail");
249
250         _check_for_updates = f.optional_bool_child("CheckForUpdates").get_value_or (false);
251         _check_for_test_updates = f.optional_bool_child("CheckForTestUpdates").get_value_or (false);
252
253         _maximum_j2k_bandwidth = f.optional_number_child<int> ("MaximumJ2KBandwidth").get_value_or (250000000);
254         _allow_any_dcp_frame_rate = f.optional_bool_child ("AllowAnyDCPFrameRate").get_value_or (false);
255
256         _log_types = f.optional_number_child<int> ("LogTypes").get_value_or (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR);
257         _analyse_ebur128 = f.optional_bool_child("AnalyseEBUR128").get_value_or (true);
258         _automatic_audio_analysis = f.optional_bool_child ("AutomaticAudioAnalysis").get_value_or (false);
259 #ifdef DCPOMATIC_WINDOWS
260         _win32_console = f.optional_bool_child ("Win32Console").get_value_or (false);
261 #endif
262
263         list<cxml::NodePtr> his = f.node_children ("History");
264         for (list<cxml::NodePtr>::const_iterator i = his.begin(); i != his.end(); ++i) {
265                 _history.push_back ((*i)->content ());
266         }
267
268         cxml::NodePtr signer = f.optional_node_child ("Signer");
269         if (signer) {
270                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
271                 /* Read the signing certificates and private key in from the config file */
272                 BOOST_FOREACH (cxml::NodePtr i, signer->node_children ("Certificate")) {
273                         c->add (dcp::Certificate (i->content ()));
274                 }
275                 c->set_key (signer->string_child ("PrivateKey"));
276                 _signer_chain = c;
277         } else {
278                 /* Make a new set of signing certificates and key */
279                 _signer_chain = create_certificate_chain ();
280         }
281
282         cxml::NodePtr decryption = f.optional_node_child ("Decryption");
283         if (decryption) {
284                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
285                 BOOST_FOREACH (cxml::NodePtr i, decryption->node_children ("Certificate")) {
286                         c->add (dcp::Certificate (i->content ()));
287                 }
288                 c->set_key (decryption->string_child ("PrivateKey"));
289                 _decryption_chain = c;
290         } else {
291                 _decryption_chain = create_certificate_chain ();
292         }
293
294         list<cxml::NodePtr> dkdm = f.node_children ("DKDM");
295         BOOST_FOREACH (cxml::NodePtr i, f.node_children ("DKDM")) {
296                 _dkdms.push_back (dcp::EncryptedKDM (i->content ()));
297         }
298
299         _cinemas_file = f.optional_string_child("CinemasFile").get_value_or (path ("cinemas.xml").string ());
300
301         /* Replace any cinemas from config.xml with those from the configured file */
302         if (boost::filesystem::exists (_cinemas_file)) {
303                 cxml::Document f ("Cinemas");
304                 f.read_file (_cinemas_file);
305                 read_cinemas (f);
306         }
307 }
308
309 /** @return Filename to write configuration to */
310 boost::filesystem::path
311 Config::path (string file, bool create_directories)
312 {
313         boost::filesystem::path p;
314 #ifdef DCPOMATIC_OSX
315         p /= g_get_home_dir ();
316         p /= "Library";
317         p /= "Preferences";
318         p /= "com.dcpomatic";
319         p /= "2";
320 #else
321         p /= g_get_user_config_dir ();
322         p /= "dcpomatic2";
323 #endif
324         boost::system::error_code ec;
325         if (create_directories) {
326                 boost::filesystem::create_directories (p, ec);
327         }
328         p /= file;
329         return p;
330 }
331
332 /** @return Singleton instance */
333 Config *
334 Config::instance ()
335 {
336         if (_instance == 0) {
337                 _instance = new Config;
338                 try {
339                         _instance->read ();
340                 } catch (exception& e) {
341                         /* configuration load failed; never mind, just
342                            stick with the default.
343                         */
344                         cerr << "dcpomatic: warning: configuration did not load (" << e.what() << "); using defaults\n";
345                 } catch (...) {
346                         cerr << "dcpomatic: warning: configuration did not load; using defaults\n";
347                 }
348         }
349
350         return _instance;
351 }
352
353 /** Write our configuration to disk */
354 void
355 Config::write () const
356 {
357         write_config_xml ();
358         write_cinemas_xml ();
359 }
360
361 void
362 Config::write_config_xml () const
363 {
364         xmlpp::Document doc;
365         xmlpp::Element* root = doc.create_root_node ("Config");
366
367         root->add_child("Version")->add_child_text ("2");
368         root->add_child("NumLocalEncodingThreads")->add_child_text (raw_convert<string> (_num_local_encoding_threads));
369         root->add_child("DefaultDirectory")->add_child_text (_default_directory.string ());
370         root->add_child("ServerPortBase")->add_child_text (raw_convert<string> (_server_port_base));
371         root->add_child("UseAnyServers")->add_child_text (_use_any_servers ? "1" : "0");
372
373         for (vector<string>::const_iterator i = _servers.begin(); i != _servers.end(); ++i) {
374                 root->add_child("Server")->add_child_text (*i);
375         }
376
377         root->add_child("OnlyServersEncode")->add_child_text (_only_servers_encode ? "1" : "0");
378         root->add_child("TMSProtocol")->add_child_text (raw_convert<string> (_tms_protocol));
379         root->add_child("TMSIP")->add_child_text (_tms_ip);
380         root->add_child("TMSPath")->add_child_text (_tms_path);
381         root->add_child("TMSUser")->add_child_text (_tms_user);
382         root->add_child("TMSPassword")->add_child_text (_tms_password);
383         if (_cinema_sound_processor) {
384                 root->add_child("CinemaSoundProcessor")->add_child_text (_cinema_sound_processor->id ());
385         }
386         if (_language) {
387                 root->add_child("Language")->add_child_text (_language.get());
388         }
389         if (_default_container) {
390                 root->add_child("DefaultContainer")->add_child_text (_default_container->id ());
391         }
392         if (_default_dcp_content_type) {
393                 root->add_child("DefaultDCPContentType")->add_child_text (_default_dcp_content_type->isdcf_name ());
394         }
395         root->add_child("DefaultDCPAudioChannels")->add_child_text (raw_convert<string> (_default_dcp_audio_channels));
396         root->add_child("DCPIssuer")->add_child_text (_dcp_issuer);
397         root->add_child("DCPCreator")->add_child_text (_dcp_creator);
398
399         _default_isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
400
401         root->add_child("DefaultStillLength")->add_child_text (raw_convert<string> (_default_still_length));
402         root->add_child("DefaultJ2KBandwidth")->add_child_text (raw_convert<string> (_default_j2k_bandwidth));
403         root->add_child("DefaultAudioDelay")->add_child_text (raw_convert<string> (_default_audio_delay));
404         root->add_child("DefaultInterop")->add_child_text (_default_interop ? "1" : "0");
405         root->add_child("MailServer")->add_child_text (_mail_server);
406         root->add_child("MailPort")->add_child_text (raw_convert<string> (_mail_port));
407         root->add_child("MailUser")->add_child_text (_mail_user);
408         root->add_child("MailPassword")->add_child_text (_mail_password);
409         root->add_child("KDMSubject")->add_child_text (_kdm_subject);
410         root->add_child("KDMFrom")->add_child_text (_kdm_from);
411         BOOST_FOREACH (string i, _kdm_cc) {
412                 root->add_child("KDMCC")->add_child_text (i);
413         }
414         root->add_child("KDMBCC")->add_child_text (_kdm_bcc);
415         root->add_child("KDMEmail")->add_child_text (_kdm_email);
416
417         root->add_child("CheckForUpdates")->add_child_text (_check_for_updates ? "1" : "0");
418         root->add_child("CheckForTestUpdates")->add_child_text (_check_for_test_updates ? "1" : "0");
419
420         root->add_child("MaximumJ2KBandwidth")->add_child_text (raw_convert<string> (_maximum_j2k_bandwidth));
421         root->add_child("AllowAnyDCPFrameRate")->add_child_text (_allow_any_dcp_frame_rate ? "1" : "0");
422         root->add_child("LogTypes")->add_child_text (raw_convert<string> (_log_types));
423         root->add_child("AnalyseEBUR128")->add_child_text (_analyse_ebur128 ? "1" : "0");
424         root->add_child("AutomaticAudioAnalysis")->add_child_text (_automatic_audio_analysis ? "1" : "0");
425 #ifdef DCPOMATIC_WINDOWS
426         root->add_child("Win32Console")->add_child_text (_win32_console ? "1" : "0");
427 #endif
428
429         xmlpp::Element* signer = root->add_child ("Signer");
430         DCPOMATIC_ASSERT (_signer_chain);
431         BOOST_FOREACH (dcp::Certificate const & i, _signer_chain->root_to_leaf ()) {
432                 signer->add_child("Certificate")->add_child_text (i.certificate (true));
433         }
434         signer->add_child("PrivateKey")->add_child_text (_signer_chain->key().get ());
435
436         xmlpp::Element* decryption = root->add_child ("Decryption");
437         DCPOMATIC_ASSERT (_decryption_chain);
438         BOOST_FOREACH (dcp::Certificate const & i, _decryption_chain->root_to_leaf ()) {
439                 decryption->add_child("Certificate")->add_child_text (i.certificate (true));
440         }
441         decryption->add_child("PrivateKey")->add_child_text (_decryption_chain->key().get ());
442
443         for (vector<boost::filesystem::path>::const_iterator i = _history.begin(); i != _history.end(); ++i) {
444                 root->add_child("History")->add_child_text (i->string ());
445         }
446
447         BOOST_FOREACH (dcp::EncryptedKDM i, _dkdms) {
448                 root->add_child("DKDM")->add_child_text (i.as_xml ());
449         }
450
451         root->add_child("CinemasFile")->add_child_text (_cinemas_file.string());
452
453         try {
454                 doc.write_to_file_formatted (path("config.xml").string ());
455         } catch (xmlpp::exception& e) {
456                 string s = e.what ();
457                 trim (s);
458                 throw FileError (s, path("config.xml"));
459         }
460 }
461
462 void
463 Config::write_cinemas_xml () const
464 {
465         xmlpp::Document doc;
466         xmlpp::Element* root = doc.create_root_node ("Cinemas");
467         root->add_child("Version")->add_child_text ("1");
468
469         for (list<shared_ptr<Cinema> >::const_iterator i = _cinemas.begin(); i != _cinemas.end(); ++i) {
470                 (*i)->as_xml (root->add_child ("Cinema"));
471         }
472
473         try {
474                 doc.write_to_file_formatted (_cinemas_file.string ());
475         } catch (xmlpp::exception& e) {
476                 string s = e.what ();
477                 trim (s);
478                 throw FileError (s, _cinemas_file);
479         }
480 }
481
482 boost::filesystem::path
483 Config::default_directory_or (boost::filesystem::path a) const
484 {
485         if (_default_directory.empty()) {
486                 return a;
487         }
488
489         boost::system::error_code ec;
490         bool const e = boost::filesystem::exists (_default_directory, ec);
491         if (ec || !e) {
492                 return a;
493         }
494
495         return _default_directory;
496 }
497
498 void
499 Config::drop ()
500 {
501         delete _instance;
502         _instance = 0;
503 }
504
505 void
506 Config::changed (Property what)
507 {
508         Changed (what);
509 }
510
511 void
512 Config::set_kdm_email_to_default ()
513 {
514         _kdm_subject = _("KDM delivery: $CPL_NAME");
515
516         _kdm_email = _(
517                 "Dear Projectionist\n\n"
518                 "Please find attached KDMs for $CPL_NAME.\n\n"
519                 "Cinema: $CINEMA_NAME\n"
520                 "Screen(s): $SCREENS\n\n"
521                 "The KDMs are valid from $START_TIME until $END_TIME.\n\n"
522                 "Best regards,\nDCP-o-matic"
523                 );
524 }
525
526 void
527 Config::reset_kdm_email ()
528 {
529         set_kdm_email_to_default ();
530         changed ();
531 }
532
533 void
534 Config::add_to_history (boost::filesystem::path p)
535 {
536         /* Remove existing instances of this path in the history */
537         _history.erase (remove (_history.begin(), _history.end(), p), _history.end ());
538
539         _history.insert (_history.begin (), p);
540         if (_history.size() > HISTORY_SIZE) {
541                 _history.pop_back ();
542         }
543
544         changed ();
545 }
546
547 bool
548 Config::have_existing (string file)
549 {
550         return boost::filesystem::exists (path (file, false));
551 }
552
553 void
554 Config::read_cinemas (cxml::Document const & f)
555 {
556         _cinemas.clear ();
557         list<cxml::NodePtr> cin = f.node_children ("Cinema");
558         for (list<cxml::NodePtr>::iterator i = cin.begin(); i != cin.end(); ++i) {
559                 /* Slightly grotty two-part construction of Cinema here so that we can use
560                    shared_from_this.
561                 */
562                 shared_ptr<Cinema> cinema (new Cinema (*i));
563                 cinema->read_screens (*i);
564                 _cinemas.push_back (cinema);
565         }
566 }
567
568 void
569 Config::set_cinemas_file (boost::filesystem::path file)
570 {
571         _cinemas_file = file;
572
573         if (boost::filesystem::exists (_cinemas_file)) {
574                 /* Existing file; read it in */
575                 cxml::Document f ("Cinemas");
576                 f.read_file (_cinemas_file);
577                 read_cinemas (f);
578         }
579
580         changed (OTHER);
581 }