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