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