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