swaroop: basics of encrypted MP4 playback.
[dcpomatic.git] / src / wx / swaroop_controls.cc
1 /*
2     Copyright (C) 2018-2019 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "swaroop_controls.h"
22 #include "film_viewer.h"
23 #include "wx_util.h"
24 #include "content_view.h"
25 #include "dcpomatic_button.h"
26 #include "static_text.h"
27 #include "lib/player_video.h"
28 #include "lib/dcp_content.h"
29 #include "lib/cross.h"
30 #include "lib/scoped_temporary.h"
31 #include "lib/internet.h"
32 #include "lib/ffmpeg_content.h"
33 #include <dcp/raw_convert.h>
34 #include <dcp/exceptions.h>
35 #include <wx/listctrl.h>
36 #include <wx/progdlg.h>
37
38 using std::string;
39 using std::cout;
40 using std::exception;
41 using std::sort;
42 using boost::shared_ptr;
43 using boost::dynamic_pointer_cast;
44 using boost::optional;
45 using namespace dcpomatic;
46
47 SwaroopControls::SwaroopControls (wxWindow* parent, shared_ptr<FilmViewer> viewer)
48         : Controls (parent, viewer, false)
49         , _play_button (new Button(this, _("Play")))
50         , _pause_button (new Button(this, _("Pause")))
51         , _stop_button (new Button(this, _("Stop")))
52         , _next_button (new Button(this, "Next"))
53         , _previous_button (new Button(this, "Previous"))
54         , _current_disable_timeline (false)
55         , _current_disable_next (false)
56 {
57         _button_sizer->Add (_previous_button, 0, wxEXPAND);
58         _button_sizer->Add (_play_button, 0, wxEXPAND);
59         _button_sizer->Add (_pause_button, 0, wxEXPAND);
60         _button_sizer->Add (_stop_button, 0, wxEXPAND);
61         _button_sizer->Add (_next_button, 0, wxEXPAND);
62
63         _spl_view = new wxListCtrl (this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT | wxLC_NO_HEADER);
64         _spl_view->AppendColumn (wxT(""), wxLIST_FORMAT_LEFT, 740);
65
66         wxBoxSizer* left_sizer = new wxBoxSizer (wxVERTICAL);
67         wxBoxSizer* e_sizer = new wxBoxSizer (wxHORIZONTAL);
68
69         wxFont subheading_font (*wxNORMAL_FONT);
70         subheading_font.SetWeight (wxFONTWEIGHT_BOLD);
71
72         wxBoxSizer* spl_header = new wxBoxSizer (wxHORIZONTAL);
73         {
74                 wxStaticText* m = new StaticText (this, "Playlists");
75                 m->SetFont (subheading_font);
76                 spl_header->Add (m, 1, wxALIGN_CENTER_VERTICAL);
77         }
78         _refresh_spl_view = new Button (this, "Refresh");
79         spl_header->Add (_refresh_spl_view, 0, wxBOTTOM, DCPOMATIC_SIZER_GAP / 2);
80
81         left_sizer->Add (spl_header, 0, wxLEFT | wxRIGHT | wxEXPAND, DCPOMATIC_SIZER_GAP);
82         left_sizer->Add (_spl_view, 1, wxLEFT | wxRIGHT | wxBOTTOM | wxEXPAND, DCPOMATIC_SIZER_GAP);
83
84         _content_view = new ContentView (this);
85
86         wxBoxSizer* content_header = new wxBoxSizer (wxHORIZONTAL);
87         {
88                 wxStaticText* m = new StaticText (this, "Content");
89                 m->SetFont (subheading_font);
90                 content_header->Add (m, 1, wxALIGN_CENTER_VERTICAL);
91         }
92         _refresh_content_view = new Button (this, "Refresh");
93         content_header->Add (_refresh_content_view, 0, wxBOTTOM, DCPOMATIC_SIZER_GAP / 2);
94
95         left_sizer->Add (content_header, 0, wxTOP | wxLEFT | wxRIGHT | wxEXPAND, DCPOMATIC_SIZER_GAP);
96         left_sizer->Add (_content_view, 1, wxLEFT | wxRIGHT | wxBOTTOM | wxEXPAND, DCPOMATIC_SIZER_GAP);
97
98         _current_spl_view = new wxListCtrl (this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT | wxLC_NO_HEADER);
99         _current_spl_view->AppendColumn (wxT(""), wxLIST_FORMAT_LEFT, 500);
100         _current_spl_view->AppendColumn (wxT(""), wxLIST_FORMAT_LEFT, 80);
101         e_sizer->Add (left_sizer, 1, wxALL | wxEXPAND, DCPOMATIC_SIZER_GAP);
102         e_sizer->Add (_current_spl_view, 1, wxALL | wxEXPAND, DCPOMATIC_SIZER_GAP);
103
104         _v_sizer->Add (e_sizer, 1, wxEXPAND);
105
106         _log = new wxTextCtrl (this, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(-1, 200), wxTE_READONLY | wxTE_MULTILINE);
107         _v_sizer->Add (_log, 0, wxALL | wxEXPAND, DCPOMATIC_SIZER_GAP);
108
109         _play_button->Bind     (wxEVT_BUTTON, boost::bind(&SwaroopControls::play_clicked,  this));
110         _pause_button->Bind    (wxEVT_BUTTON, boost::bind(&SwaroopControls::pause_clicked, this));
111         _stop_button->Bind     (wxEVT_BUTTON, boost::bind(&SwaroopControls::stop_clicked,  this));
112         _next_button->Bind     (wxEVT_BUTTON, boost::bind(&SwaroopControls::next_clicked,  this));
113         _previous_button->Bind (wxEVT_BUTTON, boost::bind(&SwaroopControls::previous_clicked,  this));
114         _spl_view->Bind        (wxEVT_LIST_ITEM_SELECTED,   boost::bind(&SwaroopControls::spl_selection_changed, this));
115         _spl_view->Bind        (wxEVT_LIST_ITEM_DESELECTED, boost::bind(&SwaroopControls::spl_selection_changed, this));
116         _viewer->Finished.connect (boost::bind(&SwaroopControls::viewer_finished, this));
117         _viewer->PositionChanged.connect (boost::bind(&SwaroopControls::viewer_position_changed, this));
118         _refresh_spl_view->Bind (wxEVT_BUTTON, boost::bind(&SwaroopControls::update_playlist_directory, this));
119         _refresh_content_view->Bind (wxEVT_BUTTON, boost::bind(&ContentView::update, _content_view));
120
121         _content_view->update ();
122         update_playlist_directory ();
123
124         _viewer->set_background_image (true);
125 }
126
127 void
128 SwaroopControls::check_restart ()
129 {
130         cout << "check_restart called\n";
131         FILE* f = fopen_boost (Config::path("position"), "r");
132         if (!f) {
133                 cout << "could not open position file (" << errno << ")\n";
134                 return;
135         }
136
137         char id[64];
138         int index;
139         int64_t time;
140         fscanf (f, "%63s %d %ld", id, &index, &time);
141
142         cout << "Looking for playlist " << id << " to restart.\n";
143
144         for (size_t i = 0; i < _playlists.size(); ++i) {
145                 if (_playlists[i].id() == id) {
146                         cout << "Found playlist " << id << "\n";
147                         select_playlist (i, index);
148                         update_current_content ();
149                         _viewer->seek (DCPTime(time), false);
150                         _viewer->start ();
151                 }
152         }
153
154         fclose (f);
155 }
156
157 void
158 SwaroopControls::viewer_position_changed ()
159 {
160         if (!_selected_playlist || !_viewer->playing() || _viewer->position().get() % DCPTime::HZ) {
161                 return;
162         }
163
164         FILE* f = fopen_boost (Config::path("position"), "w");
165         if (f) {
166                 string const p = _playlists[*_selected_playlist].id()
167                         + " " + dcp::raw_convert<string>(_selected_playlist_position)
168                         + " " + dcp::raw_convert<string>(_viewer->position().get());
169
170                 checked_fwrite (p.c_str(), p.length(), f, Config::path("position"));
171 #ifdef DCPOMATIC_LINUX
172                 fflush (f);
173                 fsync (fileno(f));
174 #endif
175                 fclose (f);
176         }
177 }
178
179 void
180 SwaroopControls::started ()
181 {
182         Controls::started ();
183         _play_button->Enable (false);
184         _pause_button->Enable (true);
185         _viewer->set_background_image (false);
186 }
187
188 void
189 SwaroopControls::stopped ()
190 {
191         Controls::stopped ();
192         _play_button->Enable (true);
193         _pause_button->Enable (false);
194 }
195
196 void
197 SwaroopControls::play_clicked ()
198 {
199         _viewer->start ();
200 }
201
202 void
203 SwaroopControls::setup_sensitivity ()
204 {
205         Controls::setup_sensitivity ();
206         bool const active_job = _active_job && *_active_job != "examine_content";
207         bool const c = _film && !_film->content().empty() && !active_job;
208         _play_button->Enable (c && !_viewer->playing());
209         _pause_button->Enable (_viewer->playing());
210         _slider->Enable (!_current_disable_timeline);
211         _spl_view->Enable (!_viewer->playing());
212         _next_button->Enable (!_current_disable_next && can_do_next());
213         _previous_button->Enable (can_do_previous());
214 }
215
216 void
217 SwaroopControls::pause_clicked ()
218 {
219         _viewer->stop ();
220 }
221
222 void
223 SwaroopControls::stop_clicked ()
224 {
225         _viewer->stop ();
226         _viewer->seek (DCPTime(), true);
227         if (_selected_playlist) {
228                 _selected_playlist_position = 0;
229                 update_current_content ();
230         }
231         _viewer->set_background_image (true);
232 }
233
234 bool
235 SwaroopControls::can_do_previous ()
236 {
237         return _selected_playlist && (_selected_playlist_position - 1) >= 0;
238 }
239
240 void
241 SwaroopControls::previous_clicked ()
242 {
243         if (!can_do_previous ()) {
244                 return;
245         }
246
247         _selected_playlist_position--;
248         update_current_content ();
249 }
250
251 bool
252 SwaroopControls::can_do_next ()
253 {
254         return _selected_playlist && (_selected_playlist_position + 1) < int(_playlists[*_selected_playlist].get().size());
255 }
256
257 void
258 SwaroopControls::next_clicked ()
259 {
260         if (!can_do_next ()) {
261                 return;
262         }
263
264         _selected_playlist_position++;
265         update_current_content ();
266 }
267
268 void
269 SwaroopControls::log (wxString s)
270 {
271         struct timeval time;
272         gettimeofday (&time, 0);
273         char buffer[64];
274         time_t const sec = time.tv_sec;
275         struct tm* t = localtime (&sec);
276         strftime (buffer, 64, "%c", t);
277         wxString ts = std_to_wx(string(buffer)) + N_(": ");
278         _log->SetValue(_log->GetValue() + ts + s + "\n");
279
280         optional<boost::filesystem::path> log = Config::instance()->player_activity_log_file();
281         if (!log) {
282                 return;
283         }
284
285         FILE* f = fopen_boost (*log, "a");
286         fprintf (f, "%s%s\n", wx_to_std(ts).c_str(), wx_to_std(s).c_str());
287         fclose (f);
288 }
289
290 void
291 SwaroopControls::add_playlist_to_list (SPL spl)
292 {
293         int const N = _spl_view->GetItemCount();
294
295         wxListItem it;
296         it.SetId(N);
297         it.SetColumn(0);
298         string t = spl.name();
299         if (spl.missing()) {
300                 t += " (content missing)";
301         }
302         it.SetText (std_to_wx(t));
303         _spl_view->InsertItem (it);
304 }
305
306 struct SPLComparator
307 {
308         bool operator() (SPL const & a, SPL const & b) {
309                 return a.name() < b.name();
310         }
311 };
312
313 void
314 SwaroopControls::update_playlist_directory ()
315 {
316         using namespace boost::filesystem;
317
318         _spl_view->DeleteAllItems ();
319         optional<path> dir = Config::instance()->player_playlist_directory();
320         if (!dir) {
321                 return;
322         }
323
324         _playlists.clear ();
325
326         for (directory_iterator i = directory_iterator(*dir); i != directory_iterator(); ++i) {
327                 try {
328                         if (is_regular_file(i->path()) && i->path().extension() == ".xml") {
329                                 SPL spl;
330                                 spl.read (i->path(), _content_view);
331                                 _playlists.push_back (spl);
332                         }
333                 } catch (exception& e) {
334                         /* Never mind */
335                 }
336         }
337
338         sort (_playlists.begin(), _playlists.end(), SPLComparator());
339         BOOST_FOREACH (SPL i, _playlists) {
340                 add_playlist_to_list (i);
341         }
342
343         _selected_playlist = boost::none;
344 }
345
346 optional<dcp::EncryptedKDM>
347 SwaroopControls::get_kdm_from_url (shared_ptr<DCPContent> dcp)
348 {
349         ScopedTemporary temp;
350         string url = Config::instance()->kdm_server_url();
351         boost::algorithm::replace_all (url, "{CPL}", *dcp->cpl());
352         optional<dcp::EncryptedKDM> kdm;
353         if (dcp->cpl() && !get_from_url(url, false, false, temp)) {
354                 try {
355                         kdm = dcp::EncryptedKDM (dcp::file_to_string(temp.file()));
356                         if (kdm->cpl_id() != dcp->cpl()) {
357                                 kdm = boost::none;
358                         }
359                 } catch (std::exception& e) {
360                         /* Hey well */
361                 }
362         }
363         return kdm;
364 }
365
366 optional<dcp::EncryptedKDM>
367 SwaroopControls::get_kdm_from_directory (shared_ptr<DCPContent> dcp)
368 {
369         using namespace boost::filesystem;
370         optional<path> kdm_dir = Config::instance()->player_kdm_directory();
371         if (!kdm_dir) {
372                 return optional<dcp::EncryptedKDM>();
373         }
374         for (directory_iterator i = directory_iterator(*kdm_dir); i != directory_iterator(); ++i) {
375                 try {
376                         if (file_size(i->path()) < MAX_KDM_SIZE) {
377                                 dcp::EncryptedKDM kdm (dcp::file_to_string(i->path()));
378                                 if (kdm.cpl_id() == dcp->cpl()) {
379                                         return kdm;
380                                 }
381                         }
382                 } catch (std::exception& e) {
383                         /* Hey well */
384                 }
385         }
386         return optional<dcp::EncryptedKDM>();
387 }
388
389 optional<EncryptedECinemaKDM>
390 SwaroopControls::get_kdm_from_directory (shared_ptr<FFmpegContent> ffmpeg)
391 {
392         using namespace boost::filesystem;
393         optional<path> kdm_dir = Config::instance()->player_kdm_directory();
394         if (!kdm_dir) {
395                 return optional<EncryptedECinemaKDM>();
396         }
397         for (directory_iterator i = directory_iterator(*kdm_dir); i != directory_iterator(); ++i) {
398                 try {
399                         if (file_size(i->path()) < MAX_KDM_SIZE) {
400                                 EncryptedECinemaKDM kdm (dcp::file_to_string(i->path()));
401                                 if (kdm.id() == ffmpeg->id().get_value_or("")) {
402                                         return kdm;
403                                 }
404                         }
405                 } catch (std::exception& e) {
406                         /* Hey well */
407                 }
408         }
409         return optional<EncryptedECinemaKDM>();
410 }
411 void
412 SwaroopControls::spl_selection_changed ()
413 {
414         long int selected = _spl_view->GetNextItem (-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
415         if (selected == -1) {
416                 _current_spl_view->DeleteAllItems ();
417                 _selected_playlist = boost::none;
418                 return;
419         }
420
421         if (_playlists[selected].missing()) {
422                 error_dialog (this, "This playlist cannot be loaded as some content is missing.");
423                 _selected_playlist = boost::none;
424                 _spl_view->SetItemState (selected, 0, wxLIST_STATE_SELECTED);
425                 return;
426         }
427
428         if (_playlists[selected].get().empty()) {
429                 error_dialog (this, "This playlist is empty.");
430                 return;
431         }
432
433         select_playlist (selected, 0);
434 }
435
436 void
437 SwaroopControls::select_playlist (int selected, int position)
438 {
439         log (wxString::Format("load-playlist %s", std_to_wx(_playlists[selected].name()).data()));
440
441         wxProgressDialog dialog (_("DCP-o-matic"), "Loading playlist and KDMs");
442
443         BOOST_FOREACH (SPLEntry const & i, _playlists[selected].get()) {
444                 dialog.Pulse ();
445                 shared_ptr<DCPContent> dcp = dynamic_pointer_cast<DCPContent> (i.content);
446                 if (dcp && dcp->needs_kdm()) {
447                         optional<dcp::EncryptedKDM> kdm;
448                         kdm = get_kdm_from_url (dcp);
449                         if (!kdm) {
450                                 kdm = get_kdm_from_directory (dcp);
451                         }
452                         if (kdm) {
453                                 try {
454                                         dcp->add_kdm (*kdm);
455                                         dcp->examine (_film, shared_ptr<Job>());
456                                 } catch (KDMError& e) {
457                                         error_dialog (this, "Could not load KDM.");
458                                 }
459                         }
460                         if (dcp->needs_kdm()) {
461                                 /* We didn't get a KDM for this */
462                                 error_dialog (this, "This playlist cannot be loaded as a KDM is missing.");
463                                 _selected_playlist = boost::none;
464                                 _spl_view->SetItemState (selected, 0, wxLIST_STATE_SELECTED);
465                                 return;
466                         }
467                 }
468                 shared_ptr<FFmpegContent> ffmpeg = dynamic_pointer_cast<FFmpegContent> (i.content);
469                 if (ffmpeg && ffmpeg->encrypted()) {
470                         optional<EncryptedECinemaKDM> kdm = get_kdm_from_directory (ffmpeg);
471                         if (kdm) {
472                                 try {
473                                         ffmpeg->add_kdm (*kdm);
474                                 } catch (KDMError& e) {
475                                         error_dialog (this, "Could not load KDM.");
476                                 }
477                         } else {
478                                 error_dialog (this, "This playlist cannot be loaded as a KDM is missing.");
479                                 _selected_playlist = boost::none;
480                                 _spl_view->SetItemState (selected, 0, wxLIST_STATE_SELECTED);
481                                 return;
482                         }
483                 }
484         }
485
486         _current_spl_view->DeleteAllItems ();
487
488         int N = 0;
489         BOOST_FOREACH (SPLEntry i, _playlists[selected].get()) {
490                 wxListItem it;
491                 it.SetId (N);
492                 it.SetColumn (0);
493                 it.SetText (std_to_wx(i.name));
494                 _current_spl_view->InsertItem (it);
495                 ++N;
496         }
497
498         _selected_playlist = selected;
499         _selected_playlist_position = position;
500         dialog.Pulse ();
501         reset_film ();
502         dialog.Pulse ();
503         update_current_content ();
504 }
505
506 void
507 SwaroopControls::reset_film ()
508 {
509         DCPOMATIC_ASSERT (_selected_playlist);
510         shared_ptr<Film> film (new Film(optional<boost::filesystem::path>()));
511         film->add_content (_playlists[*_selected_playlist].get()[_selected_playlist_position].content);
512         ResetFilm (film);
513 }
514
515 void
516 SwaroopControls::config_changed (int property)
517 {
518         Controls::config_changed (property);
519
520         if (property == Config::PLAYER_CONTENT_DIRECTORY) {
521                 _content_view->update ();
522         } else if (property == Config::PLAYER_PLAYLIST_DIRECTORY) {
523                 update_playlist_directory ();
524         }
525 }
526
527 void
528 SwaroopControls::set_film (shared_ptr<Film> film)
529 {
530         Controls::set_film (film);
531         setup_sensitivity ();
532 }
533
534 void
535 SwaroopControls::update_current_content ()
536 {
537         DCPOMATIC_ASSERT (_selected_playlist);
538
539         wxProgressDialog dialog (_("DCP-o-matic"), "Loading content");
540
541         SPLEntry const & e = _playlists[*_selected_playlist].get()[_selected_playlist_position];
542         _current_disable_timeline = e.disable_timeline;
543         _current_disable_next = !e.skippable;
544
545         setup_sensitivity ();
546         dialog.Pulse ();
547         reset_film ();
548 }
549
550 void
551 SwaroopControls::viewer_finished ()
552 {
553         if (!_selected_playlist) {
554                 return;
555         }
556
557         bool const stop = _playlists[*_selected_playlist].get()[_selected_playlist_position].stop_after_play;
558
559         _selected_playlist_position++;
560         if (_selected_playlist_position < int(_playlists[*_selected_playlist].get().size())) {
561                 update_current_content ();
562                 if (!stop) {
563                         _viewer->start ();
564                 }
565         } else {
566                 _selected_playlist_position = 0;
567                 _viewer->set_background_image (true);
568                 ResetFilm (shared_ptr<Film>(new Film(optional<boost::filesystem::path>())));
569         }
570 }