Add a new "Add DKDM" dialogue (#1637).
[dcpomatic.git] / src / lib / config.cc
1 /*
2     Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "config.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 "colour_conversion.h"
28 #include "cinema.h"
29 #include "util.h"
30 #include "cross.h"
31 #include "film.h"
32 #include "dkdm_wrapper.h"
33 #include "compose.hpp"
34 #include "crypto.h"
35 #include "dkdm_recipient.h"
36 #include <dcp/raw_convert.h>
37 #include <dcp/name_format.h>
38 #include <dcp/certificate_chain.h>
39 #include <libcxml/cxml.h>
40 #include <glib.h>
41 #include <libxml++/libxml++.h>
42 #include <boost/filesystem.hpp>
43 #include <boost/algorithm/string.hpp>
44 #include <boost/foreach.hpp>
45 #include <boost/thread.hpp>
46 #include <cstdlib>
47 #include <fstream>
48 #include <iostream>
49
50 #include "i18n.h"
51
52 using std::vector;
53 using std::cout;
54 using std::ifstream;
55 using std::string;
56 using std::list;
57 using std::min;
58 using std::max;
59 using std::remove;
60 using std::exception;
61 using std::cerr;
62 using boost::shared_ptr;
63 using boost::optional;
64 using boost::dynamic_pointer_cast;
65 using boost::algorithm::trim;
66 using dcp::raw_convert;
67
68 Config* Config::_instance = 0;
69 int const Config::_current_version = 3;
70 boost::signals2::signal<void ()> Config::FailedToLoad;
71 boost::signals2::signal<void (string)> Config::Warning;
72 boost::signals2::signal<bool (Config::BadReason)> Config::Bad;
73
74 /** Construct default configuration */
75 Config::Config ()
76         /* DKDMs are not considered a thing to reset on set_defaults() */
77         : _dkdms (new DKDMGroup ("root"))
78 {
79         set_defaults ();
80 }
81
82 void
83 Config::set_defaults ()
84 {
85         _master_encoding_threads = max (2U, boost::thread::hardware_concurrency ());
86         _server_encoding_threads = max (2U, boost::thread::hardware_concurrency ());
87         _server_port_base = 6192;
88         _use_any_servers = true;
89         _servers.clear ();
90         _only_servers_encode = false;
91         _tms_protocol = FILE_TRANSFER_PROTOCOL_SCP;
92         _tms_ip = "";
93         _tms_path = ".";
94         _tms_user = "";
95         _tms_password = "";
96         _allow_any_dcp_frame_rate = false;
97         _allow_any_container = false;
98         _show_experimental_audio_processors = false;
99         _language = optional<string> ();
100         _default_still_length = 10;
101         _default_container = Ratio::from_id ("185");
102         _default_scale_to = 0;
103         _default_dcp_content_type = DCPContentType::from_isdcf_name ("FTR");
104         _default_dcp_audio_channels = 6;
105         _default_j2k_bandwidth = 150000000;
106         _default_audio_delay = 0;
107         _default_interop = true;
108         _default_upload_after_make_dcp = false;
109         _mail_server = "";
110         _mail_port = 25;
111         _mail_protocol = EMAIL_PROTOCOL_AUTO;
112         _mail_user = "";
113         _mail_password = "";
114         _kdm_from = "";
115         _kdm_cc.clear ();
116         _kdm_bcc = "";
117         _notification_from = "";
118         _notification_to = "";
119         _notification_cc.clear ();
120         _notification_bcc = "";
121         _check_for_updates = false;
122         _check_for_test_updates = false;
123         _maximum_j2k_bandwidth = 250000000;
124         _log_types = LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR;
125         _analyse_ebur128 = true;
126         _automatic_audio_analysis = false;
127 #ifdef DCPOMATIC_WINDOWS
128         _win32_console = false;
129 #endif
130         _cinemas_file = path ("cinemas.xml");
131         _dkdm_recipients_file = path ("dkdm_recipients.xml");
132         _show_hints_before_make_dcp = true;
133         _confirm_kdm_email = true;
134         _kdm_container_name_format = dcp::NameFormat ("KDM %f %c");
135         _kdm_filename_format = dcp::NameFormat ("KDM %f %c %s");
136         _dkdm_filename_format = dcp::NameFormat ("DKDM %f %c %s");
137         _dcp_metadata_filename_format = dcp::NameFormat ("%t");
138         _dcp_asset_filename_format = dcp::NameFormat ("%t");
139         _jump_to_selected = true;
140         for (int i = 0; i < NAG_COUNT; ++i) {
141                 _nagged[i] = false;
142         }
143         _sound = true;
144         _sound_output = optional<string> ();
145         _last_kdm_write_type = KDM_WRITE_FLAT;
146         _last_dkdm_write_type = DKDM_WRITE_INTERNAL;
147
148         /* I think the scaling factor here should be the ratio of the longest frame
149            encode time to the shortest; if the thread count is T, longest time is L
150            and the shortest time S we could encode L/S frames per thread whilst waiting
151            for the L frame to encode so we might have to store LT/S frames.
152
153            However we don't want to use too much memory, so keep it a bit lower than we'd
154            perhaps like.  A J2K frame is typically about 1Mb so 3 here will mean we could
155            use about 240Mb with 72 encoding threads.
156         */
157         _frames_in_memory_multiplier = 3;
158         _decode_reduction = optional<int>();
159         _default_notify = false;
160         for (int i = 0; i < NOTIFICATION_COUNT; ++i) {
161                 _notification[i] = false;
162         }
163         _barco_username = optional<string>();
164         _barco_password = optional<string>();
165         _christie_username = optional<string>();
166         _christie_password = optional<string>();
167         _gdc_username = optional<string>();
168         _gdc_password = optional<string>();
169         _interface_complexity = INTERFACE_SIMPLE;
170         _player_mode = PLAYER_MODE_WINDOW;
171         _image_display = 0;
172         _video_view_type = VIDEO_VIEW_SIMPLE;
173         _respect_kdm_validity_periods = true;
174         _player_activity_log_file = boost::none;
175         _player_debug_log_file = boost::none;
176         _player_content_directory = boost::none;
177         _player_playlist_directory = boost::none;
178         _player_kdm_directory = boost::none;
179         _audio_mapping = boost::none;
180 #ifdef DCPOMATIC_VARIANT_SWAROOP
181         _player_background_image = boost::none;
182         _kdm_server_url = "http://localhost:8000/{CPL}";
183         _player_watermark_theatre = "";
184         _player_watermark_period = 1;
185         _player_watermark_duration = 50;
186         _player_lock_file = boost::none;
187         _signer_chain_path = "signer";
188         _decryption_chain_path = "decryption";
189 #endif
190
191         _allowed_dcp_frame_rates.clear ();
192         _allowed_dcp_frame_rates.push_back (24);
193         _allowed_dcp_frame_rates.push_back (25);
194         _allowed_dcp_frame_rates.push_back (30);
195         _allowed_dcp_frame_rates.push_back (48);
196         _allowed_dcp_frame_rates.push_back (50);
197         _allowed_dcp_frame_rates.push_back (60);
198
199         set_kdm_email_to_default ();
200         set_notification_email_to_default ();
201         set_cover_sheet_to_default ();
202 }
203
204 void
205 Config::restore_defaults ()
206 {
207         Config::instance()->set_defaults ();
208         Config::instance()->changed ();
209 }
210
211 shared_ptr<dcp::CertificateChain>
212 Config::create_certificate_chain ()
213 {
214         return shared_ptr<dcp::CertificateChain> (
215                 new dcp::CertificateChain (
216                         openssl_path(),
217                         "dcpomatic.com",
218                         "dcpomatic.com",
219                         ".dcpomatic.smpte-430-2.ROOT",
220                         ".dcpomatic.smpte-430-2.INTERMEDIATE",
221                         "CS.dcpomatic.smpte-430-2.LEAF"
222                         )
223                 );
224 }
225
226 void
227 Config::backup ()
228 {
229         /* Make a copy of the configuration */
230         try {
231                 int n = 1;
232                 while (n < 100 && boost::filesystem::exists(path(String::compose("config.xml.%1", n)))) {
233                         ++n;
234                 }
235
236                 boost::filesystem::copy_file(path("config.xml", false), path(String::compose("config.xml.%1", n), false));
237                 boost::filesystem::copy_file(path("cinemas.xml", false), path(String::compose("cinemas.xml.%1", n), false));
238                 boost::filesystem::copy_file(path("dkdm_recipients.xml", false), path(String::compose("dkdm_recipients.xml.%1", n), false));
239         } catch (...) {}
240 }
241
242 void
243 Config::read ()
244 try
245 {
246 #if defined(DCPOMATIC_VARIANT_SWAROOP) && defined(DCPOMATIC_LINUX)
247         if (geteuid() == 0) {
248                 /* Take ownership of the config file if we're root */
249                 chown (config_file().string().c_str(), 0, 0);
250                 chmod (config_file().string().c_str(), 0644);
251         }
252 #endif
253
254         cxml::Document f ("Config");
255         f.read_file (config_file ());
256
257         optional<int> version = f.optional_number_child<int> ("Version");
258         if (version && *version < _current_version) {
259                 /* Back up the old config before we re-write it in a back-incompatible way */
260                 backup ();
261         }
262
263         if (f.optional_number_child<int>("NumLocalEncodingThreads")) {
264                 _master_encoding_threads = _server_encoding_threads = f.optional_number_child<int>("NumLocalEncodingThreads").get();
265         } else {
266                 _master_encoding_threads = f.number_child<int>("MasterEncodingThreads");
267                 _server_encoding_threads = f.number_child<int>("ServerEncodingThreads");
268         }
269
270         _default_directory = f.optional_string_child ("DefaultDirectory");
271         if (_default_directory && _default_directory->empty ()) {
272                 /* We used to store an empty value for this to mean "none set" */
273                 _default_directory = boost::optional<boost::filesystem::path> ();
274         }
275
276         boost::optional<int> b = f.optional_number_child<int> ("ServerPort");
277         if (!b) {
278                 b = f.optional_number_child<int> ("ServerPortBase");
279         }
280         _server_port_base = b.get ();
281
282         boost::optional<bool> u = f.optional_bool_child ("UseAnyServers");
283         _use_any_servers = u.get_value_or (true);
284
285         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("Server")) {
286                 if (i->node_children("HostName").size() == 1) {
287                         _servers.push_back (i->string_child ("HostName"));
288                 } else {
289                         _servers.push_back (i->content ());
290                 }
291         }
292
293         _only_servers_encode = f.optional_bool_child ("OnlyServersEncode").get_value_or (false);
294         _tms_protocol = static_cast<FileTransferProtocol>(f.optional_number_child<int>("TMSProtocol").get_value_or(static_cast<int>(FILE_TRANSFER_PROTOCOL_SCP)));
295         _tms_ip = f.string_child ("TMSIP");
296         _tms_path = f.string_child ("TMSPath");
297         _tms_user = f.string_child ("TMSUser");
298         _tms_password = f.string_child ("TMSPassword");
299
300         _language = f.optional_string_child ("Language");
301
302         optional<string> c = f.optional_string_child ("DefaultContainer");
303         if (c) {
304                 _default_container = Ratio::from_id (c.get ());
305         }
306
307         if (_default_container && !_default_container->used_for_container()) {
308                 Warning (_("Your default container is not valid and has been changed to Flat (1.85:1)"));
309                 _default_container = Ratio::from_id ("185");
310         }
311
312         c = f.optional_string_child ("DefaultScaleTo");
313         if (c) {
314                 _default_scale_to = Ratio::from_id (c.get ());
315         }
316
317         _default_dcp_content_type = DCPContentType::from_isdcf_name(f.optional_string_child("DefaultDCPContentType").get_value_or("FTR"));
318         _default_dcp_audio_channels = f.optional_number_child<int>("DefaultDCPAudioChannels").get_value_or (6);
319
320         if (f.optional_string_child ("DCPMetadataIssuer")) {
321                 _dcp_issuer = f.string_child ("DCPMetadataIssuer");
322         } else if (f.optional_string_child ("DCPIssuer")) {
323                 _dcp_issuer = f.string_child ("DCPIssuer");
324         }
325
326         _default_upload_after_make_dcp = f.optional_bool_child("DefaultUploadAfterMakeDCP").get_value_or (false);
327         _dcp_creator = f.optional_string_child ("DCPCreator").get_value_or ("");
328
329         if (version && version.get() >= 2) {
330                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
331         } else {
332                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
333         }
334
335         _default_still_length = f.optional_number_child<int>("DefaultStillLength").get_value_or (10);
336         _default_j2k_bandwidth = f.optional_number_child<int>("DefaultJ2KBandwidth").get_value_or (200000000);
337         _default_audio_delay = f.optional_number_child<int>("DefaultAudioDelay").get_value_or (0);
338         _default_interop = f.optional_bool_child("DefaultInterop").get_value_or (false);
339         _default_kdm_directory = f.optional_string_child("DefaultKDMDirectory");
340
341         /* Read any cinemas that are still lying around in the config file
342          * from an old version.
343          */
344         read_cinemas (f);
345
346         _mail_server = f.string_child ("MailServer");
347         _mail_port = f.optional_number_child<int> ("MailPort").get_value_or (25);
348
349         {
350                 /* Make sure this matches the code in write_config */
351                 string const protocol = f.optional_string_child("MailProtocol").get_value_or("Auto");
352                 if (protocol == "Auto") {
353                         _mail_protocol = EMAIL_PROTOCOL_AUTO;
354                 } else if (protocol == "Plain") {
355                         _mail_protocol = EMAIL_PROTOCOL_PLAIN;
356                 } else if (protocol == "STARTTLS") {
357                         _mail_protocol = EMAIL_PROTOCOL_STARTTLS;
358                 } else if (protocol == "SSL") {
359                         _mail_protocol = EMAIL_PROTOCOL_SSL;
360                 }
361         }
362
363         _mail_user = f.optional_string_child("MailUser").get_value_or ("");
364         _mail_password = f.optional_string_child("MailPassword").get_value_or ("");
365
366         _kdm_subject = f.optional_string_child ("KDMSubject").get_value_or (_("KDM delivery: $CPL_NAME"));
367         _kdm_from = f.string_child ("KDMFrom");
368         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("KDMCC")) {
369                 if (!i->content().empty()) {
370                         _kdm_cc.push_back (i->content ());
371                 }
372         }
373         _kdm_bcc = f.optional_string_child ("KDMBCC").get_value_or ("");
374         _kdm_email = f.string_child ("KDMEmail");
375
376         _notification_subject = f.optional_string_child("NotificationSubject").get_value_or(_("DCP-o-matic notification"));
377         _notification_from = f.optional_string_child("NotificationFrom").get_value_or("");
378         _notification_to = f.optional_string_child("NotificationTo").get_value_or("");
379         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("NotificationCC")) {
380                 if (!i->content().empty()) {
381                         _notification_cc.push_back (i->content ());
382                 }
383         }
384         _notification_bcc = f.optional_string_child("NotificationBCC").get_value_or("");
385         if (f.optional_string_child("NotificationEmail")) {
386                 _notification_email = f.string_child("NotificationEmail");
387         }
388
389         _check_for_updates = f.optional_bool_child("CheckForUpdates").get_value_or (false);
390         _check_for_test_updates = f.optional_bool_child("CheckForTestUpdates").get_value_or (false);
391
392         _maximum_j2k_bandwidth = f.optional_number_child<int> ("MaximumJ2KBandwidth").get_value_or (250000000);
393         _allow_any_dcp_frame_rate = f.optional_bool_child ("AllowAnyDCPFrameRate").get_value_or (false);
394         _allow_any_container = f.optional_bool_child ("AllowAnyContainer").get_value_or (false);
395         _show_experimental_audio_processors = f.optional_bool_child ("ShowExperimentalAudioProcessors").get_value_or (false);
396
397         _log_types = f.optional_number_child<int> ("LogTypes").get_value_or (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR);
398         _analyse_ebur128 = f.optional_bool_child("AnalyseEBUR128").get_value_or (true);
399         _automatic_audio_analysis = f.optional_bool_child ("AutomaticAudioAnalysis").get_value_or (false);
400 #ifdef DCPOMATIC_WINDOWS
401         _win32_console = f.optional_bool_child ("Win32Console").get_value_or (false);
402 #endif
403
404         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("History")) {
405                 _history.push_back (i->content ());
406         }
407
408         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("PlayerHistory")) {
409                 _player_history.push_back (i->content ());
410         }
411
412         cxml::NodePtr signer = f.optional_node_child ("Signer");
413 #ifdef DCPOMATIC_VARIANT_SWAROOP
414         if (signer && signer->node_children().size() == 1) {
415                 /* The content of <Signer> is a path to a file; if it's relative it's in the same
416                    directory as .config. */
417                 _signer_chain_path = signer->content();
418                 if (_signer_chain_path.is_relative()) {
419                         _signer_chain = read_swaroop_chain (path(_signer_chain_path.string()));
420                 } else {
421                         _signer_chain = read_swaroop_chain (_signer_chain_path);
422                 }
423         } else {
424                 /* <Signer> is not present or has children: ignore it and remake. */
425                 _signer_chain = create_certificate_chain ();
426         }
427 #else
428         if (signer) {
429                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
430                 /* Read the signing certificates and private key in from the config file */
431                 BOOST_FOREACH (cxml::NodePtr i, signer->node_children ("Certificate")) {
432                         c->add (dcp::Certificate (i->content ()));
433                 }
434                 c->set_key (signer->string_child ("PrivateKey"));
435                 _signer_chain = c;
436         } else {
437                 /* Make a new set of signing certificates and key */
438                 _signer_chain = create_certificate_chain ();
439         }
440 #endif
441
442         cxml::NodePtr decryption = f.optional_node_child ("Decryption");
443 #ifdef DCPOMATIC_VARIANT_SWAROOP
444         if (decryption && decryption->node_children().size() == 1) {
445                 /* The content of <Decryption> is a path to a file; if it's relative, it's in the same
446                    directory as .config. */
447                 _decryption_chain_path = decryption->content();
448                 if (_decryption_chain_path.is_relative()) {
449                         _decryption_chain = read_swaroop_chain (path(_decryption_chain_path.string()));
450                 } else {
451                         _decryption_chain = read_swaroop_chain (_decryption_chain_path);
452                 }
453         } else {
454                 /* <Decryption> is not present or has more children: ignore it and remake. */
455                 _decryption_chain = create_certificate_chain ();
456         }
457 #else
458         if (decryption) {
459                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
460                 BOOST_FOREACH (cxml::NodePtr i, decryption->node_children ("Certificate")) {
461                         c->add (dcp::Certificate (i->content ()));
462                 }
463                 c->set_key (decryption->string_child ("PrivateKey"));
464                 _decryption_chain = c;
465         } else {
466                 _decryption_chain = create_certificate_chain ();
467         }
468 #endif
469
470         /* These must be done before we call Bad as that might set one
471            of the nags.
472         */
473         BOOST_FOREACH (cxml::NodePtr i, f.node_children("Nagged")) {
474                 int const id = i->number_attribute<int>("Id");
475                 if (id >= 0 && id < NAG_COUNT) {
476                         _nagged[id] = raw_convert<int>(i->content());
477                 }
478         }
479
480         optional<BadReason> bad;
481
482         BOOST_FOREACH (dcp::Certificate const & i, _signer_chain->unordered()) {
483                 if (i.has_utf8_strings()) {
484                         bad = BAD_SIGNER_UTF8_STRINGS;
485                 }
486         }
487
488         if (!_signer_chain->chain_valid() || !_signer_chain->private_key_valid()) {
489                 bad = BAD_SIGNER_INCONSISTENT;
490         }
491
492         if (!_decryption_chain->chain_valid() || !_decryption_chain->private_key_valid()) {
493                 bad = BAD_DECRYPTION_INCONSISTENT;
494         }
495
496         if (bad) {
497                 optional<bool> const remake = Bad(*bad);
498                 if (remake && *remake) {
499                         switch (*bad) {
500                         case BAD_SIGNER_UTF8_STRINGS:
501                         case BAD_SIGNER_INCONSISTENT:
502                                 _signer_chain = create_certificate_chain ();
503                                 break;
504                         case BAD_DECRYPTION_INCONSISTENT:
505                                 _decryption_chain = create_certificate_chain ();
506                                 break;
507                         }
508                 }
509         }
510
511         if (f.optional_node_child("DKDMGroup")) {
512                 /* New-style: all DKDMs in a group */
513                 _dkdms = dynamic_pointer_cast<DKDMGroup> (DKDMBase::read (f.node_child("DKDMGroup")));
514         } else {
515                 /* Old-style: one or more DKDM nodes */
516                 _dkdms.reset (new DKDMGroup ("root"));
517                 BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("DKDM")) {
518                         _dkdms->add (DKDMBase::read (i));
519                 }
520         }
521         _cinemas_file = f.optional_string_child("CinemasFile").get_value_or (path ("cinemas.xml").string ());
522         _dkdm_recipients_file = f.optional_string_child("DKDMRecipientsFile").get_value_or (path("dkdm_recipients.xml").string());
523         _show_hints_before_make_dcp = f.optional_bool_child("ShowHintsBeforeMakeDCP").get_value_or (true);
524         _confirm_kdm_email = f.optional_bool_child("ConfirmKDMEmail").get_value_or (true);
525         _kdm_container_name_format = dcp::NameFormat (f.optional_string_child("KDMContainerNameFormat").get_value_or ("KDM %f %c"));
526         _kdm_filename_format = dcp::NameFormat (f.optional_string_child("KDMFilenameFormat").get_value_or ("KDM %f %c %s"));
527         _dkdm_filename_format = dcp::NameFormat (f.optional_string_child("DKDMFilenameFormat").get_value_or("DKDM %f %c %s"));
528         _dcp_metadata_filename_format = dcp::NameFormat (f.optional_string_child("DCPMetadataFilenameFormat").get_value_or ("%t"));
529         _dcp_asset_filename_format = dcp::NameFormat (f.optional_string_child("DCPAssetFilenameFormat").get_value_or ("%t"));
530         _jump_to_selected = f.optional_bool_child("JumpToSelected").get_value_or (true);
531         /* The variable was renamed but not the XML tag */
532         _sound = f.optional_bool_child("PreviewSound").get_value_or (true);
533         _sound_output = f.optional_string_child("PreviewSoundOutput");
534         if (f.optional_string_child("CoverSheet")) {
535                 _cover_sheet = f.optional_string_child("CoverSheet").get();
536         }
537         _last_player_load_directory = f.optional_string_child("LastPlayerLoadDirectory");
538         if (f.optional_string_child("LastKDMWriteType")) {
539                 if (f.optional_string_child("LastKDMWriteType").get() == "flat") {
540                         _last_kdm_write_type = KDM_WRITE_FLAT;
541                 } else if (f.optional_string_child("LastKDMWriteType").get() == "folder") {
542                         _last_kdm_write_type = KDM_WRITE_FOLDER;
543                 } else if (f.optional_string_child("LastKDMWriteType").get() == "zip") {
544                         _last_kdm_write_type = KDM_WRITE_ZIP;
545                 }
546         }
547         if (f.optional_string_child("LastDKDMWriteType")) {
548                 if (f.optional_string_child("LastDKDMWriteType").get() == "internal") {
549                         _last_dkdm_write_type = DKDM_WRITE_INTERNAL;
550                 } else if (f.optional_string_child("LastDKDMWriteType").get() == "file") {
551                         _last_dkdm_write_type = DKDM_WRITE_FILE;
552                 }
553         }
554         _frames_in_memory_multiplier = f.optional_number_child<int>("FramesInMemoryMultiplier").get_value_or(3);
555         _decode_reduction = f.optional_number_child<int>("DecodeReduction");
556         _default_notify = f.optional_bool_child("DefaultNotify").get_value_or(false);
557
558         BOOST_FOREACH (cxml::NodePtr i, f.node_children("Notification")) {
559                 int const id = i->number_attribute<int>("Id");
560                 if (id >= 0 && id < NOTIFICATION_COUNT) {
561                         _notification[id] = raw_convert<int>(i->content());
562                 }
563         }
564
565         _barco_username = f.optional_string_child("BarcoUsername");
566         _barco_password = f.optional_string_child("BarcoPassword");
567         _christie_username = f.optional_string_child("ChristieUsername");
568         _christie_password = f.optional_string_child("ChristiePassword");
569         _gdc_username = f.optional_string_child("GDCUsername");
570         _gdc_password = f.optional_string_child("GDCPassword");
571
572         optional<string> ic = f.optional_string_child("InterfaceComplexity");
573         if (ic && *ic == "full") {
574                 _interface_complexity = INTERFACE_FULL;
575         }
576         optional<string> pm = f.optional_string_child("PlayerMode");
577         if (pm && *pm == "window") {
578                 _player_mode = PLAYER_MODE_WINDOW;
579         } else if (pm && *pm == "full") {
580                 _player_mode = PLAYER_MODE_FULL;
581         } else if (pm && *pm == "dual") {
582                 _player_mode = PLAYER_MODE_DUAL;
583         }
584
585         _image_display = f.optional_number_child<int>("ImageDisplay").get_value_or(0);
586         optional<string> vc = f.optional_string_child("VideoViewType");
587         if (vc && *vc == "opengl") {
588                 _video_view_type = VIDEO_VIEW_OPENGL;
589         } else if (vc && *vc == "simple") {
590                 _video_view_type = VIDEO_VIEW_SIMPLE;
591         }
592         _respect_kdm_validity_periods = f.optional_bool_child("RespectKDMValidityPeriods").get_value_or(true);
593         /* PlayerLogFile is old name */
594         _player_activity_log_file = f.optional_string_child("PlayerLogFile");
595         if (!_player_activity_log_file) {
596                 _player_activity_log_file = f.optional_string_child("PlayerActivityLogFile");
597         }
598         _player_debug_log_file = f.optional_string_child("PlayerDebugLogFile");
599         _player_content_directory = f.optional_string_child("PlayerContentDirectory");
600         _player_playlist_directory = f.optional_string_child("PlayerPlaylistDirectory");
601         _player_kdm_directory = f.optional_string_child("PlayerKDMDirectory");
602
603         if (f.optional_node_child("AudioMapping")) {
604                 _audio_mapping = AudioMapping (f.node_child("AudioMapping"), Film::current_state_version);
605         }
606
607 #ifdef DCPOMATIC_VARIANT_SWAROOP
608         _player_background_image = f.optional_string_child("PlayerBackgroundImage");
609         _kdm_server_url = f.optional_string_child("KDMServerURL").get_value_or("http://localhost:8000/{CPL}");
610         _player_watermark_theatre = f.optional_string_child("PlayerWatermarkTheatre").get_value_or("");
611         _player_watermark_period = f.optional_number_child<int>("PlayerWatermarkPeriod").get_value_or(1);
612         _player_watermark_duration = f.optional_number_child<int>("PlayerWatermarkDuration").get_value_or(150);
613         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("RequiredMonitor")) {
614                 _required_monitors.push_back(Monitor(i));
615         }
616         _player_lock_file = f.optional_string_child("PlayerLockFile");
617 #endif
618
619         if (boost::filesystem::exists (_cinemas_file)) {
620                 cxml::Document f ("Cinemas");
621                 f.read_file (_cinemas_file);
622                 read_cinemas (f);
623         }
624
625         if (boost::filesystem::exists (_dkdm_recipients_file)) {
626                 cxml::Document f ("DKDMRecipients");
627                 f.read_file (_dkdm_recipients_file);
628                 read_dkdm_recipients (f);
629         }
630 }
631 catch (...) {
632         if (have_existing ("config.xml")) {
633                 backup ();
634                 /* We have a config file but it didn't load */
635                 FailedToLoad ();
636         }
637         set_defaults ();
638         /* Make a new set of signing certificates and key */
639         _signer_chain = create_certificate_chain ();
640         /* And similar for decryption of KDMs */
641         _decryption_chain = create_certificate_chain ();
642         write ();
643 }
644
645 /** @return Singleton instance */
646 Config *
647 Config::instance ()
648 {
649         if (_instance == 0) {
650                 _instance = new Config;
651                 _instance->read ();
652         }
653
654         return _instance;
655 }
656
657 /** Write our configuration to disk */
658 void
659 Config::write () const
660 {
661         write_config ();
662         write_cinemas ();
663         write_dkdm_recipients ();
664 }
665
666 void
667 Config::write_config () const
668 {
669         xmlpp::Document doc;
670         xmlpp::Element* root = doc.create_root_node ("Config");
671
672         /* [XML] Version The version number of the configuration file format. */
673         root->add_child("Version")->add_child_text (raw_convert<string>(_current_version));
674         /* [XML] MasterEncodingThreads Number of encoding threads to use when running as master. */
675         root->add_child("MasterEncodingThreads")->add_child_text (raw_convert<string> (_master_encoding_threads));
676         /* [XML] ServerEncodingThreads Number of encoding threads to use when running as server. */
677         root->add_child("ServerEncodingThreads")->add_child_text (raw_convert<string> (_server_encoding_threads));
678         if (_default_directory) {
679                 /* [XML:opt] DefaultDirectory Default directory when creating a new film in the GUI. */
680                 root->add_child("DefaultDirectory")->add_child_text (_default_directory->string ());
681         }
682         /* [XML] ServerPortBase Port number to use for frame encoding requests.  <code>ServerPortBase</code> + 1 and
683            <code>ServerPortBase</code> + 2 are used for querying servers.  <code>ServerPortBase</code> + 3 is used
684            by the batch converter to listen for job requests.
685         */
686         root->add_child("ServerPortBase")->add_child_text (raw_convert<string> (_server_port_base));
687         /* [XML] UseAnyServers 1 to broadcast to look for encoding servers to use, 0 to use only those configured. */
688         root->add_child("UseAnyServers")->add_child_text (_use_any_servers ? "1" : "0");
689
690         BOOST_FOREACH (string i, _servers) {
691                 /* [XML:opt] Server IP address or hostname of an encoding server to use; you can use as many of these tags
692                    as you like.
693                 */
694                 root->add_child("Server")->add_child_text (i);
695         }
696
697         /* [XML] OnlyServersEncode 1 to set the master to do decoding of source content no JPEG2000 encoding; all encoding
698            is done by the encoding servers.  0 to set the master to do some encoding as well as coordinating the job.
699         */
700         root->add_child("OnlyServersEncode")->add_child_text (_only_servers_encode ? "1" : "0");
701         /* [XML] TMSProtocol Protocol to use to copy files to a TMS; 0 to use SCP, 1 for FTP. */
702         root->add_child("TMSProtocol")->add_child_text (raw_convert<string> (static_cast<int> (_tms_protocol)));
703         /* [XML] TMSIP IP address of TMS. */
704         root->add_child("TMSIP")->add_child_text (_tms_ip);
705         /* [XML] TMSPath Path on the TMS to copy files to. */
706         root->add_child("TMSPath")->add_child_text (_tms_path);
707         /* [XML] TMSUser Username to log into the TMS with. */
708         root->add_child("TMSUser")->add_child_text (_tms_user);
709         /* [XML] TMSPassword Password to log into the TMS with. */
710         root->add_child("TMSPassword")->add_child_text (_tms_password);
711         if (_language) {
712                 /* [XML:opt] Language Language to use in the GUI e.g. <code>fr_FR</code>. */
713                 root->add_child("Language")->add_child_text (_language.get());
714         }
715         if (_default_container) {
716                 /* [XML:opt] DefaultContainer ID of default container
717                    to use when creating new films (<code>185</code>,<code>239</code> or
718                    <code>190</code>).
719                 */
720                 root->add_child("DefaultContainer")->add_child_text (_default_container->id ());
721         }
722         if (_default_scale_to) {
723                 /* [XML:opt] DefaultScaleTo ID of default ratio to scale content to when creating new films
724                    (see <code>DefaultContainer</code> for IDs).
725                 */
726                 root->add_child("DefaultScaleTo")->add_child_text (_default_scale_to->id ());
727         }
728         if (_default_dcp_content_type) {
729                 /* [XML:opt] DefaultDCPContentType Default content type ot use when creating new films (<code>FTR</code>, <code>SHR</code>,
730                    <code>TLR</code>, <code>TST</code>, <code>XSN</code>, <code>RTG</code>, <code>TSR</code>, <code>POL</code>,
731                    <code>PSA</code> or <code>ADV</code>). */
732                 root->add_child("DefaultDCPContentType")->add_child_text (_default_dcp_content_type->isdcf_name ());
733         }
734         /* [XML] DefaultDCPAudioChannels Default number of audio channels to use when creating new films. */
735         root->add_child("DefaultDCPAudioChannels")->add_child_text (raw_convert<string> (_default_dcp_audio_channels));
736         /* [XML] DCPIssuer Issuer text to write into CPL files. */
737         root->add_child("DCPIssuer")->add_child_text (_dcp_issuer);
738         /* [XML] DCPIssuer Creator text to write into CPL files. */
739         root->add_child("DCPCreator")->add_child_text (_dcp_creator);
740         /* [XML] DefaultUploadAfterMakeDCP 1 to default to uploading to a TMS after making a DCP, 0 to default to no upload. */
741         root->add_child("DefaultUploadAfterMakeDCP")->add_child_text (_default_upload_after_make_dcp ? "1" : "0");
742
743         /* [XML] ISDCFMetadata Default ISDCF metadata to use for new films; child tags are <code>&lt;ContentVersion&gt;</code>,
744            <code>&lt;AudioLanguage&gt;</code>, <code>&lt;SubtitleLanguage&gt;</code>, <code>&lt;Territory&gt;</code>,
745            <code>&lt;Rating&gt;</code>, <code>&lt;Studio&gt;</code>, <code>&lt;Facility&gt;</code>, <code>&lt;TempVersion&gt;</code>,
746            <code>&lt;PreRelease&gt;</code>, <code>&lt;RedBand&gt;</code>, <code>&lt;Chain&gt;</code>, <code>&lt;TwoDVersionOFThreeD&gt;</code>,
747            <code>&lt;MasteredLuminance&gt;</code>.
748         */
749         _default_isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
750
751         /* [XML] DefaultStillLength Default length (in seconds) for still images in new films. */
752         root->add_child("DefaultStillLength")->add_child_text (raw_convert<string> (_default_still_length));
753         /* [XML] DefaultJ2KBandwidth Default bitrate (in bits per second) for JPEG2000 data in new films. */
754         root->add_child("DefaultJ2KBandwidth")->add_child_text (raw_convert<string> (_default_j2k_bandwidth));
755         /* [XML] DefaultAudioDelay Default delay to apply to audio (positive moves audio later) in milliseconds. */
756         root->add_child("DefaultAudioDelay")->add_child_text (raw_convert<string> (_default_audio_delay));
757         /* [XML] DefaultInterop 1 to default new films to Interop, 0 for SMPTE. */
758         root->add_child("DefaultInterop")->add_child_text (_default_interop ? "1" : "0");
759         if (_default_kdm_directory) {
760                 /* [XML:opt] DefaultKDMDirectory Default directory to write KDMs to. */
761                 root->add_child("DefaultKDMDirectory")->add_child_text (_default_kdm_directory->string ());
762         }
763         /* [XML] MailServer Hostname of SMTP server to use. */
764         root->add_child("MailServer")->add_child_text (_mail_server);
765         /* [XML] MailPort Port number to use on SMTP server. */
766         root->add_child("MailPort")->add_child_text (raw_convert<string> (_mail_port));
767         /* [XML] MailProtocol Protocol to use on SMTP server (Auto, Plain, STARTTLS or SSL) */
768         switch (_mail_protocol) {
769         case EMAIL_PROTOCOL_AUTO:
770                 root->add_child("MailProtocol")->add_child_text("Auto");
771                 break;
772         case EMAIL_PROTOCOL_PLAIN:
773                 root->add_child("MailProtocol")->add_child_text("Plain");
774                 break;
775         case EMAIL_PROTOCOL_STARTTLS:
776                 root->add_child("MailProtocol")->add_child_text("STARTTLS");
777                 break;
778         case EMAIL_PROTOCOL_SSL:
779                 root->add_child("MailProtocol")->add_child_text("SSL");
780                 break;
781         }
782         /* [XML] MailUser Username to use on SMTP server. */
783         root->add_child("MailUser")->add_child_text (_mail_user);
784         /* [XML] MailPassword Password to use on SMTP server. */
785         root->add_child("MailPassword")->add_child_text (_mail_password);
786
787         /* [XML] KDMSubject Subject to use for KDM emails. */
788         root->add_child("KDMSubject")->add_child_text (_kdm_subject);
789         /* [XML] KDMFrom From address to use for KDM emails. */
790         root->add_child("KDMFrom")->add_child_text (_kdm_from);
791         BOOST_FOREACH (string i, _kdm_cc) {
792                 /* [XML] KDMCC CC address to use for KDM emails; you can use as many of these tags as you like. */
793                 root->add_child("KDMCC")->add_child_text (i);
794         }
795         /* [XML] KDMBCC BCC address to use for KDM emails. */
796         root->add_child("KDMBCC")->add_child_text (_kdm_bcc);
797         /* [XML] KDMEmail Text of KDM email. */
798         root->add_child("KDMEmail")->add_child_text (_kdm_email);
799
800         /* [XML] NotificationSubject Subject to use for notification emails. */
801         root->add_child("NotificationSubject")->add_child_text (_notification_subject);
802         /* [XML] NotificationFrom From address to use for notification emails. */
803         root->add_child("NotificationFrom")->add_child_text (_notification_from);
804         /* [XML] NotificationFrom To address to use for notification emails. */
805         root->add_child("NotificationTo")->add_child_text (_notification_to);
806         BOOST_FOREACH (string i, _notification_cc) {
807                 /* [XML] NotificationCC CC address to use for notification emails; you can use as many of these tags as you like. */
808                 root->add_child("NotificationCC")->add_child_text (i);
809         }
810         /* [XML] NotificationBCC BCC address to use for notification emails. */
811         root->add_child("NotificationBCC")->add_child_text (_notification_bcc);
812         /* [XML] NotificationEmail Text of notification email. */
813         root->add_child("NotificationEmail")->add_child_text (_notification_email);
814
815         /* [XML] CheckForUpdates 1 to check dcpomatic.com for new versions, 0 to check only on request. */
816         root->add_child("CheckForUpdates")->add_child_text (_check_for_updates ? "1" : "0");
817         /* [XML] CheckForUpdates 1 to check dcpomatic.com for new text versions, 0 to check only on request. */
818         root->add_child("CheckForTestUpdates")->add_child_text (_check_for_test_updates ? "1" : "0");
819
820         /* [XML] MaximumJ2KBandwidth Maximum J2K bandwidth (in bits per second) that can be specified in the GUI. */
821         root->add_child("MaximumJ2KBandwidth")->add_child_text (raw_convert<string> (_maximum_j2k_bandwidth));
822         /* [XML] AllowAnyDCPFrameRate 1 to allow users to specify any frame rate when creating DCPs, 0 to limit the GUI to standard rates. */
823         root->add_child("AllowAnyDCPFrameRate")->add_child_text (_allow_any_dcp_frame_rate ? "1" : "0");
824         /* [XML] AllowAnyContainer 1 to allow users to user any container ratio for their DCP, 0 to limit the GUI to standard containers. */
825         root->add_child("AllowAnyContainer")->add_child_text (_allow_any_container ? "1" : "0");
826         /* [XML] ShowExperimentalAudioProcessors 1 to offer users the (experimental) audio upmixer processors, 0 to hide them */
827         root->add_child("ShowExperimentalAudioProcessors")->add_child_text (_show_experimental_audio_processors ? "1" : "0");
828         /* [XML] LogTypes Types of logging to write; a bitfield where 1 is general notes, 2 warnings, 4 errors, 8 debug information related
829            to encoding, 16 debug information related to encoding, 32 debug information for timing purposes, 64 debug information related
830            to sending email.
831         */
832         root->add_child("LogTypes")->add_child_text (raw_convert<string> (_log_types));
833         /* [XML] AnalyseEBUR128 1 to do EBUR128 analyses when analysing audio, otherwise 0. */
834         root->add_child("AnalyseEBUR128")->add_child_text (_analyse_ebur128 ? "1" : "0");
835         /* [XML] AutomaticAudioAnalysis 1 to run audio analysis automatically when audio content is added to the film, otherwise 0. */
836         root->add_child("AutomaticAudioAnalysis")->add_child_text (_automatic_audio_analysis ? "1" : "0");
837 #ifdef DCPOMATIC_WINDOWS
838         /* [XML] Win32Console 1 to open a console when running on Windows, otherwise 0. */
839         root->add_child("Win32Console")->add_child_text (_win32_console ? "1" : "0");
840 #endif
841
842 #ifdef DCPOMATIC_VARIANT_SWAROOP
843         if (_signer_chain_path.is_relative()) {
844                 write_swaroop_chain (_signer_chain, path(_signer_chain_path.string()));
845         } else {
846                 write_swaroop_chain (_signer_chain, _signer_chain_path);
847         }
848         root->add_child("Signer")->add_child_text(_signer_chain_path.string());
849 #else
850         /* [XML] Signer Certificate chain and private key to use when signing DCPs and KDMs.  Should contain <code>&lt;Certificate&gt;</code>
851            tags in order and a <code>&lt;PrivateKey&gt;</code> tag all containing PEM-encoded certificates or private keys as appropriate.
852         */
853         xmlpp::Element* signer = root->add_child ("Signer");
854         DCPOMATIC_ASSERT (_signer_chain);
855         BOOST_FOREACH (dcp::Certificate const & i, _signer_chain->unordered()) {
856                 signer->add_child("Certificate")->add_child_text (i.certificate (true));
857         }
858         signer->add_child("PrivateKey")->add_child_text (_signer_chain->key().get ());
859 #endif
860
861 #ifdef DCPOMATIC_VARIANT_SWAROOP
862         if (_decryption_chain_path.is_relative()) {
863                 write_swaroop_chain (_decryption_chain, path(_decryption_chain_path.string()));
864         } else {
865                 write_swaroop_chain (_decryption_chain, _decryption_chain_path);
866         }
867         root->add_child("Decryption")->add_child_text(_decryption_chain_path.string());
868 #else
869         /* [XML] Decryption Certificate chain and private key to use when decrypting KDMs */
870         xmlpp::Element* decryption = root->add_child ("Decryption");
871         DCPOMATIC_ASSERT (_decryption_chain);
872         BOOST_FOREACH (dcp::Certificate const & i, _decryption_chain->unordered()) {
873                 decryption->add_child("Certificate")->add_child_text (i.certificate (true));
874         }
875         decryption->add_child("PrivateKey")->add_child_text (_decryption_chain->key().get ());
876 #endif
877
878         /* [XML] History Filename of DCP to present in the <guilabel>File</guilabel> menu of the GUI; there can be more than one
879            of these tags.
880         */
881         BOOST_FOREACH (boost::filesystem::path i, _history) {
882                 root->add_child("History")->add_child_text (i.string ());
883         }
884
885         /* [XML] History Filename of DCP to present in the <guilabel>File</guilabel> menu of the player; there can be more than one
886            of these tags.
887         */
888         BOOST_FOREACH (boost::filesystem::path i, _player_history) {
889                 root->add_child("PlayerHistory")->add_child_text (i.string ());
890         }
891
892         /* [XML] DKDMGroup A group of DKDMs, each with a <code>Name</code> attribute, containing other <code>&lt;DKDMGroup&gt;</code>
893            or <code>&lt;DKDM&gt;</code> tags.
894         */
895         /* [XML] DKDM A DKDM as XML */
896         _dkdms->as_xml (root);
897
898         /* [XML] CinemasFile Filename of cinemas list file. */
899         root->add_child("CinemasFile")->add_child_text (_cinemas_file.string());
900         /* [XML] DKDMRecipientsFile Filename of DKDM recipients list file. */
901         root->add_child("DKDMRecipientsFile")->add_child_text (_dkdm_recipients_file.string());
902         /* [XML] ShowHintsBeforeMakeDCP 1 to show hints in the GUI before making a DCP, otherwise 0. */
903         root->add_child("ShowHintsBeforeMakeDCP")->add_child_text (_show_hints_before_make_dcp ? "1" : "0");
904         /* [XML] ConfirmKDMEmail 1 to confirm before sending KDM emails in the GUI, otherwise 0. */
905         root->add_child("ConfirmKDMEmail")->add_child_text (_confirm_kdm_email ? "1" : "0");
906         /* [XML] KDMFilenameFormat Format for KDM filenames. */
907         root->add_child("KDMFilenameFormat")->add_child_text (_kdm_filename_format.specification ());
908         /* [XML] KDMFilenameFormat Format for DKDM filenames. */
909         root->add_child("DKDMFilenameFormat")->add_child_text(_dkdm_filename_format.specification());
910         /* [XML] KDMContainerNameFormat Format for KDM containers (directories or ZIP files). */
911         root->add_child("KDMContainerNameFormat")->add_child_text (_kdm_container_name_format.specification ());
912         /* [XML] DCPMetadataFilenameFormat Format for DCP metadata filenames. */
913         root->add_child("DCPMetadataFilenameFormat")->add_child_text (_dcp_metadata_filename_format.specification ());
914         /* [XML] DCPAssetFilenameFormat Format for DCP asset filenames. */
915         root->add_child("DCPAssetFilenameFormat")->add_child_text (_dcp_asset_filename_format.specification ());
916         /* [XML] JumpToSelected 1 to make the GUI jump to the start of content when it is selected, otherwise 0. */
917         root->add_child("JumpToSelected")->add_child_text (_jump_to_selected ? "1" : "0");
918         /* [XML] Nagged 1 if a particular nag screen has been shown and should not be shown again, otherwise 0. */
919         for (int i = 0; i < NAG_COUNT; ++i) {
920                 xmlpp::Element* e = root->add_child ("Nagged");
921                 e->set_attribute ("Id", raw_convert<string>(i));
922                 e->add_child_text (_nagged[i] ? "1" : "0");
923         }
924         /* [XML] PreviewSound 1 to use sound in the GUI preview and player, otherwise 0. */
925         root->add_child("PreviewSound")->add_child_text (_sound ? "1" : "0");
926         if (_sound_output) {
927                 /* [XML:opt] PreviewSoundOutput Name of the audio output to use. */
928                 root->add_child("PreviewSoundOutput")->add_child_text (_sound_output.get());
929         }
930         /* [XML] CoverSheet Text of the cover sheet to write when making DCPs. */
931         root->add_child("CoverSheet")->add_child_text (_cover_sheet);
932         if (_last_player_load_directory) {
933                 root->add_child("LastPlayerLoadDirectory")->add_child_text(_last_player_load_directory->string());
934         }
935         /* [XML] LastKDMWriteType Last type of KDM-write: <code>flat</code> for a flat file, <code>folder</code> for a folder or <code>zip</code> for a ZIP file. */
936         if (_last_kdm_write_type) {
937                 switch (_last_kdm_write_type.get()) {
938                 case KDM_WRITE_FLAT:
939                         root->add_child("LastKDMWriteType")->add_child_text("flat");
940                         break;
941                 case KDM_WRITE_FOLDER:
942                         root->add_child("LastKDMWriteType")->add_child_text("folder");
943                         break;
944                 case KDM_WRITE_ZIP:
945                         root->add_child("LastKDMWriteType")->add_child_text("zip");
946                         break;
947                 }
948         }
949         /* [XML] LastDKDMWriteType Last type of DKDM-write: <code>file</code> for a file, <code>internal</code> to add to DCP-o-matic's list. */
950         if (_last_dkdm_write_type) {
951                 switch (_last_dkdm_write_type.get()) {
952                 case DKDM_WRITE_INTERNAL:
953                         root->add_child("LastDKDMWriteType")->add_child_text("internal");
954                         break;
955                 case DKDM_WRITE_FILE:
956                         root->add_child("LastDKDMWriteType")->add_child_text("file");
957                         break;
958                 }
959         }
960         /* [XML] FramesInMemoryMultiplier value to multiply the encoding threads count by to get the maximum number of
961            frames to be held in memory at once.
962         */
963         root->add_child("FramesInMemoryMultiplier")->add_child_text(raw_convert<string>(_frames_in_memory_multiplier));
964
965         /* [XML] DecodeReduction power of 2 to reduce DCP images by before decoding in the player. */
966         if (_decode_reduction) {
967                 root->add_child("DecodeReduction")->add_child_text(raw_convert<string>(_decode_reduction.get()));
968         }
969
970         /* [XML] DefaultNotify 1 to default jobs to notify when complete, otherwise 0. */
971         root->add_child("DefaultNotify")->add_child_text(_default_notify ? "1" : "0");
972
973         /* [XML] Notification 1 if a notification type is enabled, otherwise 0. */
974         for (int i = 0; i < NOTIFICATION_COUNT; ++i) {
975                 xmlpp::Element* e = root->add_child ("Notification");
976                 e->set_attribute ("Id", raw_convert<string>(i));
977                 e->add_child_text (_notification[i] ? "1" : "0");
978         }
979
980         if (_barco_username) {
981                 /* [XML] BarcoUsername Username for logging into Barco's servers when downloading server certificates. */
982                 root->add_child("BarcoUsername")->add_child_text(*_barco_username);
983         }
984         if (_barco_password) {
985                 /* [XML] BarcoPassword Password for logging into Barco's servers when downloading server certificates. */
986                 root->add_child("BarcoPassword")->add_child_text(*_barco_password);
987         }
988
989         if (_christie_username) {
990                 /* [XML] ChristieUsername Username for logging into Christie's servers when downloading server certificates. */
991                 root->add_child("ChristieUsername")->add_child_text(*_christie_username);
992         }
993         if (_christie_password) {
994                 /* [XML] ChristiePassword Password for logging into Christie's servers when downloading server certificates. */
995                 root->add_child("ChristiePassword")->add_child_text(*_christie_password);
996         }
997
998         if (_gdc_username) {
999                 /* [XML] GCCUsername Username for logging into GDC's servers when downloading server certificates. */
1000                 root->add_child("GDCUsername")->add_child_text(*_gdc_username);
1001         }
1002         if (_gdc_password) {
1003                 /* [XML] GCCPassword Password for logging into GDC's servers when downloading server certificates. */
1004                 root->add_child("GDCPassword")->add_child_text(*_gdc_password);
1005         }
1006
1007         /* [XML] InterfaceComplexity <code>simple</code> for the reduced interface or <code>full</code> for the full interface. */
1008         switch (_interface_complexity) {
1009         case INTERFACE_SIMPLE:
1010                 root->add_child("InterfaceComplexity")->add_child_text("simple");
1011                 break;
1012         case INTERFACE_FULL:
1013                 root->add_child("InterfaceComplexity")->add_child_text("full");
1014                 break;
1015         }
1016
1017         /* [XML] PlayerMode <code>window</code> for a single window, <code>full</code> for full-screen and <code>dual</code> for full screen playback
1018            with controls on another monitor.
1019         */
1020         switch (_player_mode) {
1021         case PLAYER_MODE_WINDOW:
1022                 root->add_child("PlayerMode")->add_child_text("window");
1023                 break;
1024         case PLAYER_MODE_FULL:
1025                 root->add_child("PlayerMode")->add_child_text("full");
1026                 break;
1027         case PLAYER_MODE_DUAL:
1028                 root->add_child("PlayerMode")->add_child_text("dual");
1029                 break;
1030         }
1031
1032         /* [XML] ImageDisplay Screen number to put image on in dual-screen player mode. */
1033         root->add_child("ImageDisplay")->add_child_text(raw_convert<string>(_image_display));
1034         switch (_video_view_type) {
1035         case VIDEO_VIEW_SIMPLE:
1036                 root->add_child("VideoViewType")->add_child_text("simple");
1037                 break;
1038         case VIDEO_VIEW_OPENGL:
1039                 root->add_child("VideoViewType")->add_child_text("opengl");
1040                 break;
1041         }
1042         /* [XML] RespectKDMValidityPeriods 1 to refuse to use KDMs that are out of date, 0 to ignore KDM dates. */
1043         root->add_child("RespectKDMValidityPeriods")->add_child_text(_respect_kdm_validity_periods ? "1" : "0");
1044         if (_player_activity_log_file) {
1045                 /* [XML] PlayerLogFile Filename to use for player activity logs (e.g starting, stopping, playlist loads) */
1046                 root->add_child("PlayerActivityLogFile")->add_child_text(_player_activity_log_file->string());
1047         }
1048         if (_player_debug_log_file) {
1049                 /* [XML] PlayerLogFile Filename to use for player debug logs */
1050                 root->add_child("PlayerDebugLogFile")->add_child_text(_player_debug_log_file->string());
1051         }
1052         if (_player_content_directory) {
1053                 /* [XML] PlayerContentDirectory Directory to use for player content in the dual-screen mode. */
1054                 root->add_child("PlayerContentDirectory")->add_child_text(_player_content_directory->string());
1055         }
1056         if (_player_playlist_directory) {
1057                 /* [XML] PlayerPlaylistDirectory Directory to use for player playlists in the dual-screen mode. */
1058                 root->add_child("PlayerPlaylistDirectory")->add_child_text(_player_playlist_directory->string());
1059         }
1060         if (_player_kdm_directory) {
1061                 /* [XML] PlayerKDMDirectory Directory to use for player KDMs in the dual-screen mode. */
1062                 root->add_child("PlayerKDMDirectory")->add_child_text(_player_kdm_directory->string());
1063         }
1064         if (_audio_mapping) {
1065                 _audio_mapping->as_xml (root->add_child("AudioMapping"));
1066         }
1067 #ifdef DCPOMATIC_VARIANT_SWAROOP
1068         if (_player_background_image) {
1069                 root->add_child("PlayerBackgroundImage")->add_child_text(_player_background_image->string());
1070         }
1071         root->add_child("KDMServerURL")->add_child_text(_kdm_server_url);
1072         root->add_child("PlayerWatermarkTheatre")->add_child_text(_player_watermark_theatre);
1073         root->add_child("PlayerWatermarkPeriod")->add_child_text(raw_convert<string>(_player_watermark_period));
1074         root->add_child("PlayerWatermarkDuration")->add_child_text(raw_convert<string>(_player_watermark_duration));
1075         BOOST_FOREACH (Monitor i, _required_monitors) {
1076                 i.as_xml(root->add_child("RequiredMonitor"));
1077         }
1078         if (_player_lock_file) {
1079                 root->add_child("PlayerLockFile")->add_child_text(_player_lock_file->string());
1080         }
1081 #endif
1082
1083         try {
1084                 string const s = doc.write_to_string_formatted ();
1085                 boost::filesystem::path tmp (string(config_file().string()).append(".tmp"));
1086                 FILE* f = fopen_boost (tmp, "w");
1087                 if (!f) {
1088                         throw FileError (_("Could not open file for writing"), tmp);
1089                 }
1090                 checked_fwrite (s.c_str(), s.length(), f, tmp);
1091                 fclose (f);
1092                 boost::filesystem::remove (config_file());
1093                 boost::filesystem::rename (tmp, config_file());
1094         } catch (xmlpp::exception& e) {
1095                 string s = e.what ();
1096                 trim (s);
1097                 throw FileError (s, config_file());
1098         }
1099 }
1100
1101
1102 template <class T>
1103 void
1104 write_file (string root_node, string node, string version, list<shared_ptr<T> > things, boost::filesystem::path file)
1105 {
1106         xmlpp::Document doc;
1107         xmlpp::Element* root = doc.create_root_node (root_node);
1108         root->add_child("Version")->add_child_text(version);
1109
1110         BOOST_FOREACH (shared_ptr<T> i, things) {
1111                 i->as_xml (root->add_child(node));
1112         }
1113
1114         try {
1115                 doc.write_to_file_formatted (file.string() + ".tmp");
1116                 boost::filesystem::remove (file);
1117                 boost::filesystem::rename (file.string() + ".tmp", file);
1118         } catch (xmlpp::exception& e) {
1119                 string s = e.what ();
1120                 trim (s);
1121                 throw FileError (s, file);
1122         }
1123 }
1124
1125
1126 void
1127 Config::write_cinemas () const
1128 {
1129         write_file ("Cinemas", "Cinema", "1", _cinemas, _cinemas_file);
1130 }
1131
1132
1133 void
1134 Config::write_dkdm_recipients () const
1135 {
1136         write_file ("DKDMRecipients", "DKDMRecipient", "1", _dkdm_recipients, _dkdm_recipients_file);
1137 }
1138
1139
1140 boost::filesystem::path
1141 Config::default_directory_or (boost::filesystem::path a) const
1142 {
1143         return directory_or (_default_directory, a);
1144 }
1145
1146 boost::filesystem::path
1147 Config::default_kdm_directory_or (boost::filesystem::path a) const
1148 {
1149         return directory_or (_default_kdm_directory, a);
1150 }
1151
1152 boost::filesystem::path
1153 Config::directory_or (optional<boost::filesystem::path> dir, boost::filesystem::path a) const
1154 {
1155         if (!dir) {
1156                 return a;
1157         }
1158
1159         boost::system::error_code ec;
1160         bool const e = boost::filesystem::exists (*dir, ec);
1161         if (ec || !e) {
1162                 return a;
1163         }
1164
1165         return *dir;
1166 }
1167
1168 void
1169 Config::drop ()
1170 {
1171         delete _instance;
1172         _instance = 0;
1173 }
1174
1175 void
1176 Config::changed (Property what)
1177 {
1178         Changed (what);
1179 }
1180
1181 void
1182 Config::set_kdm_email_to_default ()
1183 {
1184         _kdm_subject = _("KDM delivery: $CPL_NAME");
1185
1186         _kdm_email = _(
1187                 "Dear Projectionist\n\n"
1188                 "Please find attached KDMs for $CPL_NAME.\n\n"
1189                 "Cinema: $CINEMA_NAME\n"
1190                 "Screen(s): $SCREENS\n\n"
1191                 "The KDMs are valid from $START_TIME until $END_TIME.\n\n"
1192                 "Best regards,\nDCP-o-matic"
1193                 );
1194 }
1195
1196 void
1197 Config::set_notification_email_to_default ()
1198 {
1199         _notification_subject = _("DCP-o-matic notification");
1200
1201         _notification_email = _(
1202                 "$JOB_NAME: $JOB_STATUS"
1203                 );
1204 }
1205
1206 void
1207 Config::reset_kdm_email ()
1208 {
1209         set_kdm_email_to_default ();
1210         changed ();
1211 }
1212
1213 void
1214 Config::reset_notification_email ()
1215 {
1216         set_notification_email_to_default ();
1217         changed ();
1218 }
1219
1220 void
1221 Config::set_cover_sheet_to_default ()
1222 {
1223         _cover_sheet = _(
1224                 "$CPL_NAME\n\n"
1225                 "Type: $TYPE\n"
1226                 "Format: $CONTAINER\n"
1227                 "Audio: $AUDIO\n"
1228                 "Audio Language: $AUDIO_LANGUAGE\n"
1229                 "Subtitle Language: $SUBTITLE_LANGUAGE\n"
1230                 "Length: $LENGTH\n"
1231                 "Size: $SIZE\n"
1232                 );
1233 }
1234
1235 void
1236 Config::add_to_history (boost::filesystem::path p)
1237 {
1238         add_to_history_internal (_history, p);
1239 }
1240
1241 /** Remove non-existant items from the history */
1242 void
1243 Config::clean_history ()
1244 {
1245         clean_history_internal (_history);
1246 }
1247
1248 void
1249 Config::add_to_player_history (boost::filesystem::path p)
1250 {
1251         add_to_history_internal (_player_history, p);
1252 }
1253
1254 /** Remove non-existant items from the player history */
1255 void
1256 Config::clean_player_history ()
1257 {
1258         clean_history_internal (_player_history);
1259 }
1260
1261 void
1262 Config::add_to_history_internal (vector<boost::filesystem::path>& h, boost::filesystem::path p)
1263 {
1264         /* Remove existing instances of this path in the history */
1265         h.erase (remove (h.begin(), h.end(), p), h.end ());
1266
1267         h.insert (h.begin (), p);
1268         if (h.size() > HISTORY_SIZE) {
1269                 h.pop_back ();
1270         }
1271
1272         changed (HISTORY);
1273 }
1274
1275 void
1276 Config::clean_history_internal (vector<boost::filesystem::path>& h)
1277 {
1278         vector<boost::filesystem::path> old = h;
1279         h.clear ();
1280         BOOST_FOREACH (boost::filesystem::path i, old) {
1281                 try {
1282                         if (boost::filesystem::is_directory(i)) {
1283                                 h.push_back (i);
1284                         }
1285                 } catch (...) {
1286                         /* We couldn't find out if it's a directory for some reason; just ignore it */
1287                 }
1288         }
1289 }
1290
1291 bool
1292 Config::have_existing (string file)
1293 {
1294         return boost::filesystem::exists (path (file, false));
1295 }
1296
1297 void
1298 Config::read_cinemas (cxml::Document const & f)
1299 {
1300         _cinemas.clear ();
1301         list<cxml::NodePtr> cin = f.node_children ("Cinema");
1302         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("Cinema")) {
1303                 /* Slightly grotty two-part construction of Cinema here so that we can use
1304                    shared_from_this.
1305                 */
1306                 shared_ptr<Cinema> cinema (new Cinema (i));
1307                 cinema->read_screens (i);
1308                 _cinemas.push_back (cinema);
1309         }
1310 }
1311
1312 void
1313 Config::set_cinemas_file (boost::filesystem::path file)
1314 {
1315         if (file == _cinemas_file) {
1316                 return;
1317         }
1318
1319         _cinemas_file = file;
1320
1321         if (boost::filesystem::exists (_cinemas_file)) {
1322                 /* Existing file; read it in */
1323                 cxml::Document f ("Cinemas");
1324                 f.read_file (_cinemas_file);
1325                 read_cinemas (f);
1326         }
1327
1328         changed (OTHER);
1329 }
1330
1331
1332 void
1333 Config::read_dkdm_recipients (cxml::Document const & f)
1334 {
1335         _dkdm_recipients.clear ();
1336         list<cxml::NodePtr> cin = f.node_children ("DKDMRecipient");
1337         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("DKDMRecipient")) {
1338                 _dkdm_recipients.push_back (shared_ptr<DKDMRecipient>(new DKDMRecipient(i)));
1339         }
1340 }
1341
1342 void
1343 Config::set_dkdm_recipients_file (boost::filesystem::path file)
1344 {
1345         if (file == _dkdm_recipients_file) {
1346                 return;
1347         }
1348
1349         _dkdm_recipients_file = file;
1350
1351         if (boost::filesystem::exists (_dkdm_recipients_file)) {
1352                 /* Existing file; read it in */
1353                 cxml::Document f ("DKDMRecipients");
1354                 f.read_file (_dkdm_recipients_file);
1355                 read_dkdm_recipients (f);
1356         }
1357
1358         changed (OTHER);
1359 }
1360
1361
1362 void
1363 Config::save_template (shared_ptr<const Film> film, string name) const
1364 {
1365         film->write_template (template_path (name));
1366 }
1367
1368 list<string>
1369 Config::templates () const
1370 {
1371         if (!boost::filesystem::exists (path ("templates"))) {
1372                 return list<string> ();
1373         }
1374
1375         list<string> n;
1376         for (boost::filesystem::directory_iterator i (path("templates")); i != boost::filesystem::directory_iterator(); ++i) {
1377                 n.push_back (i->path().filename().string());
1378         }
1379         return n;
1380 }
1381
1382 bool
1383 Config::existing_template (string name) const
1384 {
1385         return boost::filesystem::exists (template_path (name));
1386 }
1387
1388 boost::filesystem::path
1389 Config::template_path (string name) const
1390 {
1391         return path("templates") / tidy_for_filename (name);
1392 }
1393
1394 void
1395 Config::rename_template (string old_name, string new_name) const
1396 {
1397         boost::filesystem::rename (template_path (old_name), template_path (new_name));
1398 }
1399
1400 void
1401 Config::delete_template (string name) const
1402 {
1403         boost::filesystem::remove (template_path (name));
1404 }
1405
1406 /** @return Path to the config.xml containing the actual settings, following a link if required */
1407 boost::filesystem::path
1408 Config::config_file ()
1409 {
1410         cxml::Document f ("Config");
1411         boost::filesystem::path main = path("config.xml", false);
1412         if (!boost::filesystem::exists (main)) {
1413                 /* It doesn't exist, so there can't be any links; just return it */
1414                 return main;
1415         }
1416
1417         /* See if there's a link */
1418         try {
1419                 f.read_file (main);
1420                 optional<string> link = f.optional_string_child("Link");
1421                 if (link) {
1422                         return *link;
1423                 }
1424         } catch (xmlpp::exception& e) {
1425                 /* There as a problem reading the main configuration file,
1426                    so there can't be a link.
1427                 */
1428         }
1429
1430         return main;
1431 }
1432
1433 void
1434 Config::reset_cover_sheet ()
1435 {
1436         set_cover_sheet_to_default ();
1437         changed ();
1438 }
1439
1440 void
1441 Config::link (boost::filesystem::path new_file) const
1442 {
1443         xmlpp::Document doc;
1444         doc.create_root_node("Config")->add_child("Link")->add_child_text(new_file.string());
1445         try {
1446                 doc.write_to_file_formatted(path("config.xml", true).string());
1447         } catch (xmlpp::exception& e) {
1448                 string s = e.what ();
1449                 trim (s);
1450                 throw FileError (s, path("config.xml"));
1451         }
1452 }
1453
1454 void
1455 Config::copy_and_link (boost::filesystem::path new_file) const
1456 {
1457         write ();
1458         boost::filesystem::copy_file (config_file(), new_file, boost::filesystem::copy_option::overwrite_if_exists);
1459         link (new_file);
1460 }
1461
1462 bool
1463 Config::have_write_permission () const
1464 {
1465         FILE* f = fopen_boost (config_file(), "r+");
1466         if (!f) {
1467                 return false;
1468         }
1469
1470         fclose (f);
1471         return true;
1472 }
1473
1474 /** @param  output_channels Number of output channels in use.
1475  *  @return Audio mapping for this output channel count (may be a default).
1476  */
1477 AudioMapping
1478 Config::audio_mapping (int output_channels)
1479 {
1480         if (!_audio_mapping || _audio_mapping->output_channels() != output_channels) {
1481                 /* Set up a default */
1482                 _audio_mapping = AudioMapping (MAX_DCP_AUDIO_CHANNELS, output_channels);
1483                 if (output_channels == 2) {
1484                         /* Special case for stereo output.
1485                            Map so that Lt = L(-3dB) + Ls(-3dB) + C(-6dB) + Lfe(-10dB)
1486                            Rt = R(-3dB) + Rs(-3dB) + C(-6dB) + Lfe(-10dB)
1487                         */
1488                         _audio_mapping->set (dcp::LEFT,   0, 1 / sqrt(2));  // L   -> Lt
1489                         _audio_mapping->set (dcp::RIGHT,  1, 1 / sqrt(2));  // R   -> Rt
1490                         _audio_mapping->set (dcp::CENTRE, 0, 1 / 2.0);      // C   -> Lt
1491                         _audio_mapping->set (dcp::CENTRE, 1, 1 / 2.0);      // C   -> Rt
1492                         _audio_mapping->set (dcp::LFE,    0, 1 / sqrt(10)); // Lfe -> Lt
1493                         _audio_mapping->set (dcp::LFE,    1, 1 / sqrt(10)); // Lfe -> Rt
1494                         _audio_mapping->set (dcp::LS,     0, 1 / sqrt(2));  // Ls  -> Lt
1495                         _audio_mapping->set (dcp::RS,     1, 1 / sqrt(2));  // Rs  -> Rt
1496                 } else {
1497                         /* 1:1 mapping */
1498                         for (int i = 0; i < min (MAX_DCP_AUDIO_CHANNELS, output_channels); ++i) {
1499                                 _audio_mapping->set (i, i, 1);
1500                         }
1501                 }
1502         }
1503
1504         return *_audio_mapping;
1505 }
1506
1507 void
1508 Config::set_audio_mapping (AudioMapping m)
1509 {
1510         _audio_mapping = m;
1511         changed (AUDIO_MAPPING);
1512 }
1513
1514 void
1515 Config::set_audio_mapping_to_default ()
1516 {
1517         DCPOMATIC_ASSERT (_audio_mapping);
1518         int const ch = _audio_mapping->output_channels ();
1519         _audio_mapping = boost::none;
1520         _audio_mapping = audio_mapping (ch);
1521         changed (AUDIO_MAPPING);
1522 }