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