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