Fix KDM target buttons for DKDMs too (#1137).
[dcpomatic.git] / src / lib / config.cc
1 /*
2     Copyright (C) 2012-2018 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 "cinema_sound_processor.h"
28 #include "colour_conversion.h"
29 #include "cinema.h"
30 #include "util.h"
31 #include "cross.h"
32 #include "film.h"
33 #include "dkdm_wrapper.h"
34 #include "compose.hpp"
35 #include <dcp/raw_convert.h>
36 #include <dcp/name_format.h>
37 #include <dcp/certificate_chain.h>
38 #include <libcxml/cxml.h>
39 #include <glib.h>
40 #include <libxml++/libxml++.h>
41 #include <boost/filesystem.hpp>
42 #include <boost/algorithm/string.hpp>
43 #include <boost/foreach.hpp>
44 #include <boost/thread.hpp>
45 #include <cstdlib>
46 #include <fstream>
47 #include <iostream>
48
49 #include "i18n.h"
50
51 using std::vector;
52 using std::cout;
53 using std::ifstream;
54 using std::string;
55 using std::list;
56 using std::max;
57 using std::remove;
58 using std::exception;
59 using std::cerr;
60 using boost::shared_ptr;
61 using boost::optional;
62 using boost::dynamic_pointer_cast;
63 using boost::algorithm::trim;
64 using dcp::raw_convert;
65
66 Config* Config::_instance = 0;
67 boost::signals2::signal<void ()> Config::FailedToLoad;
68 boost::signals2::signal<void (string)> Config::Warning;
69 boost::optional<boost::filesystem::path> Config::test_path;
70
71 /** Construct default configuration */
72 Config::Config ()
73         /* DKDMs are not considered a thing to reset on set_defaults() */
74         : _dkdms (new DKDMGroup ("root"))
75 {
76         set_defaults ();
77 }
78
79 void
80 Config::set_defaults ()
81 {
82         _master_encoding_threads = max (2U, boost::thread::hardware_concurrency ());
83         _server_encoding_threads = max (2U, boost::thread::hardware_concurrency ());
84         _server_port_base = 6192;
85         _use_any_servers = true;
86         _servers.clear ();
87         _only_servers_encode = false;
88         _tms_protocol = PROTOCOL_SCP;
89         _tms_ip = "";
90         _tms_path = ".";
91         _tms_user = "";
92         _tms_password = "";
93         _cinema_sound_processor = CinemaSoundProcessor::from_id (N_("dolby_cp750"));
94         _allow_any_dcp_frame_rate = false;
95         _language = optional<string> ();
96         _default_still_length = 10;
97         _default_container = Ratio::from_id ("185");
98         _default_scale_to = 0;
99         _default_dcp_content_type = DCPContentType::from_isdcf_name ("FTR");
100         _default_dcp_audio_channels = 6;
101         _default_j2k_bandwidth = 100000000;
102         _default_audio_delay = 0;
103         _default_interop = true;
104         _default_upload_after_make_dcp = false;
105         _mail_server = "";
106         _mail_port = 25;
107         _mail_user = "";
108         _mail_password = "";
109         _kdm_from = "";
110         _kdm_cc.clear ();
111         _kdm_bcc = "";
112         _check_for_updates = false;
113         _check_for_test_updates = false;
114         _maximum_j2k_bandwidth = 250000000;
115         _log_types = LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR;
116         _analyse_ebur128 = true;
117         _automatic_audio_analysis = false;
118 #ifdef DCPOMATIC_WINDOWS
119         _win32_console = false;
120 #endif
121         _cinemas_file = path ("cinemas.xml");
122         _show_hints_before_make_dcp = true;
123         _confirm_kdm_email = true;
124         _kdm_container_name_format = dcp::NameFormat ("KDM %f %c");
125         _kdm_filename_format = dcp::NameFormat ("KDM %f %c %s");
126         _dcp_metadata_filename_format = dcp::NameFormat ("%t");
127         _dcp_asset_filename_format = dcp::NameFormat ("%t");
128         _jump_to_selected = true;
129         for (int i = 0; i < NAG_COUNT; ++i) {
130                 _nagged[i] = false;
131         }
132         _sound = true;
133         _sound_output = optional<string> ();
134         _last_kdm_write_type = KDM_WRITE_FLAT;
135         _last_dkdm_write_type = DKDM_WRITE_INTERNAL;
136
137         /* I think the scaling factor here should be the ratio of the longest frame
138            encode time to the shortest; if the thread count is T, longest time is L
139            and the shortest time S we could encode L/S frames per thread whilst waiting
140            for the L frame to encode so we might have to store LT/S frames.
141
142            However we don't want to use too much memory, so keep it a bit lower than we'd
143            perhaps like.  A J2K frame is typically about 1Mb so 3 here will mean we could
144            use about 240Mb with 72 encoding threads.
145         */
146         _frames_in_memory_multiplier = 3;
147
148         _allowed_dcp_frame_rates.clear ();
149         _allowed_dcp_frame_rates.push_back (24);
150         _allowed_dcp_frame_rates.push_back (25);
151         _allowed_dcp_frame_rates.push_back (30);
152         _allowed_dcp_frame_rates.push_back (48);
153         _allowed_dcp_frame_rates.push_back (50);
154         _allowed_dcp_frame_rates.push_back (60);
155
156         set_kdm_email_to_default ();
157         set_cover_sheet_to_default ();
158 }
159
160 void
161 Config::restore_defaults ()
162 {
163         Config::instance()->set_defaults ();
164         Config::instance()->changed ();
165 }
166
167 shared_ptr<dcp::CertificateChain>
168 Config::create_certificate_chain ()
169 {
170         return shared_ptr<dcp::CertificateChain> (
171                 new dcp::CertificateChain (
172                         openssl_path(),
173                         "dcpomatic.com",
174                         "dcpomatic.com",
175                         ".dcpomatic.smpte-430-2.ROOT",
176                         ".dcpomatic.smpte-430-2.INTERMEDIATE",
177                         "CS.dcpomatic.smpte-430-2.LEAF"
178                         )
179                 );
180 }
181
182 void
183 Config::read ()
184 try
185 {
186         cxml::Document f ("Config");
187         f.read_file (config_file ());
188
189         optional<int> version = f.optional_number_child<int> ("Version");
190
191         if (f.optional_number_child<int>("NumLocalEncodingThreads")) {
192                 _master_encoding_threads = _server_encoding_threads = f.optional_number_child<int>("NumLocalEncodingThreads").get();
193         } else {
194                 _master_encoding_threads = f.number_child<int>("MasterEncodingThreads");
195                 _server_encoding_threads = f.number_child<int>("ServerEncodingThreads");
196         }
197
198         _default_directory = f.optional_string_child ("DefaultDirectory");
199         if (_default_directory && _default_directory->empty ()) {
200                 /* We used to store an empty value for this to mean "none set" */
201                 _default_directory = boost::optional<boost::filesystem::path> ();
202         }
203
204         boost::optional<int> b = f.optional_number_child<int> ("ServerPort");
205         if (!b) {
206                 b = f.optional_number_child<int> ("ServerPortBase");
207         }
208         _server_port_base = b.get ();
209
210         boost::optional<bool> u = f.optional_bool_child ("UseAnyServers");
211         _use_any_servers = u.get_value_or (true);
212
213         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("Server")) {
214                 if (i->node_children("HostName").size() == 1) {
215                         _servers.push_back (i->string_child ("HostName"));
216                 } else {
217                         _servers.push_back (i->content ());
218                 }
219         }
220
221         _only_servers_encode = f.optional_bool_child ("OnlyServersEncode").get_value_or (false);
222         _tms_protocol = static_cast<Protocol> (f.optional_number_child<int> ("TMSProtocol").get_value_or (static_cast<int> (PROTOCOL_SCP)));
223         _tms_ip = f.string_child ("TMSIP");
224         _tms_path = f.string_child ("TMSPath");
225         _tms_user = f.string_child ("TMSUser");
226         _tms_password = f.string_child ("TMSPassword");
227
228         optional<string> c;
229         c = f.optional_string_child ("SoundProcessor");
230         if (c) {
231                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
232         }
233         c = f.optional_string_child ("CinemaSoundProcessor");
234         if (c) {
235                 _cinema_sound_processor = CinemaSoundProcessor::from_id (c.get ());
236         }
237
238         _language = f.optional_string_child ("Language");
239
240         c = f.optional_string_child ("DefaultContainer");
241         if (c) {
242                 _default_container = Ratio::from_id (c.get ());
243         }
244
245         if (_default_container && !_default_container->used_for_container()) {
246                 Warning (_("Your default container is not valid and has been changed to Flat (1.85:1)"));
247                 _default_container = Ratio::from_id ("185");
248         }
249
250         c = f.optional_string_child ("DefaultScaleTo");
251         if (c) {
252                 _default_scale_to = Ratio::from_id (c.get ());
253         }
254
255         c = f.optional_string_child ("DefaultDCPContentType");
256         if (c) {
257                 _default_dcp_content_type = DCPContentType::from_isdcf_name (c.get ());
258         }
259
260         _default_dcp_audio_channels = f.optional_number_child<int>("DefaultDCPAudioChannels").get_value_or (6);
261
262         if (f.optional_string_child ("DCPMetadataIssuer")) {
263                 _dcp_issuer = f.string_child ("DCPMetadataIssuer");
264         } else if (f.optional_string_child ("DCPIssuer")) {
265                 _dcp_issuer = f.string_child ("DCPIssuer");
266         }
267
268         _default_upload_after_make_dcp = f.optional_bool_child("DefaultUploadAfterMakeDCP").get_value_or (false);
269         _dcp_creator = f.optional_string_child ("DCPCreator").get_value_or ("");
270
271         if (version && version.get() >= 2) {
272                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("ISDCFMetadata"));
273         } else {
274                 _default_isdcf_metadata = ISDCFMetadata (f.node_child ("DCIMetadata"));
275         }
276
277         _default_still_length = f.optional_number_child<int>("DefaultStillLength").get_value_or (10);
278         _default_j2k_bandwidth = f.optional_number_child<int>("DefaultJ2KBandwidth").get_value_or (200000000);
279         _default_audio_delay = f.optional_number_child<int>("DefaultAudioDelay").get_value_or (0);
280         _default_interop = f.optional_bool_child("DefaultInterop").get_value_or (false);
281         _default_kdm_directory = f.optional_string_child("DefaultKDMDirectory");
282
283         /* Load any cinemas from config.xml */
284         read_cinemas (f);
285
286         _mail_server = f.string_child ("MailServer");
287         _mail_port = f.optional_number_child<int> ("MailPort").get_value_or (25);
288         _mail_user = f.optional_string_child("MailUser").get_value_or ("");
289         _mail_password = f.optional_string_child("MailPassword").get_value_or ("");
290         _kdm_subject = f.optional_string_child ("KDMSubject").get_value_or (_("KDM delivery: $CPL_NAME"));
291         _kdm_from = f.string_child ("KDMFrom");
292         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("KDMCC")) {
293                 if (!i->content().empty()) {
294                         _kdm_cc.push_back (i->content ());
295                 }
296         }
297         _kdm_bcc = f.optional_string_child ("KDMBCC").get_value_or ("");
298         _kdm_email = f.string_child ("KDMEmail");
299
300         _check_for_updates = f.optional_bool_child("CheckForUpdates").get_value_or (false);
301         _check_for_test_updates = f.optional_bool_child("CheckForTestUpdates").get_value_or (false);
302
303         _maximum_j2k_bandwidth = f.optional_number_child<int> ("MaximumJ2KBandwidth").get_value_or (250000000);
304         _allow_any_dcp_frame_rate = f.optional_bool_child ("AllowAnyDCPFrameRate").get_value_or (false);
305
306         _log_types = f.optional_number_child<int> ("LogTypes").get_value_or (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR);
307         _analyse_ebur128 = f.optional_bool_child("AnalyseEBUR128").get_value_or (true);
308         _automatic_audio_analysis = f.optional_bool_child ("AutomaticAudioAnalysis").get_value_or (false);
309 #ifdef DCPOMATIC_WINDOWS
310         _win32_console = f.optional_bool_child ("Win32Console").get_value_or (false);
311 #endif
312
313         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("History")) {
314                 _history.push_back (i->content ());
315         }
316
317         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("PlayerHistory")) {
318                 _player_history.push_back (i->content ());
319         }
320
321         cxml::NodePtr signer = f.optional_node_child ("Signer");
322         if (signer) {
323                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
324                 /* Read the signing certificates and private key in from the config file */
325                 BOOST_FOREACH (cxml::NodePtr i, signer->node_children ("Certificate")) {
326                         c->add (dcp::Certificate (i->content ()));
327                 }
328                 c->set_key (signer->string_child ("PrivateKey"));
329                 _signer_chain = c;
330         } else {
331                 /* Make a new set of signing certificates and key */
332                 _signer_chain = create_certificate_chain ();
333         }
334
335         cxml::NodePtr decryption = f.optional_node_child ("Decryption");
336         if (decryption) {
337                 shared_ptr<dcp::CertificateChain> c (new dcp::CertificateChain ());
338                 BOOST_FOREACH (cxml::NodePtr i, decryption->node_children ("Certificate")) {
339                         c->add (dcp::Certificate (i->content ()));
340                 }
341                 c->set_key (decryption->string_child ("PrivateKey"));
342                 _decryption_chain = c;
343         } else {
344                 _decryption_chain = create_certificate_chain ();
345         }
346
347         if (f.optional_node_child("DKDMGroup")) {
348                 /* New-style: all DKDMs in a group */
349                 _dkdms = dynamic_pointer_cast<DKDMGroup> (DKDMBase::read (f.node_child("DKDMGroup")));
350         } else {
351                 /* Old-style: one or more DKDM nodes */
352                 _dkdms.reset (new DKDMGroup ("root"));
353                 BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("DKDM")) {
354                         _dkdms->add (DKDMBase::read (i));
355                 }
356         }
357         _cinemas_file = f.optional_string_child("CinemasFile").get_value_or (path ("cinemas.xml").string ());
358         _show_hints_before_make_dcp = f.optional_bool_child("ShowHintsBeforeMakeDCP").get_value_or (true);
359         _confirm_kdm_email = f.optional_bool_child("ConfirmKDMEmail").get_value_or (true);
360         _kdm_container_name_format = dcp::NameFormat (f.optional_string_child("KDMContainerNameFormat").get_value_or ("KDM %f %c"));
361         _kdm_filename_format = dcp::NameFormat (f.optional_string_child("KDMFilenameFormat").get_value_or ("KDM %f %c %s"));
362         _dcp_metadata_filename_format = dcp::NameFormat (f.optional_string_child("DCPMetadataFilenameFormat").get_value_or ("%t"));
363         _dcp_asset_filename_format = dcp::NameFormat (f.optional_string_child("DCPAssetFilenameFormat").get_value_or ("%t"));
364         _jump_to_selected = f.optional_bool_child("JumpToSelected").get_value_or (true);
365         BOOST_FOREACH (cxml::NodePtr i, f.node_children("Nagged")) {
366                 int const id = i->number_attribute<int>("Id");
367                 if (id >= 0 && id < NAG_COUNT) {
368                         _nagged[id] = raw_convert<int>(i->content());
369                 }
370         }
371         /* The variable was renamed but not the XML tag */
372         _sound = f.optional_bool_child("PreviewSound").get_value_or (true);
373         _sound_output = f.optional_string_child("PreviewSoundOutput");
374         if (f.optional_string_child("CoverSheet")) {
375                 _cover_sheet = f.optional_string_child("CoverSheet").get();
376         }
377         _last_player_load_directory = f.optional_string_child("LastPlayerLoadDirectory");
378         if (f.optional_string_child("LastKDMWriteType")) {
379                 if (f.optional_string_child("LastKDMWriteType").get() == "flat") {
380                         _last_kdm_write_type = KDM_WRITE_FLAT;
381                 } else if (f.optional_string_child("LastKDMWriteType").get() == "folder") {
382                         _last_kdm_write_type = KDM_WRITE_FOLDER;
383                 } else if (f.optional_string_child("LastKDMWriteType").get() == "zip") {
384                         _last_kdm_write_type = KDM_WRITE_ZIP;
385                 }
386         }
387         if (f.optional_string_child("LastDKDMWriteType")) {
388                 if (f.optional_string_child("LastDKDMWriteType").get() == "internal") {
389                         _last_dkdm_write_type = DKDM_WRITE_INTERNAL;
390                 } else if (f.optional_string_child("LastDKDMWriteType").get() == "file") {
391                         _last_dkdm_write_type = DKDM_WRITE_FILE;
392                 }
393         }
394         _frames_in_memory_multiplier = f.optional_number_child<int>("FramesInMemoryMultiplier").get_value_or(3);
395
396         /* Replace any cinemas from config.xml with those from the configured file */
397         if (boost::filesystem::exists (_cinemas_file)) {
398                 cxml::Document f ("Cinemas");
399                 f.read_file (_cinemas_file);
400                 read_cinemas (f);
401         }
402 }
403 catch (...) {
404         if (have_existing ("config.xml")) {
405
406                 /* Make a copy of the configuration */
407                 try {
408                         int n = 1;
409                         while (n < 100 && boost::filesystem::exists(path(String::compose("config.xml.%1", n)))) {
410                                 ++n;
411                         }
412
413                         boost::filesystem::copy_file(path("config.xml", false), path(String::compose("config.xml.%1", n), false));
414                         boost::filesystem::copy_file(path("cinemas.xml", false), path(String::compose("cinemas.xml.%1", n), false));
415                 } catch (...) {}
416
417                 /* We have a config file but it didn't load */
418                 FailedToLoad ();
419         }
420         set_defaults ();
421         /* Make a new set of signing certificates and key */
422         _signer_chain = create_certificate_chain ();
423         /* And similar for decryption of KDMs */
424         _decryption_chain = create_certificate_chain ();
425         write ();
426 }
427
428 /** @return Filename to write configuration to */
429 boost::filesystem::path
430 Config::path (string file, bool create_directories)
431 {
432         boost::filesystem::path p;
433         if (test_path) {
434                 p = test_path.get();
435         } else {
436 #ifdef DCPOMATIC_OSX
437                 p /= g_get_home_dir ();
438                 p /= "Library";
439                 p /= "Preferences";
440                 p /= "com.dcpomatic";
441                 p /= "2";
442 #else
443                 p /= g_get_user_config_dir ();
444                 p /= "dcpomatic2";
445 #endif
446         }
447         boost::system::error_code ec;
448         if (create_directories) {
449                 boost::filesystem::create_directories (p, ec);
450         }
451         p /= file;
452         return p;
453 }
454
455 /** @return Singleton instance */
456 Config *
457 Config::instance ()
458 {
459         if (_instance == 0) {
460                 _instance = new Config;
461                 _instance->read ();
462         }
463
464         return _instance;
465 }
466
467 /** Write our configuration to disk */
468 void
469 Config::write () const
470 {
471         write_config ();
472         write_cinemas ();
473 }
474
475 void
476 Config::write_config () const
477 {
478         xmlpp::Document doc;
479         xmlpp::Element* root = doc.create_root_node ("Config");
480
481         /* [XML] Version The version number of the configuration file format; currently 2. */
482         root->add_child("Version")->add_child_text ("2");
483         /* [XML] MasterEncodingThreads Number of encoding threads to use when running as master. */
484         root->add_child("MasterEncodingThreads")->add_child_text (raw_convert<string> (_master_encoding_threads));
485         /* [XML] ServerEncodingThreads Number of encoding threads to use when running as server. */
486         root->add_child("ServerEncodingThreads")->add_child_text (raw_convert<string> (_server_encoding_threads));
487         if (_default_directory) {
488                 /* [XML:opt] DefaultDirectory Default directory when creating a new film in the GUI. */
489                 root->add_child("DefaultDirectory")->add_child_text (_default_directory->string ());
490         }
491         /* [XML] ServerPortBase Port number to use for frame encoding requests.  <code>ServerPortBase</code> + 1 and
492            <code>ServerPortBase</code> + 2 are used for querying servers.  <code>ServerPortBase</code> + 3 is used
493            by the batch converter to listen for job requests.
494         */
495         root->add_child("ServerPortBase")->add_child_text (raw_convert<string> (_server_port_base));
496         /* [XML] UseAnyServers 1 to broadcast to look for encoding servers to use, 0 to use only those configured. */
497         root->add_child("UseAnyServers")->add_child_text (_use_any_servers ? "1" : "0");
498
499         BOOST_FOREACH (string i, _servers) {
500                 /* [XML:opt] Server IP address or hostname of an encoding server to use; you can use as many of these tags
501                    as you like.
502                 */
503                 root->add_child("Server")->add_child_text (i);
504         }
505
506         /* [XML] OnlyServersEncode 1 to set the master to do decoding of source content no JPEG2000 encoding; all encoding
507            is done by the encoding servers.  0 to set the master to do some encoding as well as coordinating the job.
508         */
509         root->add_child("OnlyServersEncode")->add_child_text (_only_servers_encode ? "1" : "0");
510         /* [XML] TMSProtocol Protocol to use to copy files to a TMS; 0 to use SCP, 1 for FTP. */
511         root->add_child("TMSProtocol")->add_child_text (raw_convert<string> (static_cast<int> (_tms_protocol)));
512         /* [XML] TMSIP IP address of TMS */
513         root->add_child("TMSIP")->add_child_text (_tms_ip);
514         /* [XML] TMSPath Path on the TMS to copy files to */
515         root->add_child("TMSPath")->add_child_text (_tms_path);
516         /* [XML] TMSUser Username to log into the TMS with */
517         root->add_child("TMSUser")->add_child_text (_tms_user);
518         /* [XML] TMSPassword Password to log into the TMS with */
519         root->add_child("TMSPassword")->add_child_text (_tms_password);
520         if (_cinema_sound_processor) {
521                 /* [XML:opt] CinemaSoundProcessor Identifier of the type of cinema sound processor to use when calculating
522                    gain changes from fader positions.  Currently can only be <code>dolby_cp750</code>.
523                 */
524                 root->add_child("CinemaSoundProcessor")->add_child_text (_cinema_sound_processor->id ());
525         }
526         if (_language) {
527                 /* [XML:opt] Language Language to use in the GUI e.g. <code>fr_FR</code>. */
528                 root->add_child("Language")->add_child_text (_language.get());
529         }
530         if (_default_container) {
531                 /* [XML:opt] DefaultContainer ID of default container
532                  * to use when creating new films (<code>185</code>,<code>239</code> or
533                  * <code>190</code>).
534                 */
535                 root->add_child("DefaultContainer")->add_child_text (_default_container->id ());
536         }
537         if (_default_scale_to) {
538                 /* [XML:opt] DefaultScaleTo ID of default ratio to scale content to when creating new films
539                    (see <code>DefaultContainer</code> for IDs).
540                 */
541                 root->add_child("DefaultScaleTo")->add_child_text (_default_scale_to->id ());
542         }
543         if (_default_dcp_content_type) {
544                 /* [XML:opt] DefaultDCPContentType Default content type ot use when creating new films (<code>FTR</code>, <code>SHR</code>,
545                    <code>TLR</code>, <code>TST</code>, <code>XSN</code>, <code>RTG</code>, <code>TSR</code>, <code>POL</code>,
546                    <code>PSA</code> or <code>ADV</code>). */
547                 root->add_child("DefaultDCPContentType")->add_child_text (_default_dcp_content_type->isdcf_name ());
548         }
549         /* [XML] DefaultDCPAudioChannels Default number of audio channels to use when creating new films. */
550         root->add_child("DefaultDCPAudioChannels")->add_child_text (raw_convert<string> (_default_dcp_audio_channels));
551         /* [XML] DCPIssuer Issuer text to write into CPL files. */
552         root->add_child("DCPIssuer")->add_child_text (_dcp_issuer);
553         /* [XML] DCPIssuer Creator text to write into CPL files. */
554         root->add_child("DCPCreator")->add_child_text (_dcp_creator);
555         root->add_child("DefaultUploadAfterMakeDCP")->add_child_text (_default_upload_after_make_dcp ? "1" : "0");
556
557         /* [XML] ISDCFMetadata Default ISDCF metadata to use for new films; child tags are <code>&lt;ContentVersion&gt;</code>,
558            <code>&lt;AudioLanguage&gt;</code>, <code>&lt;SubtitleLanguage&gt;</code>, <code>&lt;Territory&gt;</code>,
559            <code>&lt;Rating&gt;</code>, <code>&lt;Studio&gt;</code>, <code>&lt;Facility&gt;</code>, <code>&lt;TempVersion&gt;</code>,
560            <code>&lt;PreRelease&gt;</code>, <code>&lt;RedBand&gt;</code>, <code>&lt;Chain&gt;</code>, <code>&lt;TwoDVersionOFThreeD&gt;</code>,
561            <code>&lt;MasteredLuminance&gt;</code>.
562         */
563         _default_isdcf_metadata.as_xml (root->add_child ("ISDCFMetadata"));
564
565         /* [XML] DefaultStillLength Default length (in seconds) for still images in new films. */
566         root->add_child("DefaultStillLength")->add_child_text (raw_convert<string> (_default_still_length));
567         /* [XML] DefaultJ2KBandwidth Default bitrate (in bits per second) for JPEG2000 data in new films. */
568         root->add_child("DefaultJ2KBandwidth")->add_child_text (raw_convert<string> (_default_j2k_bandwidth));
569         /* [XML] DefaultAudioDelay Default delay to apply to audio (positive moves audio later) in milliseconds. */
570         root->add_child("DefaultAudioDelay")->add_child_text (raw_convert<string> (_default_audio_delay));
571         /* [XML] DefaultInterop 1 to default new films to Interop, 0 for SMPTE. */
572         root->add_child("DefaultInterop")->add_child_text (_default_interop ? "1" : "0");
573         if (_default_kdm_directory) {
574                 /* [XML:opt] DefaultKDMDirectory Default directory to write KDMs to. */
575                 root->add_child("DefaultKDMDirectory")->add_child_text (_default_kdm_directory->string ());
576         }
577         /* [XML] MailServer Hostname of SMTP server to use. */
578         root->add_child("MailServer")->add_child_text (_mail_server);
579         /* [XML] MailPort Port number to use on SMTP server. */
580         root->add_child("MailPort")->add_child_text (raw_convert<string> (_mail_port));
581         /* [XML] MailUser Username to use on SMTP server. */
582         root->add_child("MailUser")->add_child_text (_mail_user);
583         /* [XML] MailPassword Password to use on SMTP server. */
584         root->add_child("MailPassword")->add_child_text (_mail_password);
585         /* [XML] KDMSubject Subject to use for KDM emails. */
586         root->add_child("KDMSubject")->add_child_text (_kdm_subject);
587         /* [XML] KDMFrom From address to use for KDM emails. */
588         root->add_child("KDMFrom")->add_child_text (_kdm_from);
589         BOOST_FOREACH (string i, _kdm_cc) {
590                 /* [XML] KDMCC CC address to use for KDM emails; you can use as many of these tags as you like. */
591                 root->add_child("KDMCC")->add_child_text (i);
592         }
593         /* [XML] KDMBCC BCC address to use for KDM emails */
594         root->add_child("KDMBCC")->add_child_text (_kdm_bcc);
595         /* [XML] KDMEmail Text of KDM email */
596         root->add_child("KDMEmail")->add_child_text (_kdm_email);
597
598         /* [XML] CheckForUpdates 1 to check dcpomatic.com for new versions, 0 to check only on request */
599         root->add_child("CheckForUpdates")->add_child_text (_check_for_updates ? "1" : "0");
600         /* [XML] CheckForUpdates 1 to check dcpomatic.com for new text versions, 0 to check only on request */
601         root->add_child("CheckForTestUpdates")->add_child_text (_check_for_test_updates ? "1" : "0");
602
603         /* [XML] MaximumJ2KBandwidth Maximum J2K bandwidth (in bits per second) that can be specified in the GUI */
604         root->add_child("MaximumJ2KBandwidth")->add_child_text (raw_convert<string> (_maximum_j2k_bandwidth));
605         /* [XML] AllowAnyDCPFrameRate 1 to allow users to specify any frame rate when creating DCPs, 0 to limit the GUI to standard rates */
606         root->add_child("AllowAnyDCPFrameRate")->add_child_text (_allow_any_dcp_frame_rate ? "1" : "0");
607         /* [XML] LogTypes Types of logging to write; a bitfield where 1 is general notes, 2 warnings, 4 errors, 8 debug information related
608            to encoding, 16 debug information related to encoding, 32 debug information for timing purposes, 64 debug information related
609            to sending email.
610         */
611         root->add_child("LogTypes")->add_child_text (raw_convert<string> (_log_types));
612         /* [XML] AnalyseEBUR128 1 to do EBUR128 analyses when analysing audio, otherwise 0. */
613         root->add_child("AnalyseEBUR128")->add_child_text (_analyse_ebur128 ? "1" : "0");
614         /* [XML] AutomaticAudioAnalysis 1 to run audio analysis automatically when audio content is added to the film, otherwise 0. */
615         root->add_child("AutomaticAudioAnalysis")->add_child_text (_automatic_audio_analysis ? "1" : "0");
616 #ifdef DCPOMATIC_WINDOWS
617         /* [XML] Win32Console 1 to open a console when running on Windows, otherwise 0. */
618         root->add_child("Win32Console")->add_child_text (_win32_console ? "1" : "0");
619 #endif
620
621         /* [XML] Signer Certificate chain and private key to use when signing DCPs and KDMs.  Should contain <code>&lt;Certificate&gt;</code>
622            tags in order and a <code>&lt;PrivateKey&gt;</code> tag all containing PEM-encoded certificates or private keys as appropriate.
623         */
624         xmlpp::Element* signer = root->add_child ("Signer");
625         DCPOMATIC_ASSERT (_signer_chain);
626         BOOST_FOREACH (dcp::Certificate const & i, _signer_chain->unordered()) {
627                 signer->add_child("Certificate")->add_child_text (i.certificate (true));
628         }
629         signer->add_child("PrivateKey")->add_child_text (_signer_chain->key().get ());
630
631         /* [XML] Decryption Certificate chain and private key to use when decrypting KDMs */
632         xmlpp::Element* decryption = root->add_child ("Decryption");
633         DCPOMATIC_ASSERT (_decryption_chain);
634         BOOST_FOREACH (dcp::Certificate const & i, _decryption_chain->unordered()) {
635                 decryption->add_child("Certificate")->add_child_text (i.certificate (true));
636         }
637         decryption->add_child("PrivateKey")->add_child_text (_decryption_chain->key().get ());
638
639         /* [XML] History Filename of DCP to present in the <guilabel>File</guilabel> menu of the GUI; there can be more than one
640            of these tags.
641         */
642         BOOST_FOREACH (boost::filesystem::path i, _history) {
643                 root->add_child("History")->add_child_text (i.string ());
644         }
645
646         BOOST_FOREACH (boost::filesystem::path i, _player_history) {
647                 root->add_child("PlayerHistory")->add_child_text (i.string ());
648         }
649
650         /* [XML] DKDMGroup A group of DKDMs, each with a <code>Name</code> attribute, containing other <code>&lt;DKDMGroup&gt;</code>
651            or <code>&lt;DKDM&gt;</code> tags.
652         */
653         /* [XML] DKDM A DKDM as XML */
654         _dkdms->as_xml (root);
655
656         /* [XML] CinemasFile Filename of cinemas list file */
657         root->add_child("CinemasFile")->add_child_text (_cinemas_file.string());
658         /* [XML] ShowHintsBeforeMakeDCP 1 to show hints in the GUI before making a DCP, otherwise 0 */
659         root->add_child("ShowHintsBeforeMakeDCP")->add_child_text (_show_hints_before_make_dcp ? "1" : "0");
660         /* [XML] ConfirmKDMEmail 1 to confirm before sending KDM emails in the GUI, otherwise 0 */
661         root->add_child("ConfirmKDMEmail")->add_child_text (_confirm_kdm_email ? "1" : "0");
662         /* [XML] KDMFilenameFormat Format for KDM filenames */
663         root->add_child("KDMFilenameFormat")->add_child_text (_kdm_filename_format.specification ());
664         /* [XML] KDMContainerNameFormat Format for KDM containers (directories or ZIP files) */
665         root->add_child("KDMContainerNameFormat")->add_child_text (_kdm_container_name_format.specification ());
666         /* [XML] DCPMetadataFilenameFormat Format for DCP metadata filenames */
667         root->add_child("DCPMetadataFilenameFormat")->add_child_text (_dcp_metadata_filename_format.specification ());
668         /* [XML] DCPAssetFilenameFormat Format for DCP asset filenames */
669         root->add_child("DCPAssetFilenameFormat")->add_child_text (_dcp_asset_filename_format.specification ());
670         /* [XML] JumpToSelected 1 to make the GUI jump to the start of content when it is selected, otherwise 0 */
671         root->add_child("JumpToSelected")->add_child_text (_jump_to_selected ? "1" : "0");
672         /* [XML] Nagged 1 if a particular nag screen has been shown and should not be shown again, otherwise 0 */
673         for (int i = 0; i < NAG_COUNT; ++i) {
674                 xmlpp::Element* e = root->add_child ("Nagged");
675                 e->set_attribute ("Id", raw_convert<string>(i));
676                 e->add_child_text (_nagged[i] ? "1" : "0");
677         }
678         /* [XML] PreviewSound 1 to use sound in the GUI preview and player, otherwise 0 */
679         root->add_child("PreviewSound")->add_child_text (_sound ? "1" : "0");
680         if (_sound_output) {
681                 /* [XML:opt] PreviewSoundOutput Name of the audio output to use */
682                 root->add_child("PreviewSoundOutput")->add_child_text (_sound_output.get());
683         }
684         /* [XML] CoverSheet Text of the cover sheet to write when making DCPs */
685         root->add_child("CoverSheet")->add_child_text (_cover_sheet);
686         if (_last_player_load_directory) {
687                 root->add_child("LastPlayerLoadDirectory")->add_child_text(_last_player_load_directory->string());
688         }
689         if (_last_kdm_write_type) {
690                 switch (_last_kdm_write_type.get()) {
691                 case KDM_WRITE_FLAT:
692                         root->add_child("LastKDMWriteType")->add_child_text("flat");
693                         break;
694                 case KDM_WRITE_FOLDER:
695                         root->add_child("LastKDMWriteType")->add_child_text("folder");
696                         break;
697                 case KDM_WRITE_ZIP:
698                         root->add_child("LastKDMWriteType")->add_child_text("zip");
699                         break;
700                 }
701         }
702         if (_last_dkdm_write_type) {
703                 switch (_last_dkdm_write_type.get()) {
704                 case DKDM_WRITE_INTERNAL:
705                         root->add_child("LastDKDMWriteType")->add_child_text("internal");
706                         break;
707                 case DKDM_WRITE_FILE:
708                         root->add_child("LastDKDMWriteType")->add_child_text("file");
709                         break;
710                 }
711         }
712         /* [XML] FramesInMemoryMultiplier value to multiply the encoding threads count by to get the maximum number of
713            frames to be held in memory at once.
714         */
715         root->add_child("FramesInMemoryMultiplier")->add_child_text(raw_convert<string>(_frames_in_memory_multiplier));
716
717         try {
718                 doc.write_to_file_formatted(config_file().string());
719         } catch (xmlpp::exception& e) {
720                 string s = e.what ();
721                 trim (s);
722                 throw FileError (s, path("config.xml"));
723         }
724 }
725
726 void
727 Config::write_cinemas () const
728 {
729         xmlpp::Document doc;
730         xmlpp::Element* root = doc.create_root_node ("Cinemas");
731         root->add_child("Version")->add_child_text ("1");
732
733         BOOST_FOREACH (shared_ptr<Cinema> i, _cinemas) {
734                 i->as_xml (root->add_child ("Cinema"));
735         }
736
737         try {
738                 doc.write_to_file_formatted (_cinemas_file.string ());
739         } catch (xmlpp::exception& e) {
740                 string s = e.what ();
741                 trim (s);
742                 throw FileError (s, _cinemas_file);
743         }
744 }
745
746 boost::filesystem::path
747 Config::default_directory_or (boost::filesystem::path a) const
748 {
749         return directory_or (_default_directory, a);
750 }
751
752 boost::filesystem::path
753 Config::default_kdm_directory_or (boost::filesystem::path a) const
754 {
755         return directory_or (_default_kdm_directory, a);
756 }
757
758 boost::filesystem::path
759 Config::directory_or (optional<boost::filesystem::path> dir, boost::filesystem::path a) const
760 {
761         if (!dir) {
762                 return a;
763         }
764
765         boost::system::error_code ec;
766         bool const e = boost::filesystem::exists (*dir, ec);
767         if (ec || !e) {
768                 return a;
769         }
770
771         return *dir;
772 }
773
774 void
775 Config::drop ()
776 {
777         delete _instance;
778         _instance = 0;
779 }
780
781 void
782 Config::changed (Property what)
783 {
784         Changed (what);
785 }
786
787 void
788 Config::set_kdm_email_to_default ()
789 {
790         _kdm_subject = _("KDM delivery: $CPL_NAME");
791
792         _kdm_email = _(
793                 "Dear Projectionist\n\n"
794                 "Please find attached KDMs for $CPL_NAME.\n\n"
795                 "Cinema: $CINEMA_NAME\n"
796                 "Screen(s): $SCREENS\n\n"
797                 "The KDMs are valid from $START_TIME until $END_TIME.\n\n"
798                 "Best regards,\nDCP-o-matic"
799                 );
800 }
801
802 void
803 Config::reset_kdm_email ()
804 {
805         set_kdm_email_to_default ();
806         changed ();
807 }
808
809 void
810 Config::set_cover_sheet_to_default ()
811 {
812         _cover_sheet = _(
813                 "$CPL_NAME\n\n"
814                 "Type: $TYPE\n"
815                 "Format: $CONTAINER\n"
816                 "Audio: $AUDIO\n"
817                 "Audio Language: $AUDIO_LANGUAGE\n"
818                 "Subtitle Language: $SUBTITLE_LANGUAGE\n"
819                 "Length: $LENGTH\n"
820                 "Size: $SIZE\n"
821                 );
822 }
823
824 void
825 Config::add_to_history (boost::filesystem::path p)
826 {
827         add_to_history_internal (_history, p);
828 }
829
830 void
831 Config::add_to_player_history (boost::filesystem::path p)
832 {
833         add_to_history_internal (_player_history, p);
834 }
835
836 void
837 Config::add_to_history_internal (vector<boost::filesystem::path>& h, boost::filesystem::path p)
838 {
839         /* Remove existing instances of this path in the history */
840         h.erase (remove (h.begin(), h.end(), p), h.end ());
841
842         h.insert (h.begin (), p);
843         if (h.size() > HISTORY_SIZE) {
844                 h.pop_back ();
845         }
846
847         changed ();
848 }
849
850 bool
851 Config::have_existing (string file)
852 {
853         return boost::filesystem::exists (path (file, false));
854 }
855
856 void
857 Config::read_cinemas (cxml::Document const & f)
858 {
859         _cinemas.clear ();
860         list<cxml::NodePtr> cin = f.node_children ("Cinema");
861         BOOST_FOREACH (cxml::ConstNodePtr i, f.node_children("Cinema")) {
862                 /* Slightly grotty two-part construction of Cinema here so that we can use
863                    shared_from_this.
864                 */
865                 shared_ptr<Cinema> cinema (new Cinema (i));
866                 cinema->read_screens (i);
867                 _cinemas.push_back (cinema);
868         }
869 }
870
871 void
872 Config::set_cinemas_file (boost::filesystem::path file)
873 {
874         _cinemas_file = file;
875
876         if (boost::filesystem::exists (_cinemas_file)) {
877                 /* Existing file; read it in */
878                 cxml::Document f ("Cinemas");
879                 f.read_file (_cinemas_file);
880                 read_cinemas (f);
881         }
882
883         changed (OTHER);
884 }
885
886 void
887 Config::save_template (shared_ptr<const Film> film, string name) const
888 {
889         film->write_template (template_path (name));
890 }
891
892 list<string>
893 Config::templates () const
894 {
895         if (!boost::filesystem::exists (path ("templates"))) {
896                 return list<string> ();
897         }
898
899         list<string> n;
900         for (boost::filesystem::directory_iterator i (path("templates")); i != boost::filesystem::directory_iterator(); ++i) {
901                 n.push_back (i->path().filename().string());
902         }
903         return n;
904 }
905
906 bool
907 Config::existing_template (string name) const
908 {
909         return boost::filesystem::exists (template_path (name));
910 }
911
912 boost::filesystem::path
913 Config::template_path (string name) const
914 {
915         return path("templates") / tidy_for_filename (name);
916 }
917
918 void
919 Config::rename_template (string old_name, string new_name) const
920 {
921         boost::filesystem::rename (template_path (old_name), template_path (new_name));
922 }
923
924 void
925 Config::delete_template (string name) const
926 {
927         boost::filesystem::remove (template_path (name));
928 }
929
930 /** @return Path to the config.xml containing the actual settings, following a link if required */
931 boost::filesystem::path
932 Config::config_file ()
933 {
934         cxml::Document f ("Config");
935         boost::filesystem::path main = path("config.xml", false);
936         if (!boost::filesystem::exists (main)) {
937                 /* It doesn't exist, so there can't be any links; just return it */
938                 return main;
939         }
940
941         /* See if there's a link */
942         f.read_file (main);
943         optional<string> link = f.optional_string_child("Link");
944         if (link) {
945                 return *link;
946         }
947
948         return main;
949 }
950
951 void
952 Config::reset_cover_sheet ()
953 {
954         set_cover_sheet_to_default ();
955         changed ();
956 }
957
958 void
959 Config::link (boost::filesystem::path new_file) const
960 {
961         xmlpp::Document doc;
962         doc.create_root_node("Config")->add_child("Link")->add_child_text(new_file.string());
963         try {
964                 doc.write_to_file_formatted(path("config.xml", true).string());
965         } catch (xmlpp::exception& e) {
966                 string s = e.what ();
967                 trim (s);
968                 throw FileError (s, path("config.xml"));
969         }
970 }
971
972 void
973 Config::copy_and_link (boost::filesystem::path new_file) const
974 {
975         write ();
976         boost::filesystem::copy_file (config_file(), new_file, boost::filesystem::copy_option::overwrite_if_exists);
977         link (new_file);
978 }