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