Prevent player folding audio to 2 channel if "default DCP audio channels" is set...
[dcpomatic.git] / src / tools / dcpomatic_player.cc
1 /*
2     Copyright (C) 2017-2019 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/wx_signal_manager.h"
22 #include "wx/wx_util.h"
23 #include "wx/about_dialog.h"
24 #include "wx/report_problem_dialog.h"
25 #include "wx/film_viewer.h"
26 #include "wx/player_information.h"
27 #include "wx/update_dialog.h"
28 #include "wx/player_config_dialog.h"
29 #include "wx/verify_dcp_dialog.h"
30 #include "wx/standard_controls.h"
31 #include "wx/swaroop_controls.h"
32 #include "wx/timer_display.h"
33 #include "wx/system_information_dialog.h"
34 #include "lib/cross.h"
35 #include "lib/config.h"
36 #include "lib/util.h"
37 #include "lib/internet.h"
38 #include "lib/update_checker.h"
39 #include "lib/compose.hpp"
40 #include "lib/dcp_content.h"
41 #include "lib/job_manager.h"
42 #include "lib/job.h"
43 #include "lib/film.h"
44 #include "lib/null_log.h"
45 #include "lib/video_content.h"
46 #include "lib/text_content.h"
47 #include "lib/ratio.h"
48 #include "lib/verify_dcp_job.h"
49 #include "lib/dcp_examiner.h"
50 #include "lib/examine_content_job.h"
51 #include "lib/server.h"
52 #include "lib/dcpomatic_socket.h"
53 #include "lib/scoped_temporary.h"
54 #include "lib/monitor_checker.h"
55 #include "lib/lock_file_checker.h"
56 #include "lib/ffmpeg_content.h"
57 #include "lib/dcpomatic_log.h"
58 #include "lib/file_log.h"
59 #include <dcp/dcp.h>
60 #include <dcp/raw_convert.h>
61 #include <dcp/exceptions.h>
62 #include <wx/wx.h>
63 #include <wx/stdpaths.h>
64 #include <wx/splash.h>
65 #include <wx/cmdline.h>
66 #include <wx/preferences.h>
67 #include <wx/progdlg.h>
68 #include <wx/display.h>
69 #ifdef __WXOSX__
70 #include <ApplicationServices/ApplicationServices.h>
71 #endif
72 #include <boost/bind.hpp>
73 #include <iostream>
74
75 #ifdef check
76 #undef check
77 #endif
78
79 #define MAX_CPLS 32
80
81 using std::string;
82 using std::cout;
83 using std::list;
84 using std::exception;
85 using std::vector;
86 using boost::shared_ptr;
87 using boost::weak_ptr;
88 using boost::scoped_array;
89 using boost::optional;
90 using boost::dynamic_pointer_cast;
91 using boost::thread;
92 using boost::bind;
93 using namespace dcpomatic;
94
95 enum {
96         ID_file_open = 1,
97         ID_file_add_ov,
98         ID_file_add_kdm,
99         ID_file_history,
100         /* Allow spare IDs after _history for the recent files list */
101         ID_file_close = 100,
102         ID_view_cpl,
103         /* Allow spare IDs for CPLs */
104         ID_view_full_screen = 200,
105         ID_view_dual_screen,
106         ID_view_closed_captions,
107         ID_view_scale_appropriate,
108         ID_view_scale_full,
109         ID_view_scale_half,
110         ID_view_scale_quarter,
111         ID_help_report_a_problem,
112         ID_tools_verify,
113         ID_tools_check_for_updates,
114         ID_tools_timing,
115         ID_tools_system_information,
116         /* IDs for shortcuts (with no associated menu item) */
117         ID_start_stop,
118         ID_back_frame,
119         ID_forward_frame
120 };
121
122 class DOMFrame : public wxFrame
123 {
124 public:
125         DOMFrame ()
126                 : wxFrame (0, -1, _("DCP-o-matic Player"))
127                 , _dual_screen (0)
128                 , _update_news_requested (false)
129                 , _info (0)
130                 , _mode (Config::instance()->player_mode())
131                 , _config_dialog (0)
132                 , _file_menu (0)
133                 , _history_items (0)
134                 , _history_position (0)
135                 , _history_separator (0)
136                 , _system_information_dialog (0)
137                 , _view_full_screen (0)
138                 , _view_dual_screen (0)
139         {
140                 dcpomatic_log.reset (new NullLog());
141
142 #if defined(DCPOMATIC_WINDOWS)
143                 maybe_open_console ();
144                 cout << "DCP-o-matic Player is starting." << "\n";
145 #endif
146
147                 wxMenuBar* bar = new wxMenuBar;
148                 setup_menu (bar);
149                 set_menu_sensitivity ();
150                 SetMenuBar (bar);
151
152 #ifdef DCPOMATIC_WINDOWS
153                 SetIcon (wxIcon (std_to_wx ("id")));
154 #endif
155
156                 _config_changed_connection = Config::instance()->Changed.connect (boost::bind (&DOMFrame::config_changed, this, _1));
157                 update_from_config (Config::PLAYER_DEBUG_LOG);
158
159                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_open, this), ID_file_open);
160                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_ov, this), ID_file_add_ov);
161                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_add_kdm, this), ID_file_add_kdm);
162                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_history, this, _1), ID_file_history, ID_file_history + HISTORY_SIZE);
163                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_close, this), ID_file_close);
164                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::file_exit, this), wxID_EXIT);
165                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::edit_preferences, this), wxID_PREFERENCES);
166                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_full_screen, this), ID_view_full_screen);
167                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_dual_screen, this), ID_view_dual_screen);
168                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_closed_captions, this), ID_view_closed_captions);
169                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::view_cpl, this, _1), ID_view_cpl, ID_view_cpl + MAX_CPLS);
170                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(0)), ID_view_scale_full);
171                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(1)), ID_view_scale_half);
172                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::set_decode_reduction, this, optional<int>(2)), ID_view_scale_quarter);
173                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_about, this), wxID_ABOUT);
174                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::help_report_a_problem, this), ID_help_report_a_problem);
175                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_verify, this), ID_tools_verify);
176                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_check_for_updates, this), ID_tools_check_for_updates);
177                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_timing, this), ID_tools_timing);
178                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::tools_system_information, this), ID_tools_system_information);
179
180                 /* Use a panel as the only child of the Frame so that we avoid
181                    the dark-grey background on Windows.
182                 */
183                 _overall_panel = new wxPanel (this, wxID_ANY);
184
185                 _viewer.reset (new FilmViewer (_overall_panel));
186 #ifdef DCPOMATIC_VARIANT_SWAROOP
187                 SwaroopControls* sc = new SwaroopControls (_overall_panel, _viewer);
188                 _controls = sc;
189                 sc->ResetFilm.connect (bind(&DOMFrame::reset_film_weak, this, _1));
190 #else
191                 _controls = new StandardControls (_overall_panel, _viewer, false);
192 #endif
193                 _viewer->set_dcp_decode_reduction (Config::instance()->decode_reduction ());
194                 _viewer->PlaybackPermitted.connect (bind(&DOMFrame::playback_permitted, this));
195                 _viewer->Started.connect (bind(&DOMFrame::playback_started, this, _1));
196                 _viewer->Stopped.connect (bind(&DOMFrame::playback_stopped, this, _1));
197                 _info = new PlayerInformation (_overall_panel, _viewer);
198                 setup_main_sizer (Config::instance()->player_mode());
199 #ifdef __WXOSX__
200                 int accelerators = 4;
201 #else
202                 int accelerators = 3;
203 #endif
204
205                 wxAcceleratorEntry* accel = new wxAcceleratorEntry[accelerators];
206                 accel[0].Set(wxACCEL_NORMAL, WXK_SPACE, ID_start_stop);
207                 accel[1].Set(wxACCEL_NORMAL, WXK_LEFT, ID_back_frame);
208                 accel[2].Set(wxACCEL_NORMAL, WXK_RIGHT, ID_forward_frame);
209 #ifdef __WXOSX__
210                 accel[3].Set(wxACCEL_CTRL, static_cast<int>('W'), ID_file_close);
211 #endif
212                 wxAcceleratorTable accel_table (accelerators, accel);
213                 SetAcceleratorTable (accel_table);
214                 delete[] accel;
215
216                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::start_stop_pressed, this), ID_start_stop);
217                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::back_frame, this), ID_back_frame);
218                 Bind (wxEVT_MENU, boost::bind (&DOMFrame::forward_frame, this), ID_forward_frame);
219
220                 reset_film ();
221
222                 UpdateChecker::instance()->StateChanged.connect (boost::bind (&DOMFrame::update_checker_state_changed, this));
223 #ifdef DCPOMATIC_VARIANT_SWAROOP
224                 MonitorChecker::instance()->StateChanged.connect(boost::bind(&DOMFrame::monitor_checker_state_changed, this));
225                 MonitorChecker::instance()->run ();
226                 LockFileChecker::instance()->StateChanged.connect(boost::bind(&DOMFrame::lock_checker_state_changed, this));
227                 LockFileChecker::instance()->run ();
228 #endif
229                 setup_screen ();
230
231 #ifdef DCPOMATIC_VARIANT_SWAROOP
232                 sc->check_restart ();
233 #endif
234         }
235
236 #ifdef DCPOMATIC_VARIANT_SWAROOP
237         void monitor_checker_state_changed ()
238         {
239                 if (!MonitorChecker::instance()->ok()) {
240                         _viewer->stop ();
241                         error_dialog (this, _("The required display devices are not connected correctly."));
242                 }
243         }
244
245         void lock_checker_state_changed ()
246         {
247                 if (!LockFileChecker::instance()->ok()) {
248                         _viewer->stop ();
249                         error_dialog (this, _("The lock file is not present."));
250                 }
251         }
252 #endif
253
254         void setup_main_sizer (Config::PlayerMode mode)
255         {
256                 wxSizer* main_sizer = new wxBoxSizer (wxVERTICAL);
257                 if (mode != Config::PLAYER_MODE_DUAL) {
258                         main_sizer->Add (_viewer->panel(), 1, wxEXPAND | wxALIGN_CENTER_VERTICAL);
259                 }
260                 main_sizer->Add (_controls, mode == Config::PLAYER_MODE_DUAL ? 1 : 0, wxEXPAND | wxALL, 6);
261                 main_sizer->Add (_info, 0, wxEXPAND | wxALL, 6);
262                 _overall_panel->SetSizer (main_sizer);
263                 _overall_panel->Layout ();
264         }
265
266         bool playback_permitted ()
267         {
268 #ifdef DCPOMATIC_VARIANT_SWAROOP
269                 if (!MonitorChecker::instance()->ok()) {
270                         error_dialog (this, _("The required display devices are not connected correctly."));
271                         return false;
272                 }
273                 if (!LockFileChecker::instance()->ok()) {
274                         error_dialog (this, _("The lock file is not present."));
275                         return false;
276                 }
277 #endif
278                 if (!_film || !Config::instance()->respect_kdm_validity_periods()) {
279                         return true;
280                 }
281
282                 bool ok = true;
283                 BOOST_FOREACH (shared_ptr<Content> i, _film->content()) {
284                         shared_ptr<DCPContent> d = dynamic_pointer_cast<DCPContent>(i);
285                         if (d && !d->kdm_timing_window_valid()) {
286                                 ok = false;
287                         }
288                 }
289
290 #ifdef DCPOMATIC_VARIANT_SWAROOP
291                 BOOST_FOREACH (shared_ptr<Content> i, _film->content()) {
292                         shared_ptr<FFmpegContent> c = dynamic_pointer_cast<FFmpegContent>(i);
293                         if (c && !c->kdm_timing_window_valid()) {
294                                 ok = false;
295                         }
296                 }
297 #endif
298
299                 if (!ok) {
300                         error_dialog (this, _("The KDM does not allow playback of this content at this time."));
301                 }
302
303                 return ok;
304         }
305
306         void playback_started (DCPTime time)
307         {
308                 /* XXX: this only logs the first piece of content; probably should be each piece? */
309                 if (_film->content().empty()) {
310                         return;
311                 }
312
313                 shared_ptr<DCPContent> dcp = dynamic_pointer_cast<DCPContent>(_film->content().front());
314                 if (dcp) {
315                         DCPExaminer ex (dcp, true);
316                         shared_ptr<dcp::CPL> playing_cpl;
317                         BOOST_FOREACH (shared_ptr<dcp::CPL> i, ex.cpls()) {
318                                 if (!dcp->cpl() || i->id() == *dcp->cpl()) {
319                                         playing_cpl = i;
320                                 }
321                         }
322                         DCPOMATIC_ASSERT (playing_cpl);
323
324                         _controls->log (
325                                 wxString::Format(
326                                         "playback-started %s %s %s",
327                                         time.timecode(_film->video_frame_rate()).c_str(),
328                                         dcp->directories().front().string().c_str(),
329                                         playing_cpl->annotation_text().c_str()
330                                         )
331                                 );
332                 }
333
334                 shared_ptr<FFmpegContent> ffmpeg = dynamic_pointer_cast<FFmpegContent>(_film->content().front());
335                 if (ffmpeg) {
336                         _controls->log (
337                                 wxString::Format(
338                                         "playback-started %s %s",
339                                         time.timecode(_film->video_frame_rate()).c_str(),
340                                         ffmpeg->path(0).string().c_str()
341                                         )
342                                 );
343                 }
344         }
345
346         void playback_stopped (DCPTime time)
347         {
348 #ifdef DCPOMATIC_VARIANT_SWAROOP
349                 try {
350                         boost::filesystem::remove (Config::path("position"));
351                 } catch (...) {
352                         /* Never mind */
353                 }
354 #endif
355
356                 _controls->log (wxString::Format("playback-stopped %s", time.timecode(_film->video_frame_rate()).c_str()));
357         }
358
359         void set_decode_reduction (optional<int> reduction)
360         {
361                 _viewer->set_dcp_decode_reduction (reduction);
362                 _info->triggered_update ();
363                 Config::instance()->set_decode_reduction (reduction);
364         }
365
366         void load_dcp (boost::filesystem::path dir)
367         {
368                 DCPOMATIC_ASSERT (_film);
369
370                 reset_film ();
371                 try {
372                         shared_ptr<DCPContent> dcp (new DCPContent(dir));
373                         _film->examine_and_add_content (dcp, true);
374                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
375                         if (!ok || !report_errors_from_last_job(this)) {
376                                 return;
377                         }
378 #ifndef DCPOMATIC_VARIANT_SWAROOP
379                         Config::instance()->add_to_player_history (dir);
380 #endif
381                 } catch (dcp::DCPReadError& e) {
382                         error_dialog (this, wxString::Format(_("Could not load a DCP from %s"), std_to_wx(dir.string())), std_to_wx(e.what()));
383                 }
384         }
385
386         void reset_film_weak (weak_ptr<Film> weak_film)
387         {
388                 shared_ptr<Film> film = weak_film.lock ();
389                 if (film) {
390                         reset_film (film);
391                 }
392         }
393
394         void reset_film (shared_ptr<Film> film = shared_ptr<Film>(new Film(optional<boost::filesystem::path>())))
395         {
396                 _film = film;
397                 _film->set_tolerant (true);
398                 _film->set_audio_channels (MAX_DCP_AUDIO_CHANNELS);
399                 _viewer->set_film (_film);
400                 _controls->set_film (_film);
401                 _film->Change.connect (bind(&DOMFrame::film_changed, this, _1, _2));
402                 _info->triggered_update ();
403         }
404
405         void film_changed (ChangeType type, Film::Property property)
406         {
407                 if (type != CHANGE_TYPE_DONE || property != Film::CONTENT) {
408                         return;
409                 }
410
411                 if (_viewer->playing ()) {
412                         _viewer->stop ();
413                 }
414
415                 /* Start off as Flat */
416                 _film->set_container (Ratio::from_id("185"));
417
418                 BOOST_FOREACH (shared_ptr<Content> i, _film->content()) {
419                         shared_ptr<DCPContent> dcp = dynamic_pointer_cast<DCPContent>(i);
420
421                         BOOST_FOREACH (shared_ptr<TextContent> j, i->text) {
422                                 j->set_use (true);
423                         }
424
425                         if (i->video) {
426                                 Ratio const * r = Ratio::nearest_from_ratio(i->video->size().ratio());
427                                 if (r->id() == "239") {
428                                         /* Any scope content means we use scope */
429                                         _film->set_container(r);
430                                 }
431                         }
432
433                         /* Any 3D content means we use 3D mode */
434                         if (i->video && i->video->frame_type() != VIDEO_FRAME_TYPE_2D) {
435                                 _film->set_three_d (true);
436                         }
437                 }
438
439                 _viewer->seek (DCPTime(), true);
440                 _info->triggered_update ();
441
442                 set_menu_sensitivity ();
443
444                 wxMenuItemList old = _cpl_menu->GetMenuItems();
445                 for (wxMenuItemList::iterator i = old.begin(); i != old.end(); ++i) {
446                         _cpl_menu->Remove (*i);
447                 }
448
449                 if (_film->content().size() == 1) {
450                         /* Offer a CPL menu */
451                         shared_ptr<DCPContent> first = dynamic_pointer_cast<DCPContent>(_film->content().front());
452                         if (first) {
453                                 DCPExaminer ex (first, true);
454                                 int id = ID_view_cpl;
455                                 BOOST_FOREACH (shared_ptr<dcp::CPL> i, ex.cpls()) {
456                                         wxMenuItem* j = _cpl_menu->AppendRadioItem(
457                                                 id,
458                                                 wxString::Format("%s (%s)", std_to_wx(i->annotation_text()).data(), std_to_wx(i->id()).data())
459                                                 );
460                                         j->Check(!first->cpl() || i->id() == *first->cpl());
461                                         ++id;
462                                 }
463                         }
464                 }
465         }
466
467 private:
468
469         bool report_errors_from_last_job (wxWindow* parent) const
470         {
471                 JobManager* jm = JobManager::instance ();
472
473                 DCPOMATIC_ASSERT (!jm->get().empty());
474
475                 shared_ptr<Job> last = jm->get().back();
476                 if (last->finished_in_error()) {
477                         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()));
478                         return false;
479                 }
480
481                 return true;
482         }
483
484         void setup_menu (wxMenuBar* m)
485         {
486                 _file_menu = new wxMenu;
487                 _file_menu->Append (ID_file_open, _("&Open...\tCtrl-O"));
488                 _file_add_ov = _file_menu->Append (ID_file_add_ov, _("&Add OV..."));
489                 _file_add_kdm = _file_menu->Append (ID_file_add_kdm, _("Add &KDM..."));
490
491                 _history_position = _file_menu->GetMenuItems().GetCount();
492
493                 _file_menu->AppendSeparator ();
494                 _file_menu->Append (ID_file_close, _("&Close"));
495                 _file_menu->AppendSeparator ();
496
497 #ifdef __WXOSX__
498                 _file_menu->Append (wxID_EXIT, _("&Exit"));
499 #else
500                 _file_menu->Append (wxID_EXIT, _("&Quit"));
501 #endif
502
503 #ifdef __WXOSX__
504                 wxMenuItem* prefs = _file_menu->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
505 #else
506                 wxMenu* edit = new wxMenu;
507                 wxMenuItem* prefs = edit->Append (wxID_PREFERENCES, _("&Preferences...\tCtrl-P"));
508 #endif
509
510                 prefs->Enable (Config::instance()->have_write_permission());
511
512                 _cpl_menu = new wxMenu;
513
514                 wxMenu* view = new wxMenu;
515                 optional<int> c = Config::instance()->decode_reduction();
516                 _view_cpl = view->Append(ID_view_cpl, _("CPL"), _cpl_menu);
517                 view->AppendSeparator();
518 #ifndef DCPOMATIC_VARIANT_SWAROOP
519                 _view_full_screen = view->AppendCheckItem(ID_view_full_screen, _("Full screen\tF11"));
520                 _view_dual_screen = view->AppendCheckItem(ID_view_dual_screen, _("Dual screen\tShift+F11"));
521 #endif
522                 setup_menu ();
523                 view->AppendSeparator();
524                 view->Append(ID_view_closed_captions, _("Closed captions..."));
525                 view->AppendSeparator();
526                 view->AppendRadioItem(ID_view_scale_appropriate, _("Set decode resolution to match display"))->Check(!static_cast<bool>(c));
527                 view->AppendRadioItem(ID_view_scale_full, _("Decode at full resolution"))->Check(c && c.get() == 0);
528                 view->AppendRadioItem(ID_view_scale_half, _("Decode at half resolution"))->Check(c && c.get() == 1);
529                 view->AppendRadioItem(ID_view_scale_quarter, _("Decode at quarter resolution"))->Check(c && c.get() == 2);
530
531                 wxMenu* tools = new wxMenu;
532                 _tools_verify = tools->Append (ID_tools_verify, _("Verify DCP"));
533                 tools->AppendSeparator ();
534                 tools->Append (ID_tools_check_for_updates, _("Check for updates"));
535                 tools->Append (ID_tools_timing, _("Timing..."));
536                 tools->Append (ID_tools_system_information, _("System information..."));
537
538                 wxMenu* help = new wxMenu;
539 #ifdef __WXOSX__
540                 help->Append (wxID_ABOUT, _("About DCP-o-matic"));
541 #else
542                 help->Append (wxID_ABOUT, _("About"));
543 #endif
544                 help->Append (ID_help_report_a_problem, _("Report a problem..."));
545
546                 m->Append (_file_menu, _("&File"));
547 #ifndef __WXOSX__
548                 m->Append (edit, _("&Edit"));
549 #endif
550                 m->Append (view, _("&View"));
551                 m->Append (tools, _("&Tools"));
552                 m->Append (help, _("&Help"));
553         }
554
555         void file_open ()
556         {
557                 wxString d = wxStandardPaths::Get().GetDocumentsDir();
558                 if (Config::instance()->last_player_load_directory()) {
559                         d = std_to_wx (Config::instance()->last_player_load_directory()->string());
560                 }
561
562                 wxDirDialog* c = new wxDirDialog (this, _("Select DCP to open"), d, wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST);
563
564                 int r;
565                 while (true) {
566                         r = c->ShowModal ();
567                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
568                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
569                         } else {
570                                 break;
571                         }
572                 }
573
574                 if (r == wxID_OK) {
575                         boost::filesystem::path const dcp (wx_to_std (c->GetPath ()));
576                         load_dcp (dcp);
577                         Config::instance()->set_last_player_load_directory (dcp.parent_path());
578                 }
579
580                 c->Destroy ();
581         }
582
583         void file_add_ov ()
584         {
585                 wxDirDialog* c = new wxDirDialog (
586                         this,
587                         _("Select DCP to open as OV"),
588                         wxStandardPaths::Get().GetDocumentsDir(),
589                         wxDEFAULT_DIALOG_STYLE | wxDD_DIR_MUST_EXIST
590                         );
591
592                 int r;
593                 while (true) {
594                         r = c->ShowModal ();
595                         if (r == wxID_OK && c->GetPath() == wxStandardPaths::Get().GetDocumentsDir()) {
596                                 error_dialog (this, _("You did not select a folder.  Make sure that you select a folder before clicking Open."));
597                         } else {
598                                 break;
599                         }
600                 }
601
602                 if (r == wxID_OK) {
603                         DCPOMATIC_ASSERT (_film);
604                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
605                         DCPOMATIC_ASSERT (dcp);
606                         dcp->add_ov (wx_to_std(c->GetPath()));
607                         JobManager::instance()->add(shared_ptr<Job>(new ExamineContentJob (_film, dcp)));
608                         bool const ok = display_progress (_("DCP-o-matic Player"), _("Loading content"));
609                         if (!ok || !report_errors_from_last_job(this)) {
610                                 return;
611                         }
612                         BOOST_FOREACH (shared_ptr<TextContent> i, dcp->text) {
613                                 i->set_use (true);
614                         }
615                         if (dcp->video) {
616                                 Ratio const * r = Ratio::nearest_from_ratio(dcp->video->size().ratio());
617                                 if (r) {
618                                         _film->set_container(r);
619                                 }
620                         }
621                 }
622
623                 c->Destroy ();
624                 _info->triggered_update ();
625         }
626
627         void file_add_kdm ()
628         {
629                 wxFileDialog* d = new wxFileDialog (this, _("Select KDM"));
630
631                 if (d->ShowModal() == wxID_OK) {
632                         DCPOMATIC_ASSERT (_film);
633 #ifdef DCPOMATIC_VARIANT_SWAROOP
634                         shared_ptr<FFmpegContent> ffmpeg = boost::dynamic_pointer_cast<FFmpegContent>(_film->content().front());
635                         if (ffmpeg) {
636                                 try {
637                                         ffmpeg->add_kdm (EncryptedECinemaKDM(dcp::file_to_string(wx_to_std(d->GetPath()), MAX_KDM_SIZE)));
638                                 } catch (exception& e) {
639                                         error_dialog (this, wxString::Format(_("Could not load KDM.")), std_to_wx(e.what()));
640                                         d->Destroy();
641                                         return;
642                                 }
643                         }
644 #endif
645                         shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
646 #ifndef DCPOMATIC_VARIANT_SWAROOP
647                         DCPOMATIC_ASSERT (dcp);
648 #endif
649                         try {
650                                 if (dcp) {
651                                         dcp->add_kdm (dcp::EncryptedKDM(dcp::file_to_string(wx_to_std(d->GetPath()), MAX_KDM_SIZE)));
652                                         dcp->examine (_film, shared_ptr<Job>());
653                                 }
654                         } catch (exception& e) {
655                                 error_dialog (this, wxString::Format (_("Could not load KDM.")), std_to_wx(e.what()));
656                                 d->Destroy ();
657                                 return;
658                         }
659                 }
660
661                 d->Destroy ();
662                 _info->triggered_update ();
663         }
664
665         void file_history (wxCommandEvent& event)
666         {
667                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
668                 int n = event.GetId() - ID_file_history;
669                 if (n >= 0 && n < static_cast<int> (history.size ())) {
670                         try {
671                                 load_dcp (history[n]);
672                         } catch (exception& e) {
673                                 error_dialog (0, std_to_wx(String::compose(wx_to_std(_("Could not load DCP %1.")), history[n])), std_to_wx(e.what()));
674                         }
675                 }
676         }
677
678         void file_close ()
679         {
680                 reset_film ();
681                 _info->triggered_update ();
682                 set_menu_sensitivity ();
683         }
684
685         void file_exit ()
686         {
687                 Close ();
688         }
689
690         void edit_preferences ()
691         {
692                 if (!Config::instance()->have_write_permission()) {
693                         return;
694                 }
695
696                 if (!_config_dialog) {
697                         _config_dialog = create_player_config_dialog ();
698                 }
699                 _config_dialog->Show (this);
700         }
701
702         void view_cpl (wxCommandEvent& ev)
703         {
704                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
705                 DCPOMATIC_ASSERT (dcp);
706                 DCPExaminer ex (dcp, true);
707                 int id = ev.GetId() - ID_view_cpl;
708                 DCPOMATIC_ASSERT (id >= 0);
709                 DCPOMATIC_ASSERT (id < int(ex.cpls().size()));
710                 list<shared_ptr<dcp::CPL> > cpls = ex.cpls();
711                 list<shared_ptr<dcp::CPL> >::iterator i = cpls.begin();
712                 while (id > 0) {
713                         ++i;
714                         --id;
715                 }
716
717                 dcp->set_cpl ((*i)->id());
718                 dcp->examine (_film, shared_ptr<Job>());
719         }
720
721         void view_full_screen ()
722         {
723                 if (_mode == Config::PLAYER_MODE_FULL) {
724                         _mode = Config::PLAYER_MODE_WINDOW;
725                 } else {
726                         _mode = Config::PLAYER_MODE_FULL;
727                 }
728                 setup_screen ();
729                 setup_menu ();
730         }
731
732         void view_dual_screen ()
733         {
734                 if (_mode == Config::PLAYER_MODE_DUAL) {
735                         _mode = Config::PLAYER_MODE_WINDOW;
736                 } else {
737                         _mode = Config::PLAYER_MODE_DUAL;
738                 }
739                 setup_screen ();
740                 setup_menu ();
741         }
742
743         void setup_menu ()
744         {
745                 if (_view_full_screen) {
746                         _view_full_screen->Check (_mode == Config::PLAYER_MODE_FULL);
747                 }
748                 if (_view_dual_screen) {
749                         _view_dual_screen->Check (_mode == Config::PLAYER_MODE_DUAL);
750                 }
751         }
752
753         void setup_screen ()
754         {
755                 _controls->Show (_mode != Config::PLAYER_MODE_FULL);
756                 _info->Show (_mode != Config::PLAYER_MODE_FULL);
757                 _overall_panel->SetBackgroundColour (_mode == Config::PLAYER_MODE_FULL ? wxColour(0, 0, 0) : wxNullColour);
758                 ShowFullScreen (_mode == Config::PLAYER_MODE_FULL);
759                 _viewer->set_pad_black (_mode != Config::PLAYER_MODE_WINDOW);
760
761                 if (_mode == Config::PLAYER_MODE_DUAL) {
762                         _dual_screen = new wxFrame (this, wxID_ANY, wxT(""));
763                         _dual_screen->SetBackgroundColour (wxColour(0, 0, 0));
764                         _dual_screen->ShowFullScreen (true);
765                         _viewer->panel()->Reparent (_dual_screen);
766                         _dual_screen->Show ();
767                         if (wxDisplay::GetCount() > 1) {
768                                 switch (Config::instance()->image_display()) {
769                                 case 0:
770                                         _dual_screen->Move (0, 0);
771                                         Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
772                                         break;
773                                 case 1:
774                                         _dual_screen->Move (wxDisplay(0).GetClientArea().GetWidth(), 0);
775                                         // (0, 0) doesn't seem to work for some strange reason
776                                         Move (8, 8);
777                                         break;
778                                 }
779                         }
780                 } else {
781                         if (_dual_screen) {
782                                 _viewer->panel()->Reparent (_overall_panel);
783                                 _dual_screen->Destroy ();
784                                 _dual_screen = 0;
785                         }
786                 }
787
788                 setup_main_sizer (_mode);
789         }
790
791         void view_closed_captions ()
792         {
793                 _viewer->show_closed_captions ();
794         }
795
796         void tools_verify ()
797         {
798                 shared_ptr<DCPContent> dcp = boost::dynamic_pointer_cast<DCPContent>(_film->content().front());
799                 DCPOMATIC_ASSERT (dcp);
800
801                 JobManager* jm = JobManager::instance ();
802                 jm->add (shared_ptr<Job> (new VerifyDCPJob (dcp->directories())));
803                 bool const ok = display_progress (_("DCP-o-matic Player"), _("Verifying DCP"));
804                 if (!ok) {
805                         return;
806                 }
807
808                 DCPOMATIC_ASSERT (!jm->get().empty());
809                 shared_ptr<VerifyDCPJob> last = dynamic_pointer_cast<VerifyDCPJob> (jm->get().back());
810                 DCPOMATIC_ASSERT (last);
811
812                 VerifyDCPDialog* d = new VerifyDCPDialog (this, last);
813                 d->ShowModal ();
814                 d->Destroy ();
815         }
816
817         void tools_check_for_updates ()
818         {
819                 UpdateChecker::instance()->run ();
820                 _update_news_requested = true;
821         }
822
823         void tools_timing ()
824         {
825                 TimerDisplay* d = new TimerDisplay (this, _viewer->state_timer(), _viewer->gets());
826                 d->ShowModal ();
827                 d->Destroy ();
828         }
829
830         void tools_system_information ()
831         {
832                 if (!_system_information_dialog) {
833                         _system_information_dialog = new SystemInformationDialog (this, _viewer);
834                 }
835
836                 _system_information_dialog->Show ();
837         }
838
839         void help_about ()
840         {
841                 AboutDialog* d = new AboutDialog (this);
842                 d->ShowModal ();
843                 d->Destroy ();
844         }
845
846         void help_report_a_problem ()
847         {
848                 ReportProblemDialog* d = new ReportProblemDialog (this);
849                 if (d->ShowModal () == wxID_OK) {
850                         d->report ();
851                 }
852                 d->Destroy ();
853         }
854
855         void update_checker_state_changed ()
856         {
857                 UpdateChecker* uc = UpdateChecker::instance ();
858
859                 bool const announce =
860                         _update_news_requested ||
861                         (uc->stable() && Config::instance()->check_for_updates()) ||
862                         (uc->test() && Config::instance()->check_for_updates() && Config::instance()->check_for_test_updates());
863
864                 _update_news_requested = false;
865
866                 if (!announce) {
867                         return;
868                 }
869
870                 if (uc->state() == UpdateChecker::YES) {
871                         UpdateDialog* dialog = new UpdateDialog (this, uc->stable (), uc->test ());
872                         dialog->ShowModal ();
873                         dialog->Destroy ();
874                 } else if (uc->state() == UpdateChecker::FAILED) {
875                         error_dialog (this, _("The DCP-o-matic download server could not be contacted."));
876                 } else {
877                         error_dialog (this, _("There are no new versions of DCP-o-matic available."));
878                 }
879
880                 _update_news_requested = false;
881         }
882
883         void config_changed (Config::Property prop)
884         {
885                 /* Instantly save any config changes when using the player GUI */
886                 try {
887                         Config::instance()->write_config();
888                 } catch (FileError& e) {
889                         if (prop != Config::HISTORY) {
890                                 error_dialog (
891                                         this,
892                                         wxString::Format(
893                                                 _("Could not write to config file at %s.  Your changes have not been saved."),
894                                                 std_to_wx(e.file().string())
895                                                 )
896                                         );
897                         }
898                 } catch (exception& e) {
899                         error_dialog (
900                                 this,
901                                 _("Could not write to config file.  Your changes have not been saved.")
902                                 );
903                 }
904
905                 update_from_config (prop);
906         }
907
908         void update_from_config (Config::Property prop)
909         {
910                 for (int i = 0; i < _history_items; ++i) {
911                         delete _file_menu->Remove (ID_file_history + i);
912                 }
913
914                 if (_history_separator) {
915                         _file_menu->Remove (_history_separator);
916                 }
917                 delete _history_separator;
918                 _history_separator = 0;
919
920                 int pos = _history_position;
921
922                 /* Clear out non-existant history items before we re-build the menu */
923                 Config::instance()->clean_player_history ();
924                 vector<boost::filesystem::path> history = Config::instance()->player_history ();
925
926                 if (!history.empty ()) {
927                         _history_separator = _file_menu->InsertSeparator (pos++);
928                 }
929
930                 for (size_t i = 0; i < history.size(); ++i) {
931                         string s;
932                         if (i < 9) {
933                                 s = String::compose ("&%1 %2", i + 1, history[i].string());
934                         } else {
935                                 s = history[i].string();
936                         }
937                         _file_menu->Insert (pos++, ID_file_history + i, std_to_wx (s));
938                 }
939
940                 _history_items = history.size ();
941
942                 if (prop == Config::PLAYER_DEBUG_LOG) {
943                         optional<boost::filesystem::path> p = Config::instance()->player_debug_log_file();
944                         if (p) {
945                                 dcpomatic_log.reset (new FileLog(*p));
946                         } else {
947                                 dcpomatic_log.reset (new NullLog());
948                         }
949                         dcpomatic_log->set_types (LogEntry::TYPE_GENERAL | LogEntry::TYPE_WARNING | LogEntry::TYPE_ERROR | LogEntry::TYPE_DEBUG_PLAYER);
950                 }
951         }
952
953         void set_menu_sensitivity ()
954         {
955                 _tools_verify->Enable (static_cast<bool>(_film));
956                 _file_add_ov->Enable (static_cast<bool>(_film));
957                 _file_add_kdm->Enable (static_cast<bool>(_film));
958                 _view_cpl->Enable (static_cast<bool>(_film));
959         }
960
961         void start_stop_pressed ()
962         {
963                 if (_viewer->playing()) {
964                         _viewer->stop();
965                 } else {
966                         _viewer->start();
967                 }
968         }
969
970         void back_frame ()
971         {
972                 _viewer->seek_by (-_viewer->one_video_frame(), true);
973         }
974
975         void forward_frame ()
976         {
977                 _viewer->seek_by (_viewer->one_video_frame(), true);
978         }
979
980 private:
981
982         wxFrame* _dual_screen;
983         bool _update_news_requested;
984         PlayerInformation* _info;
985         Config::PlayerMode _mode;
986         wxPreferencesEditor* _config_dialog;
987         wxPanel* _overall_panel;
988         wxMenu* _file_menu;
989         wxMenuItem* _view_cpl;
990         wxMenu* _cpl_menu;
991         int _history_items;
992         int _history_position;
993         wxMenuItem* _history_separator;
994         shared_ptr<FilmViewer> _viewer;
995         Controls* _controls;
996         SystemInformationDialog* _system_information_dialog;
997         boost::shared_ptr<Film> _film;
998         boost::signals2::scoped_connection _config_changed_connection;
999         wxMenuItem* _file_add_ov;
1000         wxMenuItem* _file_add_kdm;
1001         wxMenuItem* _tools_verify;
1002         wxMenuItem* _view_full_screen;
1003         wxMenuItem* _view_dual_screen;
1004 };
1005
1006 static const wxCmdLineEntryDesc command_line_description[] = {
1007         { wxCMD_LINE_PARAM, 0, 0, "DCP to load or create", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1008         { wxCMD_LINE_OPTION, "c", "config", "Directory containing config.xml", wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
1009         { wxCMD_LINE_NONE, "", "", "", wxCmdLineParamType (0), 0 }
1010 };
1011
1012 class PlayServer : public Server
1013 {
1014 public:
1015         explicit PlayServer (DOMFrame* frame)
1016                 : Server (PLAYER_PLAY_PORT)
1017                 , _frame (frame)
1018         {}
1019
1020         void handle (shared_ptr<Socket> socket)
1021         {
1022                 try {
1023                         int const length = socket->read_uint32 ();
1024                         scoped_array<char> buffer (new char[length]);
1025                         socket->read (reinterpret_cast<uint8_t*> (buffer.get()), length);
1026                         string s (buffer.get());
1027                         signal_manager->when_idle (bind (&DOMFrame::load_dcp, _frame, s));
1028                         socket->write (reinterpret_cast<uint8_t const *> ("OK"), 3);
1029                 } catch (...) {
1030
1031                 }
1032         }
1033
1034 private:
1035         DOMFrame* _frame;
1036 };
1037
1038 /** @class App
1039  *  @brief The magic App class for wxWidgets.
1040  */
1041 class App : public wxApp
1042 {
1043 public:
1044         App ()
1045                 : wxApp ()
1046                 , _frame (0)
1047         {}
1048
1049 private:
1050
1051         bool OnInit ()
1052         {
1053                 wxSplashScreen* splash = 0;
1054                 try {
1055                         wxInitAllImageHandlers ();
1056
1057                         Config::FailedToLoad.connect (boost::bind (&App::config_failed_to_load, this));
1058                         Config::Warning.connect (boost::bind (&App::config_warning, this, _1));
1059
1060                         splash = maybe_show_splash ();
1061
1062                         SetAppName (_("DCP-o-matic Player"));
1063
1064                         if (!wxApp::OnInit()) {
1065                                 return false;
1066                         }
1067
1068 #ifdef DCPOMATIC_LINUX
1069                         unsetenv ("UBUNTU_MENUPROXY");
1070 #endif
1071
1072 #ifdef __WXOSX__
1073                         ProcessSerialNumber serial;
1074                         GetCurrentProcess (&serial);
1075                         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
1076 #endif
1077
1078                         dcpomatic_setup_path_encoding ();
1079
1080                         /* Enable i18n; this will create a Config object
1081                            to look for a force-configured language.  This Config
1082                            object will be wrong, however, because dcpomatic_setup
1083                            hasn't yet been called and there aren't any filters etc.
1084                            set up yet.
1085                         */
1086                         dcpomatic_setup_i18n ();
1087
1088                         /* Set things up, including filters etc.
1089                            which will now be internationalised correctly.
1090                         */
1091                         dcpomatic_setup ();
1092
1093                         /* Force the configuration to be re-loaded correctly next
1094                            time it is needed.
1095                         */
1096                         Config::drop ();
1097
1098                         signal_manager = new wxSignalManager (this);
1099
1100                         _frame = new DOMFrame ();
1101                         SetTopWindow (_frame);
1102                         _frame->Maximize ();
1103                         if (splash) {
1104                                 splash->Destroy ();
1105                                 splash = 0;
1106                         }
1107                         _frame->Show ();
1108
1109                         PlayServer* server = new PlayServer (_frame);
1110                         new thread (boost::bind (&PlayServer::run, server));
1111
1112                         if (!_dcp_to_load.empty() && boost::filesystem::is_directory (_dcp_to_load)) {
1113                                 try {
1114                                         _frame->load_dcp (_dcp_to_load);
1115                                 } catch (exception& e) {
1116                                         error_dialog (0, std_to_wx (String::compose (wx_to_std (_("Could not load DCP %1.")), _dcp_to_load)), std_to_wx(e.what()));
1117                                 }
1118                         }
1119
1120                         Bind (wxEVT_IDLE, boost::bind (&App::idle, this));
1121
1122                         if (Config::instance()->check_for_updates ()) {
1123                                 UpdateChecker::instance()->run ();
1124                         }
1125                 }
1126                 catch (exception& e)
1127                 {
1128                         if (splash) {
1129                                 splash->Destroy ();
1130                         }
1131                         error_dialog (0, _("DCP-o-matic Player could not start."), std_to_wx(e.what()));
1132                 }
1133
1134                 return true;
1135         }
1136
1137         void OnInitCmdLine (wxCmdLineParser& parser)
1138         {
1139                 parser.SetDesc (command_line_description);
1140                 parser.SetSwitchChars (wxT ("-"));
1141         }
1142
1143         bool OnCmdLineParsed (wxCmdLineParser& parser)
1144         {
1145                 if (parser.GetParamCount() > 0) {
1146                         _dcp_to_load = wx_to_std (parser.GetParam (0));
1147                 }
1148
1149                 wxString config;
1150                 if (parser.Found("c", &config)) {
1151                         Config::override_path = wx_to_std (config);
1152                 }
1153
1154                 return true;
1155         }
1156
1157         void report_exception ()
1158         {
1159                 try {
1160                         throw;
1161                 } catch (FileError& e) {
1162                         error_dialog (
1163                                 0,
1164                                 wxString::Format (
1165                                         _("An exception occurred: %s (%s)\n\n") + REPORT_PROBLEM,
1166                                         std_to_wx (e.what()),
1167                                         std_to_wx (e.file().string().c_str ())
1168                                         )
1169                                 );
1170                 } catch (exception& e) {
1171                         error_dialog (
1172                                 0,
1173                                 wxString::Format (
1174                                         _("An exception occurred: %s.\n\n") + REPORT_PROBLEM,
1175                                         std_to_wx (e.what ())
1176                                         )
1177                                 );
1178                 } catch (...) {
1179                         error_dialog (0, _("An unknown exception occurred.") + "  " + REPORT_PROBLEM);
1180                 }
1181         }
1182
1183         /* An unhandled exception has occurred inside the main event loop */
1184         bool OnExceptionInMainLoop ()
1185         {
1186                 report_exception ();
1187                 /* This will terminate the program */
1188                 return false;
1189         }
1190
1191         void OnUnhandledException ()
1192         {
1193                 report_exception ();
1194         }
1195
1196         void idle ()
1197         {
1198                 signal_manager->ui_idle ();
1199         }
1200
1201         void config_failed_to_load ()
1202         {
1203                 message_dialog (_frame, _("The existing configuration failed to load.  Default values will be used instead.  These may take a short time to create."));
1204         }
1205
1206         void config_warning (string m)
1207         {
1208                 message_dialog (_frame, std_to_wx (m));
1209         }
1210
1211         DOMFrame* _frame;
1212         string _dcp_to_load;
1213 };
1214
1215 IMPLEMENT_APP (App)