43a3e63c924d170517267c0b8f371b6aa6798235
[dcpomatic.git] / src / lib / config.cc
1 /*
2     Copyright (C) 2012-2015 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 "server.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 <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 = "";
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         _automatic_audio_analysis = false;
102 #ifdef DCPOMATIC_WINDOWS
103         _win32_console = false;
104 #endif
105
106         _allowed_dcp_frame_rates.clear ();
107         _allowed_dcp_frame_rates.push_back (24);
108         _allowed_dcp_frame_rates.push_back (25);
109         _allowed_dcp_frame_rates.push_back (30);
110         _allowed_dcp_frame_rates.push_back (48);
111         _allowed_dcp_frame_rates.push_back (50);
112         _allowed_dcp_frame_rates.push_back (60);
113
114         set_kdm_email_to_default ();
115 }
116
117 void
118 Config::restore_defaults ()
119 {
120         Config::instance()->set_defaults ();
121         Config::instance()->changed ();
122 }
123
124 shared_ptr<dcp::CertificateChain>
125 Config::create_certificate_chain ()
126 {
127         return shared_ptr<dcp::CertificateChain> (
128                 new dcp::CertificateChain (
129                         openssl_path(),
130                         "dcpomatic.com",
131                         "dcpomatic.com",
132                         ".dcpomatic.smpte-430-2.ROOT",
133                         ".dcpomatic.smpte-430-2.INTERMEDIATE",
134                         "CS.dcpomatic.smpte-430-2.LEAF"
135                         )
136                 );
137 }
138
139 void
140 Config::read ()
141 {
142         if (!have_existing ()) {
143                 /* Make a new set of signing certificates and key */
144                 _signer_chain = create_certificate_chain ();
145                 /* And similar for decryption of KDMs */
146                 _decryption_chain = create_certificate_chain ();
147                 write ();
148                 return;
149         }
150
151         cxml::Document f ("Config");
152         f.read_file (file ());
153         optional<string> c;
154
155         optional<int> version = f.optional_number_child<int> ("Version");
156
157         _num_local_encoding_threads = f.number_child<int> ("NumLocalEncodingThreads");
158         _default_directory = f.string_child ("DefaultDirectory");
159
160         boost::optional<int> b = f.optional_number_child<int> ("ServerPort");
161         if (!b) {
162                 b = f.optional_number_child<int> ("ServerPortBase");
163         }
164         _server_port_base = b.get ();
165
166         boost::optional<bool> u = f.optional_bool_child ("UseAnyServers");
167         _use_any_servers = u.get_value_or (true);
168
169         list<cxml::NodePtr> servers = f.node_children ("Server");
170         for (list<cxml::NodePtr>::iterator i = servers.begin(); i != servers.end(); ++i) {
171                 if ((*i)->node_children("HostName").size() == 1) {
172                         _servers.push_back ((*i)->string_child ("HostName"));
173                 } else {
174                         _servers.push_back ((*i)->content ());
175                 }
176         }
177
178         _only_servers_encode = f.optional_bool_child ("OnlyServersEncode").get_value_or (false);
179         _tms_protocol = static_cast<Protocol> (f.optional_number_child<int> ("TMSProtocol").get_value_or (static_cast<int> (PROTOCOL_SCP)));
180         _tms_ip = f.string_child ("TMSIP");
181         _tms_path = f.string_child ("TMSPath");
182         _tms_user = f.string_child ("TMSUser");
183         _tms_password = f.string_child ("TMSPassword");
184
185         c = f.optional_string_child ("SoundProcessor");
186         if (c) {
187                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
188         }
189         c = f.optional_string_child ("CinemaSoundProcessor");
190         if (c) {
191                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
192         }
193
194         _language = f.optional_string_child ("Language");
195
196         c = f.optional_string_child ("DefaultContainer");
197         if (c) {
198                 _default_container = Ratio::from_id (c.get ());
199         }
200
201         c = f.optional_string_child ("DefaultDCPContentType");
202         if (c) {
203                 _default_dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
204         }
205
206         if (f.optional_string_child ("DCPMetadataIssuer")) {
207                 _dcp_issuer = f.string_child ("DCPMetadataIssuer");
208         } else if (f.optional_string_child ("DCPIssuer")) {
209                 _dcp_issuer = f.string_child ("DCPIssuer");
210         }
211
212         _dcp_creator = f.optional_string_child ("DCPCreator").get_value_or ("");
213
214         if (version && version.get() >= 2) {
215                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
216         } else {
217                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
218         }
219
220         _default_still_length = f.optional_number_child<int>("DefaultStillLength").get_value_or (10);
221         _default_j2k_bandwidth = f.optional_number_child<int>("DefaultJ2KBandwidth").get_value_or (200000000);
222         _default_audio_delay = f.optional_number_child<int>("DefaultAudioDelay").get_value_or (0);
223         _default_interop = f.optional_bool_child("DefaultInterop").get_value_or (false);
224
225         list<cxml::NodePtr> cin = f.node_children ("Cinema");
226         for (list<cxml::NodePtr>::iterator i = cin.begin(); i != cin.end(); ++i) {
227                 /* Slightly grotty two-part construction of Cinema here so that we can use
228                    shared_from_this.
229                 */
230                 shared_ptr<Cinema> cinema (new Cinema (*i));
231                 cinema->read_screens (*i);
232                 _cinemas.push_back (cinema);
233         }
234
235         _mail_server = f.string_child ("MailServer");
236         _mail_port = f.optional_number_child<int> ("MailPort").get_value_or (25);
237         _mail_user = f.optional_string_child("MailUser").get_value_or ("");
238         _mail_password = f.optional_string_child("MailPassword").get_value_or ("");
239         _kdm_subject = f.optional_string_child ("KDMSubject").get_value_or (_("KDM delivery: $CPL_NAME"));
240         _kdm_from = f.string_child ("KDMFrom");
241         _kdm_cc = f.optional_string_child ("KDMCC").get_value_or ("");
242         _kdm_bcc = f.optional_string_child ("KDMBCC").get_value_or ("");
243         _kdm_email = f.string_child ("KDMEmail");
244
245         _check_for_updates = f.optional_bool_child("CheckForUpdates").get_value_or (false);
246         _check_for_test_updates = f.optional_bool_child("CheckForTestUpdates").get_value_or (false);
247
248         _maximum_j2k_bandwidth = f.optional_number_child<int> ("MaximumJ2KBandwidth").get_value_or (250000000);
249         _allow_any_dcp_frame_rate = f.optional_bool_child ("AllowAnyDCPFrameRate").get_value_or (false);
250
251         _log_types = f.optional_number_child<int> ("LogTypes").get_value_or (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR);
252         _automatic_audio_analysis = f.optional_bool_child ("AutomaticAudioAnalysis").get_value_or (false);
253 #ifdef DCPOMATIC_WINDOWS
254         _win32_console = f.optional_bool_child ("Win32Console").get_value_or (false);
255 #endif
256
257         list<cxml::NodePtr> his = f.node_children ("History");
258         for (list<cxml::NodePtr>::const_iterator i = his.begin(); i != his.end(); ++i) {
259                 _history.push_back ((*i)->content ());
260         }
261
262         cxml::NodePtr signer = f.optional_node_child ("Signer");
263         if (signer) {
264                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
265                 /* Read the signing certificates and private key in from the config file */
266                 BOOST_FOREACH (cxml::NodePtr i, signer->node_children ("Certificate")) {
267                         c->add (dcp::Certificate (i->content ()));
268                 }
269                 c->set_key (signer->string_child ("PrivateKey"));
270                 _signer_chain = c;
271         } else {
272                 /* Make a new set of signing certificates and key */
273                 _signer_chain = create_certificate_chain ();
274         }
275
276         cxml::NodePtr decryption = f.optional_node_child ("Decryption");
277         if (decryption) {
278                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
279                 BOOST_FOREACH (cxml::NodePtr i, decryption->node_children ("Certificate")) {
280                         c->add (dcp::Certificate (i->content ()));
281                 }
282                 c->set_key (decryption->string_child ("PrivateKey"));
283                 _decryption_chain = c;
284         } else {
285                 _decryption_chain = create_certificate_chain ();
286         }
287 }
288
289 /** @return Filename to write configuration to */
290 boost::filesystem::path
291 Config::file (bool create_directories)
292 {
293         boost::filesystem::path p;
294 #ifdef DCPOMATIC_OSX
295         p /= g_get_home_dir ();
296         p /= "Library";
297         p /= "Preferences";
298         p /= "com.dcpomatic";
299         p /= "2";
300 #else
301         p /= g_get_user_config_dir ();
302         p /= "dcpomatic2";
303 #endif
304         boost::system::error_code ec;
305         if (create_directories) {
306                 boost::filesystem::create_directories (p, ec);
307         }
308         p /= "config.xml";
309         return p;
310 }
311
312 /** @return Singleton instance */
313 Config *
314 Config::instance ()
315 {
316         if (_instance == 0) {
317                 _instance = new Config;
318                 try {
319                         _instance->read ();
320                 } catch (exception& e) {
321                         /* configuration load failed; never mind, just
322                            stick with the default.
323                         */
324                         cerr << "dcpomatic: warning: configuration did not load (" << e.what() << "); using defaults\n";
325                 } catch (...) {
326                         cerr << "dcpomatic: warning: configuration did not load; using defaults\n";
327                 }
328         }
329
330         return _instance;
331 }
332
333 /** Write our configuration to disk */
334 void
335 Config::write () const
336 {
337         xmlpp::Document doc;
338         xmlpp::Element* root = doc.create_root_node ("Config");
339
340         root->add_child("Version")->add_child_text ("2");
341         root->add_child("NumLocalEncodingThreads")->add_child_text (raw_convert<string> (_num_local_encoding_threads));
342         root->add_child("DefaultDirectory")->add_child_text (_default_directory.string ());
343         root->add_child("ServerPortBase")->add_child_text (raw_convert<string> (_server_port_base));
344         root->add_child("UseAnyServers")->add_child_text (_use_any_servers ? "1" : "0");
345
346         for (vector<string>::const_iterator i = _servers.begin(); i != _servers.end(); ++i) {
347                 root->add_child("Server")->add_child_text (*i);
348         }
349
350         root->add_child("OnlyServersEncode")->add_child_text (_only_servers_encode ? "1" : "0");
351         root->add_child("TMSProtocol")->add_child_text (raw_convert<string> (_tms_protocol));
352         root->add_child("TMSIP")->add_child_text (_tms_ip);
353         root->add_child("TMSPath")->add_child_text (_tms_path);
354         root->add_child("TMSUser")->add_child_text (_tms_user);
355         root->add_child("TMSPassword")->add_child_text (_tms_password);
356         if (_cinema_sound_processor) {
357                 root->add_child("CinemaSoundProcessor")->add_child_text (_cinema_sound_processor->id ());
358         }
359         if (_language) {
360                 root->add_child("Language")->add_child_text (_language.get());
361         }
362         if (_default_container) {
363                 root->add_child("DefaultContainer")->add_child_text (_default_container->id ());
364         }
365         if (_default_dcp_content_type) {
366                 root->add_child("DefaultDCPContentType")->add_child_text (_default_dcp_content_type->isdcf_name ());
367         }
368         root->add_child("DCPIssuer")->add_child_text (_dcp_issuer);
369         root->add_child("DCPCreator")->add_child_text (_dcp_creator);
370
371         _default_isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
372
373         root->add_child("DefaultStillLength")->add_child_text (raw_convert<string> (_default_still_length));
374         root->add_child("DefaultJ2KBandwidth")->add_child_text (raw_convert<string> (_default_j2k_bandwidth));
375         root->add_child("DefaultAudioDelay")->add_child_text (raw_convert<string> (_default_audio_delay));
376         root->add_child("DefaultInterop")->add_child_text (_default_interop ? "1" : "0");
377
378         for (list<shared_ptr<Cinema> >::const_iterator i = _cinemas.begin(); i != _cinemas.end(); ++i) {
379                 (*i)->as_xml (root->add_child ("Cinema"));
380         }
381
382         root->add_child("MailServer")->add_child_text (_mail_server);
383         root->add_child("MailPort")->add_child_text (raw_convert<string> (_mail_port));
384         root->add_child("MailUser")->add_child_text (_mail_user);
385         root->add_child("MailPassword")->add_child_text (_mail_password);
386         root->add_child("KDMSubject")->add_child_text (_kdm_subject);
387         root->add_child("KDMFrom")->add_child_text (_kdm_from);
388         root->add_child("KDMCC")->add_child_text (_kdm_cc);
389         root->add_child("KDMBCC")->add_child_text (_kdm_bcc);
390         root->add_child("KDMEmail")->add_child_text (_kdm_email);
391
392         root->add_child("CheckForUpdates")->add_child_text (_check_for_updates ? "1" : "0");
393         root->add_child("CheckForTestUpdates")->add_child_text (_check_for_test_updates ? "1" : "0");
394
395         root->add_child("MaximumJ2KBandwidth")->add_child_text (raw_convert<string> (_maximum_j2k_bandwidth));
396         root->add_child("AllowAnyDCPFrameRate")->add_child_text (_allow_any_dcp_frame_rate ? "1" : "0");
397         root->add_child("LogTypes")->add_child_text (raw_convert<string> (_log_types));
398         root->add_child("AutomaticAudioAnalysis")->add_child_text (_automatic_audio_analysis ? "1" : "0");
399 #ifdef DCPOMATIC_WINDOWS
400         root->add_child("Win32Console")->add_child_text (_win32_console ? "1" : "0");
401 #endif
402
403         xmlpp::Element* signer = root->add_child ("Signer");
404         BOOST_FOREACH (dcp::Certificate const & i, _signer_chain->root_to_leaf ()) {
405                 signer->add_child("Certificate")->add_child_text (i.certificate (true));
406         }
407         signer->add_child("PrivateKey")->add_child_text (_signer_chain->key().get ());
408
409         xmlpp::Element* decryption = root->add_child ("Decryption");
410         BOOST_FOREACH (dcp::Certificate const & i, _decryption_chain->root_to_leaf ()) {
411                 decryption->add_child("Certificate")->add_child_text (i.certificate (true));
412         }
413         decryption->add_child("PrivateKey")->add_child_text (_decryption_chain->key().get ());
414
415         for (vector<boost::filesystem::path>::const_iterator i = _history.begin(); i != _history.end(); ++i) {
416                 root->add_child("History")->add_child_text (i->string ());
417         }
418
419         try {
420                 doc.write_to_file_formatted (file().string ());
421         } catch (xmlpp::exception& e) {
422                 string s = e.what ();
423                 trim (s);
424                 throw FileError (s, file ());
425         }
426 }
427
428 boost::filesystem::path
429 Config::default_directory_or (boost::filesystem::path a) const
430 {
431         if (_default_directory.empty()) {
432                 return a;
433         }
434
435         boost::system::error_code ec;
436         bool const e = boost::filesystem::exists (_default_directory, ec);
437         if (ec || !e) {
438                 return a;
439         }
440
441         return _default_directory;
442 }
443
444 void
445 Config::drop ()
446 {
447         delete _instance;
448         _instance = 0;
449 }
450
451 void
452 Config::changed (Property what)
453 {
454         Changed (what);
455 }
456
457 void
458 Config::set_kdm_email_to_default ()
459 {
460         _kdm_subject = _("KDM delivery: $CPL_NAME");
461
462         _kdm_email = _(
463                 "Dear Projectionist\n\n"
464                 "Please find attached KDMs for $CPL_NAME.\n\n"
465                 "Cinema: $CINEMA_NAME\n"
466                 "Screen(s): $SCREENS\n\n"
467                 "The KDMs are valid from $START_TIME until $END_TIME.\n\n"
468                 "Best regards,\nDCP-o-matic"
469                 );
470 }
471
472 void
473 Config::reset_kdm_email ()
474 {
475         set_kdm_email_to_default ();
476         changed ();
477 }
478
479 void
480 Config::add_to_history (boost::filesystem::path p)
481 {
482         /* Remove existing instances of this path in the history */
483         _history.erase (remove (_history.begin(), _history.end(), p), _history.end ());
484
485         _history.insert (_history.begin (), p);
486         if (_history.size() > HISTORY_SIZE) {
487                 _history.pop_back ();
488         }
489
490         changed ();
491 }
492
493 bool
494 Config::have_existing ()
495 {
496         return boost::filesystem::exists (file (false));
497 }