dec07d4a8734e9adefcd7cdb00f1d0e2e9503746
[dcpomatic.git] / src / tools / dcpomatic_player.cc
1 /*
2     Copyright (C) 2017-2021 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 "wx/about_dialog.h"
22 #include "wx/file_dialog.h"
23 #include "wx/film_viewer.h"
24 #include "wx/id.h"
25 #include "wx/nag_dialog.h"
26 #include "wx/player_config_dialog.h"
27 #include "wx/player_information.h"
28 #include "wx/player_stress_tester.h"
29 #include "wx/playlist_controls.h"
30 #include "wx/report_problem_dialog.h"
31 #include "wx/standard_controls.h"
32 #include "wx/system_information_dialog.h"
33 #include "wx/timer_display.h"
34 #include "wx/update_dialog.h"
35 #include "wx/verify_dcp_progress_dialog.h"
36 #include "wx/verify_dcp_result_dialog.h"
37 #include "wx/wx_ptr.h"
38 #include "wx/wx_signal_manager.h"
39 #include "wx/wx_util.h"
40 #include "wx/wx_variant.h"
41 #include "lib/compose.hpp"
42 #include "lib/config.h"
43 #include "lib/constants.h"
44 #include "lib/cross.h"
45 #include "lib/dcp_content.h"
46 #include "lib/dcp_examiner.h"
47 #include "lib/dcpomatic_log.h"
48 #include "lib/dcpomatic_socket.h"
49 #include "lib/examine_content_job.h"
50 #include "lib/ffmpeg_content.h"
51 #include "lib/file_log.h"
52 #include "lib/film.h"
53 #include "lib/font_config.h"
54 #include "lib/image.h"
55 #include "lib/image_jpeg.h"
56 #include "lib/image_png.h"
57 #include "lib/internet.h"
58 #include "lib/job.h"
59 #include "lib/job_manager.h"
60 #include "lib/null_log.h"
61 #include "lib/player.h"
62 #include "lib/player_video.h"
63 #include "lib/ratio.h"
64 #include "lib/scoped_temporary.h"
65 #include "lib/server.h"
66 #include "lib/text_content.h"
67 #include "lib/update_checker.h"
68 #include "lib/variant.h"
69 #include "lib/verify_dcp_job.h"
70 #include "lib/video_content.h"
71 #include <dcp/cpl.h>
72 #include <dcp/dcp.h>
73 #include <dcp/exceptions.h>
74 #include <dcp/filesystem.h>
75 #include <dcp/raw_convert.h>
76 #include <dcp/scope_guard.h>
77 #include <dcp/search.h>
78 #include <dcp/warnings.h>
79 LIBDCP_DISABLE_WARNINGS
80 #include <wx/cmdline.h>
81 #include <wx/display.h>
82 #include <wx/dnd.h>
83 #include <wx/preferences.h>
84 #include <wx/progdlg.h>
85 #include <wx/splash.h>
86 #include <wx/stdpaths.h>
87 #include <wx/wx.h>
88 LIBDCP_ENABLE_WARNINGS
89 #ifdef __WXGTK__
90 #include <X11/Xlib.h>
91 #endif
92 #include <boost/algorithm/string.hpp>
93 #include <boost/bind/bind.hpp>
94 #include <iostream>
95
96 #ifdef check
97 #undef check
98 #endif
99
100
101 #define MAX_CPLS 32
102
103
104 using std::cout;
105 using std::dynamic_pointer_cast;
106 using std::exception;
107 using std::list;
108 using std::make_shared;
109 using std::shared_ptr;
110 using std::string;
111 using std::vector;
112 using std::weak_ptr;
113 using boost::bind;
114 using boost::optional;
115 using boost::scoped_array;
116 using boost::thread;
117 #if BOOST_VERSION >= 106100
118 using namespace boost::placeholders;
119 #endif
120 using dcp::raw_convert;
121 using namespace dcpomatic;
122
123
124 enum {
125         ID_file_open = DCPOMATIC_MAIN_MENU,
126         ID_file_add_ov,
127         ID_file_add_kdm,
128         ID_file_save_frame,
129         ID_file_history,
130         /* Allow spare IDs after _history for the recent files list */
131         ID_file_close = DCPOMATIC_MAIN_MENU + 100,
132         ID_view_cpl,
133         /* Allow spare IDs for CPLs */
134         ID_view_full_screen = DCPOMATIC_MAIN_MENU + 200,
135         ID_view_dual_screen,
136         ID_view_closed_captions,
137         ID_view_scale_appropriate,
138         ID_view_scale_full,
139         ID_view_scale_half,
140         ID_view_scale_quarter,
141         ID_help_report_a_problem,
142         ID_tools_verify,
143         ID_tools_check_for_updates,
144         ID_tools_timing,
145         ID_tools_system_information,
146         /* IDs for shortcuts (with no associated menu item) */
147         ID_start_stop,
148         ID_go_back_frame,
149         ID_go_forward_frame,
150         ID_go_back_small_amount,
151         ID_go_forward_small_amount,
152         ID_go_back_medium_amount,
153         ID_go_forward_medium_amount,
154         ID_go_back_large_amount,
155         ID_go_forward_large_amount,
156         ID_go_to_start,
157         ID_go_to_end
158 };
159
160
161 class DOMFrame : public wxFrame
162 {
163 public:
164
165         class DCPDropTarget : public wxFileDropTarget
166         {
167         public:
168                 DCPDropTarget(DOMFrame* owner)
169                         : _frame(owner)
170                 {}
171
172                 bool OnDropFiles(wxCoord, wxCoord, wxArrayString const& filenames) override
173                 {
174                         if (filenames.GetCount() == 1) {
175                                 /* Try to load a directory */
176                                 auto path = boost::filesystem::path(wx_to_std(filenames[0]));
177                                 if (dcp::filesystem::is_directory(path)) {
178                                         _frame->load_dcp(wx_to_std(filenames[0]));
179                                         return true;
180                                 }
181                         }
182
183                         if (filenames.GetCount() >= 1) {
184                                 /* Try to load the parent if we drop some files, one if which is an asset map */
185                                 for (size_t i = 0; i < filenames.GetCount(); ++i) {
186                                         auto path = boost::filesystem::path(wx_to_std(filenames[i]));
187                                         if (path.filename() == "ASSETMAP" || path.filename() == "ASSETMAP.xml") {
188                                                 _frame->load_dcp(path.parent_path());
189                                                 return true;
190                                         }
191                                 }
192                         }
193
194                         return false;
195                 }
196
197         private:
198                 DOMFrame* _frame;
199         };
200
201
202         DOMFrame ()
203                 : wxFrame(nullptr, -1, variant::wx::dcpomatic_player())
204                 , _mode (Config::instance()->player_mode())
205                 /* Use a panel as the only child of the Frame so that we avoid
206                    the dark-grey background on Windows.
207                 */
208                 , _overall_panel(new wxPanel(this, wxID_ANY))
209                 , _viewer(_overall_panel)
210                 , _main_sizer (new wxBoxSizer(wxVERTICAL))
211         {
212                 dcpomatic_log = make_shared<NullLog>();
213
214 #if defined(DCPOMATIC_WINDOWS)
215                 maybe_open_console ();
216                 cout << variant::dcpomatic_player() << " is starting." << "\n";
217 #endif
218
219                 auto bar = new wxMenuBar;
220                 setup_menu (bar);
221                 set_menu_sensitivity ();
222                 SetMenuBar (bar);
223
224 #ifdef DCPOMATIC_WINDOWS
225                 SetIcon (wxIcon (std_to_wx ("id")));
226 #endif
227
228                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this, _1));
229                 update_from_config (Config::PLAYER_DEBUG_LOG);
230
231                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this), ID_file_open);
232                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_ov, this), ID_file_add_ov);
233                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_kdm, this), ID_file_add_kdm);
234                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_save_frame, this), ID_file_save_frame);
235                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1), ID_file_history, ID_file_history + HISTORY_SIZE);
236                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_close, this), ID_file_close);
237                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this), wxID_EXIT);
238                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this), wxID_PREFERENCES);
239                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_full_screen, this), ID_view_full_screen);
240                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_dual_screen, this), ID_view_dual_screen);
241                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_closed_captions, this), ID_view_closed_captions);
242                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_cpl, this, _1), ID_view_cpl, ID_view_cpl + MAX_CPLS);
243                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(0)), ID_view_scale_full);
244                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(1)), ID_view_scale_half);
245                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(2)), ID_view_scale_quarter);
246                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this), wxID_ABOUT);
247                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
248                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_verify, this), ID_tools_verify);
249                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
250                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_timing, this), ID_tools_timing);
251                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_system_information, this), ID_tools_system_information);
252
253                 Bind(wxEVT_CLOSE_WINDOW, boost::bind(&DOMFrame::close, this, _1));
254
255                 if (Config::instance()->player_mode() == Config::PLAYER_MODE_DUAL) {
256                         auto pc = new PlaylistControls (_overall_panel, _viewer);
257                         _controls = pc;
258                         pc->ResetFilm.connect (bind(&DOMFrame::reset_film_weak, this, _1));
259                 } else {
260                         _controls = new StandardControls (_overall_panel, _viewer, false);
261                 }
262                 _controls->set_film(_viewer.film());
263                 _viewer.set_dcp_decode_reduction(Config::instance()->decode_reduction());
264                 _viewer.set_optimise_for_j2k(true);
265                 _viewer.PlaybackPermitted.connect(bind(&DOMFrame::playback_permitted, this));
266                 _viewer.TooManyDropped.connect(bind(&DOMFrame::too_many_frames_dropped, this));
267                 _info = new PlayerInformation (_overall_panel, _viewer);
268                 setup_main_sizer (Config::instance()->player_mode());
269 #ifdef __WXOSX__
270                 int accelerators = 12;
271 #else
272                 int accelerators = 11;
273 #endif
274
275                 _stress.setup (this, _controls);
276
277                 std::vector<wxAcceleratorEntry> accel(accelerators);
278                 accel[0].Set(wxACCEL_NORMAL,                WXK_SPACE, ID_start_stop);
279                 accel[1].Set(wxACCEL_NORMAL,                WXK_LEFT,  ID_go_back_frame);
280                 accel[2].Set(wxACCEL_NORMAL,                WXK_RIGHT, ID_go_forward_frame);
281                 accel[3].Set(wxACCEL_SHIFT,                 WXK_LEFT,  ID_go_back_small_amount);
282                 accel[4].Set(wxACCEL_SHIFT,                 WXK_RIGHT, ID_go_forward_small_amount);
283                 accel[5].Set(wxACCEL_CTRL,                  WXK_LEFT,  ID_go_back_medium_amount);
284                 accel[6].Set(wxACCEL_CTRL,                  WXK_RIGHT, ID_go_forward_medium_amount);
285                 accel[7].Set(wxACCEL_SHIFT | wxACCEL_CTRL,  WXK_LEFT,  ID_go_back_large_amount);
286                 accel[8].Set(wxACCEL_SHIFT | wxACCEL_CTRL,  WXK_RIGHT, ID_go_forward_large_amount);
287                 accel[9].Set(wxACCEL_NORMAL,                WXK_HOME,  ID_go_to_start);
288                 accel[10].Set(wxACCEL_NORMAL,               WXK_END,   ID_go_to_end);
289 #ifdef __WXOSX__
290                 accel[11].Set(wxACCEL_CTRL, static_cast<int>('W'), ID_file_close);
291 #endif
292                 wxAcceleratorTable accel_table (accelerators, accel.data());
293                 SetAcceleratorTable (accel_table);
294
295                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::start_stop_pressed, this), ID_start_stop);
296                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_back_frame, this),      ID_go_back_frame);
297                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_forward_frame, this),   ID_go_forward_frame);
298                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,   -60), ID_go_back_small_amount);
299                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,    60), ID_go_forward_small_amount);
300                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,  -600), ID_go_back_medium_amount);
301                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,   600), ID_go_forward_medium_amount);
302                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this, -3600), ID_go_back_large_amount);
303                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_seconds,  this,  3600), ID_go_forward_large_amount);
304                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_to_start, this), ID_go_to_start);
305                 Bind (wxEVT_MENU, boost::bind(&DOMFrame::go_to_end,   this), ID_go_to_end);
306
307                 reset_film ();
308
309                 UpdateChecker::instance()->StateChanged.connect (boost::bind(&DOMFrame::update_checker_state_changed, this));
310                 setup_screen ();
311
312                 _stress.LoadDCP.connect (boost::bind(&DOMFrame::load_dcp, this, _1));
313
314                 SetDropTarget(new DCPDropTarget(this));
315         }
316
317         ~DOMFrame ()
318         {
319                 /* It's important that this is stopped before our frame starts destroying its children,
320                  * otherwise UI elements that it depends on will disappear from under it.
321                  */
322                 _viewer.stop();
323         }
324
325         void close(wxCloseEvent& ev)
326         {
327                 FontConfig::drop();
328                 ev.Skip();
329         }
330
331         void setup_main_sizer (Config::PlayerMode mode)
332         {
333                 _main_sizer->Detach(_viewer.panel());
334                 _main_sizer->Detach (_controls);
335                 _main_sizer->Detach (_info);
336                 if (mode != Config::PLAYER_MODE_DUAL) {
337                         _main_sizer->Add(_viewer.panel(), 1, wxEXPAND);
338                 }
339                 _main_sizer->Add (_controls, mode == Config::PLAYER_MODE_DUAL ? 1 : 0, wxEXPAND | wxALL, 6);
340                 _main_sizer->Add (_info, 0, wxEXPAND | wxALL, 6);
341                 _overall_panel->SetSizer (_main_sizer);
342                 _overall_panel->Layout ();
343         }
344
345         bool playback_permitted ()
346         {
347                 if (!_film || !Config::instance()->respect_kdm_validity_periods()) {
348                         return true;
349                 }
350
351                 bool ok = true;
352                 for (auto i: _film->content()) {
353                         auto d = dynamic_pointer_cast<DCPContent>(i);
354                         if (d && !d->kdm_timing_window_valid()) {
355                                 ok = false;
356                         }
357                 }
358
359                 if (!ok) {
360                         error_dialog (this, _("The KDM does not allow playback of this content at this time."));
361                 }
362
363                 return ok;
364         }
365
366
367         void too_many_frames_dropped ()
368         {
369                 if (!Config::instance()->nagged(Config::NAG_TOO_MANY_DROPPED_FRAMES)) {
370                         _viewer.stop();
371                 }
372
373                 NagDialog::maybe_nag (
374                         this,
375                         Config::NAG_TOO_MANY_DROPPED_FRAMES,
376                         _(wxS("The player is dropping a lot of frames, so playback may not be accurate.\n\n"
377                           "<b>This does not necessarily mean that the DCP you are playing is defective!</b>\n\n"
378                           "You may be able to improve player performance by:\n"
379                           "• choosing 'decode at half resolution' or 'decode at quarter resolution' from the View menu\n"
380                           "• using a more powerful computer.\n"
381                          ))
382                         );
383         }
384
385         void set_decode_reduction (optional<int> reduction)
386         {
387                 _viewer.set_dcp_decode_reduction(reduction);
388                 _info->triggered_update ();
389                 Config::instance()->set_decode_reduction (reduction);
390         }
391
392         void load_dcp (boost::filesystem::path dir)
393         {
394                 DCPOMATIC_ASSERT (_film);
395
396                 reset_film ();
397                 try {
398                         _stress.set_suspended (true);
399                         auto dcp = make_shared<DCPContent>(dir);
400                         auto job = make_shared<ExamineContentJob>(_film, dcp);
401                         _examine_job_connection = job->Finished.connect(bind(&DOMFrame::add_dcp_to_film, this, weak_ptr<Job>(job), weak_ptr<Content>(dcp)));
402                         JobManager::instance()->add (job);
403                         bool const ok = display_progress(variant::wx::dcpomatic_player(), _("Loading content"));
404                         if (!ok || !report_errors_from_last_job(this)) {
405                                 return;
406                         }
407                         Config::instance()->add_to_player_history (dir);
408                         if (dcp->video_frame_rate()) {
409                                 _film->set_video_frame_rate(dcp->video_frame_rate().get(), true);
410                         }
411                 } catch (ProjectFolderError &) {
412                         error_dialog (
413                                 this,
414                                 wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())),
415                                 wxString::Format(
416                                         _("This looks like a %s project folder, which cannot be loaded into the player.  "
417                                           "Choose the DCP folder inside the %s project folder if that's what you want to play."),
418                                         variant::wx::dcpomatic(),
419                                         variant::wx::dcpomatic()
420                                         )
421                                 );
422                 } catch (dcp::ReadError& e) {
423                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
424                 } catch (DCPError& e) {
425                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
426                 }
427         }
428
429         void add_dcp_to_film (weak_ptr<Job> weak_job, weak_ptr<Content> weak_content)
430         {
431                 auto job = weak_job.lock ();
432                 if (!job || !job->finished_ok()) {
433                         return;
434                 }
435
436                 auto content = weak_content.lock ();
437                 if (!content) {
438                         return;
439                 }
440
441                 _film->add_content (content);
442                 _stress.set_suspended (false);
443         }
444
445         void reset_film_weak (weak_ptr<Film> weak_film)
446         {
447                 auto film = weak_film.lock ();
448                 if (film) {
449                         reset_film (film);
450                 }
451         }
452
453         void reset_film (shared_ptr<Film> film = shared_ptr<Film>(new Film(optional<boost::filesystem::path>())))
454         {
455                 _film = film;
456                 _film->set_tolerant (true);
457                 _film->set_audio_channels (MAX_DCP_AUDIO_CHANNELS);
458                 _viewer.set_film(_film);
459                 _controls->set_film (_film);
460                 _film->Change.connect (bind(&DOMFrame::film_changed, this, _1, _2));
461                 _info->triggered_update ();
462         }
463
464         void film_changed (ChangeType type, FilmProperty property)
465         {
466                 if (type != ChangeType::DONE || property != FilmProperty::CONTENT) {
467                         return;
468                 }
469
470                 if (_viewer.playing()) {
471                         _viewer.stop();
472                 }
473
474                 /* Start off as Flat */
475                 _film->set_container (Ratio::from_id("185"));
476
477                 for (auto i: _film->content()) {
478                         auto dcp = dynamic_pointer_cast<DCPContent>(i);
479
480                         for (auto j: i->text) {
481                                 j->set_use (true);
482                         }
483
484                         if (i->video && i->video->size()) {
485                                 auto const r = Ratio::nearest_from_ratio(i->video->size()->ratio());
486                                 if (r->id() == "239") {
487                                         /* Any scope content means we use scope */
488                                         _film->set_container(r);
489                                 }
490                         }
491
492                         /* Any 3D content means we use 3D mode */
493                         if (i->video && i->video->frame_type() != VideoFrameType::TWO_D) {
494                                 _film->set_three_d (true);
495                         }
496                 }
497
498                 _viewer.seek(DCPTime(), true);
499                 _info->triggered_update ();
500
501                 set_menu_sensitivity ();
502
503                 auto old = _cpl_menu->GetMenuItems();
504                 for (auto const& i: old) {
505                         _cpl_menu->Remove (i);
506                 }
507
508                 if (_film->content().size() == 1) {
509                         /* Offer a CPL menu */
510                         auto first = dynamic_pointer_cast<DCPContent>(_film->content().front());
511                         if (first) {
512                                 int id = ID_view_cpl;
513                                 for (auto i: dcp::find_and_resolve_cpls(first->directories(), true)) {
514                                         auto j = _cpl_menu->AppendRadioItem(
515                                                 id,
516                                                 wxString::Format("%s (%s)", std_to_wx(i->annotation_text().get_value_or("")).data(), std_to_wx(i->id()).data())
517                                                 );
518                                         j->Check(!first->cpl() || i->id() == *first->cpl());
519                                         ++id;
520                                 }
521                         }
522                 }
523         }
524
525         void load_stress_script (boost::filesystem::path path)
526         {
527                 _stress.load_script (path);
528         }
529
530 private:
531
532         void examine_content ()
533         {
534                 DCPOMATIC_ASSERT (_film);
535                 auto dcp = dynamic_pointer_cast<DCPContent>(_film->content().front());
536                 DCPOMATIC_ASSERT (dcp);
537                 dcp->examine (_film, shared_ptr<Job>());
538
539                 /* Examining content re-creates the TextContent objects, so we must re-enable them */
540                 for (auto i: dcp->text) {
541                         i->set_use (true);
542                 }
543         }
544
545         bool report_errors_from_last_job (wxWindow* parent) const
546         {
547                 auto jm = JobManager::instance ();
548
549                 DCPOMATIC_ASSERT (!jm->get().empty());
550
551                 auto last = jm->get().back();
552                 if (last->finished_in_error()) {
553                         error_dialog(parent, wxString::Format(_("Could not load DCP.\n\n%s."), std_to_wx(last->error_summary()).data()), std_to_wx(last->error_details()));
554                         return false;
555                 }
556
557                 return true;
558         }
559
560         void setup_menu (wxMenuBar* m)
561         {
562                 _file_menu = new wxMenu;
563                 _file_menu->Append (ID_file_open, _("&Open...\tCtrl-O"));
564                 _file_add_ov = _file_menu->Append (ID_file_add_ov, _("&Add OV..."));
565                 _file_add_kdm = _file_menu->Append (ID_file_add_kdm, _("Add &KDM..."));
566                 _file_menu->AppendSeparator ();
567                 _file_save_frame = _file_menu->Append (ID_file_save_frame, _("&Save frame to file...\tCtrl-S"));
568
569                 _history_position = _file_menu->GetMenuItems().GetCount();
570
571                 _file_menu->AppendSeparator ();
572                 _file_menu->Append (ID_file_close, _("&Close"));
573                 _file_menu->AppendSeparator ();
574
575 #ifdef __WXOSX__
576                 _file_menu->Append (wxID_EXIT, _("&Exit"));
577 #else
578                 _file_menu->Append (wxID_EXIT, _("&Quit"));
579 #endif
580
581 #ifdef __WXOSX__
582                 auto prefs = _file_menu->Append(wxID_PREFERENCES, _("&Preferences...\tCtrl-,"));
583 #else
584                 auto edit = new wxMenu;
585                 auto prefs = edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
586 #endif
587
588                 prefs->Enable (Config::instance()->have_write_permission());
589
590                 _cpl_menu = new wxMenu;
591
592                 auto view = new wxMenu;
593                 auto c = Config::instance()->decode_reduction();
594                 _view_cpl = view->Append(ID_view_cpl, _("CPL"), _cpl_menu);
595                 view->AppendSeparator();
596                 _view_full_screen = view->AppendCheckItem(ID_view_full_screen, _("Full screen\tF11"));
597                 _view_dual_screen = view->AppendCheckItem(ID_view_dual_screen, _("Dual screen\tShift+F11"));
598                 setup_menu ();
599                 view->AppendSeparator();
600                 view->Append(ID_view_closed_captions, _("Closed captions..."));
601                 view->AppendSeparator();
602                 view->AppendRadioItem(ID_view_scale_appropriate, _("Set decode resolution to match display"))->Check(!static_cast<bool>(c));
603                 view->AppendRadioItem(ID_view_scale_full, _("Decode at full resolution"))->Check(c && c.get() == 0);
604                 view->AppendRadioItem(ID_view_scale_half, _("Decode at half resolution"))->Check(c && c.get() == 1);
605                 view->AppendRadioItem(ID_view_scale_quarter, _("Decode at quarter resolution"))->Check(c && c.get() == 2);
606
607                 auto tools = new wxMenu;
608                 _tools_verify = tools->Append (ID_tools_verify, _("Verify DCP..."));
609                 tools->AppendSeparator ();
610                 tools->Append (ID_tools_check_for_updates, _("Check for updates"));
611                 tools->Append (ID_tools_timing, _("Timing..."));
612                 tools->Append (ID_tools_system_information, _("System information..."));
613
614                 auto help = new wxMenu;
615 #ifdef __WXOSX__
616                 help->Append(wxID_ABOUT, variant::wx::insert_dcpomatic_player(_("About %s")));
617 #else
618                 help->Append (wxID_ABOUT, _("About"));
619 #endif
620                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
621
622                 m->Append (_file_menu, _("&File"));
623                 if (!Config::instance()->player_restricted_menus()) {
624 #ifndef __WXOSX__
625                         m->Append (edit, _("&Edit"));
626 #endif
627                         m->Append (view, _("&View"));
628                         m->Append (tools, _("&Tools"));
629                         m->Append (help, _("&Help"));
630                 }
631         }
632
633         void file_open ()
634         {
635                 auto d = wxStandardPaths::Get().GetDocumentsDir();
636                 if (Config::instance()->last_player_load_directory()) {
637                         d = std_to_wx (Config::instance()->last_player_load_directory()->string());
638                 }
639
640                 auto c = make_wx<wxDirDialog>(this, _("Select DCP to open"), d, wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST);
641
642                 int r;
643                 while (true) {
644                         r = c->ShowModal ();
645                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
646                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
647                         } else {
648                                 break;
649                         }
650                 }
651
652                 if (r == wxID_OK) {
653                         boost::filesystem::path const dcp (wx_to_std (c->GetPath ()));
654                         load_dcp (dcp);
655                         Config::instance()->set_last_player_load_directory (dcp.parent_path());
656                 }
657         }
658
659         void file_add_ov ()
660         {
661                 auto initial_dir = wxStandardPaths::Get().GetDocumentsDir();
662                 if (Config::instance()->last_player_load_directory()) {
663                         initial_dir = std_to_wx(Config::instance()->last_player_load_directory()->string());
664                 }
665
666                 auto c = make_wx<wxDirDialog>(
667                         this,
668                         _("Select DCP to open as OV"),
669                         initial_dir,
670                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
671                         );
672
673                 int r;
674                 while (true) {
675                         r = c->ShowModal ();
676                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
677                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
678                         } else {
679                                 break;
680                         }
681                 }
682
683                 if (r == wxID_OK) {
684                         DCPOMATIC_ASSERT (_film);
685                         auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
686                         DCPOMATIC_ASSERT (dcp);
687                         dcp->add_ov (wx_to_std(c->GetPath()));
688                         JobManager::instance()->add(make_shared<ExamineContentJob>(_film, dcp));
689                         bool const ok = display_progress(variant::wx::dcpomatic_player(), _("Loading content"));
690                         if (!ok || !report_errors_from_last_job(this)) {
691                                 return;
692                         }
693                         for (auto i: dcp->text) {
694                                 i->set_use (true);
695                         }
696                         if (dcp->video && dcp->video->size()) {
697                                 auto const r = Ratio::nearest_from_ratio(dcp->video->size()->ratio());
698                                 if (r) {
699                                         _film->set_container(r);
700                                 }
701                         }
702                 }
703
704                 _info->triggered_update ();
705         }
706
707         void file_add_kdm ()
708         {
709                 FileDialog dialog(this, _("Select KDM"), wxT("XML files|*.xml|All files|*.*"), wxFD_MULTIPLE, "AddKDMPath");
710
711                 if (dialog.show()) {
712                         DCPOMATIC_ASSERT (_film);
713                         auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
714                         DCPOMATIC_ASSERT (dcp);
715                         try {
716                                 if (dcp) {
717                                         dcp::ScopeGuard sg([this]() {
718                                                 _viewer.set_coalesce_player_changes(false);
719                                         });
720                                         _viewer.set_coalesce_player_changes(true);
721                                         for (auto path: dialog.paths()) {
722                                                 dcp->add_kdm(dcp::EncryptedKDM(dcp::file_to_string(path)));
723                                                 _kdms.push_back(path);
724                                         }
725                                         examine_content();
726                                 }
727                         } catch (exception& e) {
728                                 error_dialog (this, wxString::Format (_("Could not load KDM.")), std_to_wx(e.what()));
729                                 return;
730                         }
731                 }
732
733                 _info->triggered_update ();
734         }
735
736         void file_save_frame ()
737         {
738                 wxFileDialog dialog (this, _("Save frame to file"), "", "", "PNG files (*.png)|*.png|JPEG files (*.jpg;*.jpeg)|*.jpg;*.jpeg", wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
739                 if (dialog.ShowModal() == wxID_CANCEL) {
740                         return;
741                 }
742
743                 auto path = boost::filesystem::path (wx_to_std(dialog.GetPath()));
744
745                 auto player = make_shared<Player>(_film, Image::Alignment::PADDED);
746                 player->seek(_viewer.position(), true);
747
748                 bool done = false;
749                 player->Video.connect ([path, &done, this](shared_ptr<PlayerVideo> video, DCPTime) {
750                         auto ext = boost::algorithm::to_lower_copy(path.extension().string());
751                         if (ext == ".png") {
752                                 auto image = video->image(boost::bind(PlayerVideo::force, AV_PIX_FMT_RGBA), VideoRange::FULL, false);
753                                 image_as_png(image).write(path);
754                         } else if (ext == ".jpg" || ext == ".jpeg") {
755                                 auto image = video->image(boost::bind(PlayerVideo::force, AV_PIX_FMT_RGB24), VideoRange::FULL, false);
756                                 image_as_jpeg(image, 80).write(path);
757                         } else {
758                                 error_dialog (this, _(wxString::Format("Unrecognised file extension %s (use .jpg, .jpeg or .png)", std_to_wx(ext))));
759                         }
760                         done = true;
761                 });
762
763                 int tries_left = 50;
764                 while (!done && tries_left >= 0) {
765                         player->pass();
766                         --tries_left;
767                 }
768
769                 DCPOMATIC_ASSERT (tries_left >= 0);
770         }
771
772         void file_history (wxCommandEvent& event)
773         {
774                 auto history = Config::instance()->player_history ();
775                 int n = event.GetId() - ID_file_history;
776                 if (n >= 0 && n < static_cast<int> (history.size ())) {
777                         try {
778                                 load_dcp (history[n]);
779                         } catch (exception& e) {
780                                 error_dialog (0, std_to_wx(String::compose(wx_to_std(_("Could not load DCP %1.")), history[n])), std_to_wx(e.what()));
781                         }
782                 }
783         }
784
785         void file_close ()
786         {
787                 reset_film ();
788                 _info->triggered_update ();
789                 set_menu_sensitivity ();
790         }
791
792         void file_exit ()
793         {
794                 Close ();
795         }
796
797         void edit_preferences ()
798         {
799                 if (!Config::instance()->have_write_permission()) {
800                         return;
801                 }
802
803                 if (!_config_dialog) {
804                         _config_dialog = create_player_config_dialog ();
805                 }
806                 _config_dialog->Show (this);
807         }
808
809         void view_cpl (wxCommandEvent& ev)
810         {
811                 auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
812                 DCPOMATIC_ASSERT (dcp);
813                 auto cpls = dcp::find_and_resolve_cpls (dcp->directories(), true);
814                 int id = ev.GetId() - ID_view_cpl;
815                 DCPOMATIC_ASSERT (id >= 0);
816                 DCPOMATIC_ASSERT (id < int(cpls.size()));
817                 auto i = cpls.begin();
818                 while (id > 0) {
819                         ++i;
820                         --id;
821                 }
822
823                 _viewer.set_coalesce_player_changes(true);
824                 dcp->set_cpl ((*i)->id());
825                 examine_content ();
826                 _viewer.set_coalesce_player_changes(false);
827
828                 _info->triggered_update ();
829         }
830
831         void view_full_screen ()
832         {
833                 if (_mode == Config::PLAYER_MODE_FULL) {
834                         _mode = Config::PLAYER_MODE_WINDOW;
835                 } else {
836                         _mode = Config::PLAYER_MODE_FULL;
837                 }
838                 setup_screen ();
839                 setup_menu ();
840         }
841
842         void view_dual_screen ()
843         {
844                 if (_mode == Config::PLAYER_MODE_DUAL) {
845                         _mode = Config::PLAYER_MODE_WINDOW;
846                 } else {
847                         _mode = Config::PLAYER_MODE_DUAL;
848                 }
849                 setup_screen ();
850                 setup_menu ();
851         }
852
853         void setup_menu ()
854         {
855                 if (_view_full_screen) {
856                         _view_full_screen->Check (_mode == Config::PLAYER_MODE_FULL);
857                 }
858                 if (_view_dual_screen) {
859                         _view_dual_screen->Check (_mode == Config::PLAYER_MODE_DUAL);
860                 }
861         }
862
863         void setup_screen ()
864         {
865                 _controls->Show (_mode != Config::PLAYER_MODE_FULL);
866                 _info->Show (_mode != Config::PLAYER_MODE_FULL);
867                 _overall_panel->SetBackgroundColour (_mode == Config::PLAYER_MODE_FULL ? wxColour(0, 0, 0) : wxNullColour);
868                 ShowFullScreen (_mode == Config::PLAYER_MODE_FULL);
869                 _viewer.set_pad_black(_mode != Config::PLAYER_MODE_WINDOW);
870
871                 if (_mode == Config::PLAYER_MODE_DUAL) {
872                         _dual_screen = new wxFrame (this, wxID_ANY, wxT(""));
873                         _dual_screen->SetBackgroundColour (wxColour(0, 0, 0));
874                         _dual_screen->ShowFullScreen (true);
875                         _viewer.panel()->Reparent(_dual_screen);
876                         _viewer.panel()->SetFocus();
877                         _dual_screen->Show ();
878                         LOG_DEBUG_PLAYER("Setting up dual screen mode with %1 displays", wxDisplay::GetCount());
879                         for (auto index = 0U; index < wxDisplay::GetCount(); ++index) {
880                                 wxDisplay display(index);
881                                 auto client = display.GetClientArea();
882                                 auto mode = display.GetCurrentMode();
883                                 auto geometry = display.GetGeometry();
884                                 LOG_DEBUG_PLAYER("Display %1", index);
885                                 LOG_DEBUG_PLAYER("  ClientArea position=(%1, %2) size=(%3, %4)", client.GetX(), client.GetY(), client.GetWidth(), client.GetHeight());
886                                 LOG_DEBUG_PLAYER("  Geometry   position=(%1, %2) size=(%3, %4)", geometry.GetX(), geometry.GetY(), geometry.GetWidth(), geometry.GetHeight());
887                                 LOG_DEBUG_PLAYER("  Mode       size=(%1, %2)", mode.GetWidth(), mode.GetHeight());
888                                 LOG_DEBUG_PLAYER("  Primary?   %1", static_cast<int>(display.IsPrimary()));
889                         }
890                         if (wxDisplay::GetCount() > 1) {
891                                 wxRect geometry[2] = {
892                                         wxDisplay(0U).GetGeometry(),
893                                         wxDisplay(1U).GetGeometry()
894                                 };
895                                 auto const image_display = Config::instance()->image_display();
896                                 _dual_screen->Move(geometry[image_display].GetX(), geometry[image_display].GetY());
897                                 _viewer.panel()->SetSize(geometry[image_display].GetWidth(), geometry[image_display].GetHeight());
898                                 Move(geometry[1 - image_display].GetX(), geometry[1 - image_display].GetY());
899                         }
900                         _dual_screen->Bind(wxEVT_CHAR_HOOK, boost::bind(&DOMFrame::dual_screen_key_press, this, _1));
901                 } else {
902                         if (_dual_screen) {
903                                 _viewer.panel()->Reparent(_overall_panel);
904                                 _dual_screen->Destroy ();
905                                 _dual_screen = 0;
906                         }
907                 }
908
909                 setup_main_sizer (_mode);
910         }
911
912         void dual_screen_key_press(wxKeyEvent& ev)
913         {
914                 if (ev.GetKeyCode() == WXK_F11) {
915                         if (ev.ShiftDown()) {
916                                 view_dual_screen();
917                         } else if (!ev.HasAnyModifiers()) {
918                                 view_full_screen();
919                         }
920                 }
921         }
922
923         void view_closed_captions ()
924         {
925                 _viewer.show_closed_captions();
926         }
927
928         void tools_verify ()
929         {
930                 auto dcp = std::dynamic_pointer_cast<DCPContent>(_film->content().front());
931                 DCPOMATIC_ASSERT (dcp);
932
933                 auto job = make_shared<VerifyDCPJob>(dcp->directories(), _kdms);
934                 VerifyDCPProgressDialog progress(this, variant::wx::dcpomatic_player());
935                 bool const completed = progress.run(job);
936                 progress.Close();
937
938                 if (completed) {
939                         VerifyDCPResultDialog dialog(this, job);
940                         dialog.ShowModal();
941                 }
942         }
943
944         void tools_check_for_updates ()
945         {
946                 UpdateChecker::instance()->run ();
947                 _update_news_requested = true;
948         }
949
950         void tools_timing ()
951         {
952                 auto d = make_wx<TimerDisplay>(this, _viewer.state_timer(), _viewer.gets());
953                 d->ShowModal ();
954         }
955
956         void tools_system_information ()
957         {
958                 if (!_system_information_dialog) {
959                         _system_information_dialog = new SystemInformationDialog (this, _viewer);
960                 }
961
962                 _system_information_dialog->Show ();
963         }
964
965         void help_about ()
966         {
967                 auto d = make_wx<AboutDialog>(this);
968                 d->ShowModal ();
969         }
970
971         void help_report_a_problem ()
972         {
973                 auto d = make_wx<ReportProblemDialog>(this);
974                 if (d->ShowModal () == wxID_OK) {
975                         d->report ();
976                 }
977         }
978
979         void update_checker_state_changed ()
980         {
981                 auto uc = UpdateChecker::instance ();
982
983                 bool const announce =
984                         _update_news_requested ||
985                         (uc->stable() && Config::instance()->check_for_updates()) ||
986                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
987
988                 _update_news_requested = false;
989
990                 if (!announce) {
991                         return;
992                 }
993
994                 if (uc->state() == UpdateChecker::State::YES) {
995                         auto dialog = make_wx<UpdateDialog>(this, uc->stable (), uc->test ());
996                         dialog->ShowModal ();
997                 } else if (uc->state() == UpdateChecker::State::FAILED) {
998                         error_dialog(this, variant::wx::insert_dcpomatic(_("The %s download server could not be contacted.")));
999                 } else {
1000                         error_dialog(this, variant::wx::insert_dcpomatic(_("There are no new versions of %s available.")));
1001                 }
1002
1003                 _update_news_requested = false;
1004         }
1005
1006         void config_changed (Config::Property prop)
1007         {
1008                 /* Instantly save any config changes when using the player GUI */
1009                 try {
1010                         Config::instance()->write_config();
1011                 } catch (FileError& e) {
1012                         if (prop != Config::HISTORY) {
1013                                 error_dialog (
1014                                         this,
1015                                         wxString::Format(
1016                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
1017                                                 std_to_wx(e.file().string())
1018                                                 )
1019                                         );
1020                         }
1021                 } catch (exception& e) {
1022                         error_dialog (
1023                                 this,
1024                                 _("Could not write to config file.  Your changes have not been saved.")
1025                                 );
1026                 }
1027
1028                 update_from_config (prop);
1029         }
1030
1031         void update_from_config (Config::Property prop)
1032         {
1033                 for (int i = 0; i < _history_items; ++i) {
1034                         delete _file_menu->Remove (ID_file_history + i);
1035                 }
1036
1037                 if (_history_separator) {
1038                         _file_menu->Remove (_history_separator);
1039                 }
1040                 delete _history_separator;
1041                 _history_separator = nullptr;
1042
1043                 int pos = _history_position;
1044
1045                 /* Clear out non-existent history items before we re-build the menu */
1046                 Config::instance()->clean_player_history ();
1047                 auto history = Config::instance()->player_history ();
1048
1049                 if (!history.empty ()) {
1050                         _history_separator = _file_menu->InsertSeparator (pos++);
1051                 }
1052
1053                 for (size_t i = 0; i < history.size(); ++i) {
1054                         string s;
1055                         if (i < 9) {
1056                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
1057                         } else {
1058                                 s = history[i].string();
1059                         }
1060                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
1061                 }
1062
1063                 _history_items = history.size ();
1064
1065                 if (prop == Config::PLAYER_DEBUG_LOG) {
1066                         auto p = Config::instance()->player_debug_log_file();
1067                         if (p) {
1068                                 dcpomatic_log = make_shared<FileLog>(*p);
1069                         } else {
1070                                 dcpomatic_log = make_shared<NullLog>();
1071                         }
1072                         dcpomatic_log->set_types (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR | LogEntry::TYPE_DEBUG_VIDEO_VIEW);
1073                 }
1074         }
1075
1076         void set_menu_sensitivity ()
1077         {
1078                 _tools_verify->Enable (static_cast<bool>(_film));
1079                 _file_add_ov->Enable (static_cast<bool>(_film));
1080                 _file_add_kdm->Enable (static_cast<bool>(_film));
1081                 _file_save_frame->Enable (static_cast<bool>(_film));
1082                 _view_cpl->Enable (static_cast<bool>(_film));
1083         }
1084
1085         void start_stop_pressed ()
1086         {
1087                 if (_viewer.playing()) {
1088                         _viewer.stop();
1089                 } else {
1090                         _viewer.start();
1091                 }
1092         }
1093
1094         void go_back_frame ()
1095         {
1096                 _viewer.seek_by(-_viewer.one_video_frame(), true);
1097         }
1098
1099         void go_forward_frame ()
1100         {
1101                 _viewer.seek_by(_viewer.one_video_frame(), true);
1102         }
1103
1104         void go_seconds (int s)
1105         {
1106                 _viewer.seek_by(DCPTime::from_seconds(s), true);
1107         }
1108
1109         void go_to_start ()
1110         {
1111                 _viewer.seek(DCPTime(), true);
1112         }
1113
1114         void go_to_end ()
1115         {
1116                 _viewer.seek(_film->length() - _viewer.one_video_frame(), true);
1117         }
1118
1119         wxFrame* _dual_screen = nullptr;
1120         bool _update_news_requested = false;
1121         PlayerInformation* _info = nullptr;
1122         Config::PlayerMode _mode;
1123         wxPreferencesEditor* _config_dialog = nullptr;
1124         wxPanel* _overall_panel = nullptr;
1125         wxMenu* _file_menu = nullptr;
1126         wxMenuItem* _view_cpl = nullptr;
1127         wxMenu* _cpl_menu = nullptr;
1128         int _history_items = 0;
1129         int _history_position = 0;
1130         wxMenuItem* _history_separator = nullptr;
1131         FilmViewer _viewer;
1132         Controls* _controls;
1133         SystemInformationDialog* _system_information_dialog = nullptr;
1134         std::shared_ptr<Film> _film;
1135         boost::signals2::scoped_connection _config_changed_connection;
1136         boost::signals2::scoped_connection _examine_job_connection;
1137         wxMenuItem* _file_add_ov = nullptr;
1138         wxMenuItem* _file_add_kdm = nullptr;
1139         wxMenuItem* _file_save_frame = nullptr;
1140         wxMenuItem* _tools_verify = nullptr;
1141         wxMenuItem* _view_full_screen = nullptr;
1142         wxMenuItem* _view_dual_screen = nullptr;
1143         wxSizer* _main_sizer = nullptr;
1144         PlayerStressTester _stress;
1145         /** KDMs that have been loaded, so that we can pass them to the verifier */
1146         std::vector<boost::filesystem::path> _kdms;
1147 };
1148
1149 static const wxCmdLineEntryDesc command_line_description[] = {
1150         { wxCMD_LINE_PARAM, 0, 0, "DCP to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1151         { wxCMD_LINE_OPTION, "c", "config", "Directory containing config.xml", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1152         { wxCMD_LINE_OPTION, "s", "stress", "File containing description of stress test", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1153         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1154 };
1155
1156 class PlayServer : public Server
1157 {
1158 public:
1159         explicit PlayServer (DOMFrame* frame)
1160                 : Server (PLAYER_PLAY_PORT)
1161                 , _frame (frame)
1162         {}
1163
1164         void handle (shared_ptr<Socket> socket) override
1165         {
1166                 try {
1167                         uint32_t const length = socket->read_uint32 ();
1168                         if (length > 65536) {
1169                                 return;
1170                         }
1171                         scoped_array<char> buffer (new char[length]);
1172                         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
1173                         string s (buffer.get());
1174                         signal_manager->when_idle (bind (&DOMFrame::load_dcp, _frame, s));
1175                         socket->write (reinterpret_cast<uint8_t const *> ("OK"), 3);
1176                 } catch (...) {
1177
1178                 }
1179         }
1180
1181 private:
1182         DOMFrame* _frame;
1183 };
1184
1185 /** @class App
1186  *  @brief The magic App class for wxWidgets.
1187  */
1188 class App : public wxApp
1189 {
1190 public:
1191         App ()
1192                 : wxApp ()
1193         {
1194 #ifdef DCPOMATIC_LINUX
1195                 XInitThreads ();
1196 #endif
1197         }
1198
1199 private:
1200
1201         bool OnInit () override
1202         {
1203                 wxSplashScreen* splash;
1204                 try {
1205                         wxInitAllImageHandlers ();
1206
1207                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1208                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1209
1210                         splash = maybe_show_splash ();
1211
1212                         SetAppName(variant::wx::dcpomatic_player());
1213
1214                         if (!wxApp::OnInit()) {
1215                                 return false;
1216                         }
1217
1218 #ifdef DCPOMATIC_LINUX
1219                         unsetenv ("UBUNTU_MENUPROXY");
1220 #endif
1221
1222 #ifdef DCPOMATIC_OSX
1223                         make_foreground_application ();
1224 #endif
1225
1226                         dcpomatic_setup_path_encoding ();
1227
1228                         /* Enable i18n; this will create a Config object
1229                            to look for a force-configured language.  This Config
1230                            object will be wrong, however, because dcpomatic_setup
1231                            hasn't yet been called and there aren't any filters etc.
1232                            set up yet.
1233                         */
1234                         dcpomatic_setup_i18n ();
1235
1236                         /* Set things up, including filters etc.
1237                            which will now be internationalised correctly.
1238                         */
1239                         dcpomatic_setup ();
1240
1241                         /* Force the configuration to be re-loaded correctly next
1242                            time it is needed.
1243                         */
1244                         Config::drop ();
1245
1246                         signal_manager = new wxSignalManager (this);
1247
1248                         _frame = new DOMFrame ();
1249                         SetTopWindow (_frame);
1250                         _frame->Maximize ();
1251                         if (splash) {
1252                                 splash->Destroy ();
1253                                 splash = nullptr;
1254                         }
1255                         _frame->Show ();
1256
1257                         try {
1258                                 auto server = new PlayServer (_frame);
1259                                 new thread (boost::bind (&PlayServer::run, server));
1260                         } catch (std::exception& e) {
1261                                 /* This is not the end of the world; probably a failure to bind the server socket
1262                                  * because there's already another player running.
1263                                  */
1264                                 LOG_DEBUG_PLAYER ("Failed to start play server (%1)", e.what());
1265                         }
1266
1267                         if (!_dcp_to_load.empty() && dcp::filesystem::is_directory(_dcp_to_load)) {
1268                                 try {
1269                                         _frame->load_dcp (_dcp_to_load);
1270                                 } catch (exception& e) {
1271                                         error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
1272                                 }
1273                         }
1274
1275                         if (_stress) {
1276                                 try {
1277                                         _frame->load_stress_script (*_stress);
1278                                 } catch (exception& e) {
1279                                         error_dialog (0, wxString::Format("Could not load stress test file %s", std_to_wx(*_stress)));
1280                                 }
1281                         }
1282
1283                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1284
1285                         if (Config::instance()->check_for_updates ()) {
1286                                 UpdateChecker::instance()->run ();
1287                         }
1288                 }
1289                 catch (exception& e)
1290                 {
1291                         if (splash) {
1292                                 splash->Destroy ();
1293                         }
1294                         error_dialog(nullptr, variant::wx::insert_dcpomatic_player(_("%s could not start")), std_to_wx(e.what()));
1295                 }
1296
1297                 return true;
1298         }
1299
1300         void OnInitCmdLine (wxCmdLineParser& parser) override
1301         {
1302                 parser.SetDesc (command_line_description);
1303                 parser.SetSwitchChars (wxT ("-"));
1304         }
1305
1306         bool OnCmdLineParsed (wxCmdLineParser& parser) override
1307         {
1308                 if (parser.GetParamCount() > 0) {
1309                         _dcp_to_load = wx_to_std (parser.GetParam (0));
1310                 }
1311
1312                 wxString config;
1313                 if (parser.Found("c", &config)) {
1314                         Config::override_path = wx_to_std (config);
1315                 }
1316                 wxString stress;
1317                 if (parser.Found("s", &stress)) {
1318                         _stress = wx_to_std (stress);
1319                 }
1320
1321                 return true;
1322         }
1323
1324         void report_exception ()
1325         {
1326                 try {
1327                         throw;
1328                 } catch (FileError& e) {
1329                         error_dialog (
1330                                 0,
1331                                 wxString::Format (
1332                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1333                                         std_to_wx (e.what()),
1334                                         std_to_wx (e.file().string().c_str ())
1335                                         )
1336                                 );
1337                 } catch (exception& e) {
1338                         error_dialog (
1339                                 0,
1340                                 wxString::Format (
1341                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1342                                         std_to_wx (e.what ())
1343                                         )
1344                                 );
1345                 } catch (...) {
1346                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1347                 }
1348         }
1349
1350         /* An unhandled exception has occurred inside the main event loop */
1351         bool OnExceptionInMainLoop () override
1352         {
1353                 report_exception ();
1354                 /* This will terminate the program */
1355                 return false;
1356         }
1357
1358         void OnUnhandledException () override
1359         {
1360                 report_exception ();
1361         }
1362
1363         void idle ()
1364         {
1365                 signal_manager->ui_idle ();
1366         }
1367
1368         void config_failed_to_load ()
1369         {
1370                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1371         }
1372
1373         void config_warning (string m)
1374         {
1375                 message_dialog (_frame, std_to_wx (m));
1376         }
1377
1378         DOMFrame* _frame = nullptr;
1379         string _dcp_to_load;
1380         boost::optional<string> _stress;
1381 };
1382
1383 IMPLEMENT_APP (App)