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