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