vtl: reduce ardour<>xjadeo communication
[ardour.git] / gtk2_ardour / video_monitor.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3     Author: Robin Gareus <robin@gareus.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20 #include "pbd/file_utils.h"
21 #include "pbd/convert.h"
22 #include "gui_thread.h"
23 #include "ardour_ui.h"
24 #include "utils.h"
25
26 #include <stdio.h>
27 #include "public_editor.h"
28 #include "editor.h"
29 #include "video_monitor.h"
30
31 #include "i18n.h"
32
33 using namespace std;
34 using namespace PBD;
35
36 VideoMonitor::VideoMonitor (PublicEditor *ed, std::string xjadeo_bin_path)
37         : editor (ed)
38 {
39         manually_seeked_frame = 0;
40         fps =0.0; // = _session->timecode_frames_per_second();
41         sync_by_manual_seek = false;
42         _restore_settings_mask = 0;
43         clock_connection = sigc::connection();
44         state_connection = sigc::connection();
45         debug_enable = false;
46         state_clk_divide = 0;
47         starting = 0;
48         osdmode = 10; // 1: frameno, 2: timecode, 8: box
49
50         process = new SystemExec(xjadeo_bin_path, X_("-R"));
51         process->ReadStdout.connect_same_thread (*this, boost::bind (&VideoMonitor::parse_output, this, _1 ,_2));
52         process->Terminated.connect (*this, invalidator (*this), boost::bind (&VideoMonitor::terminated, this), gui_context());
53         XJKeyEvent.connect (*this, invalidator (*this), boost::bind (&VideoMonitor::forward_keyevent, this, _1), gui_context());
54 }
55
56 VideoMonitor::~VideoMonitor ()
57 {
58         if (clock_connection.connected()) {
59                 clock_connection.disconnect();
60         }
61         if (state_connection.connected()) {
62                 state_connection.disconnect();
63         }
64         delete process;
65 }
66
67 bool
68 VideoMonitor::start ()
69 {
70         if (is_started()) {
71                 return true;
72         }
73
74         manually_seeked_frame = 0;
75         sync_by_manual_seek = false;
76         if (clock_connection.connected()) { clock_connection.disconnect(); }
77
78         if (process->start(debug_enable?2:1)) {
79                 return false;
80         }
81         return true;
82 }
83
84 void
85 VideoMonitor::query_full_state (bool wait)
86 {
87         knownstate = 0;
88         process->write_to_stdin("get windowsize\n");
89         process->write_to_stdin("get windowpos\n");
90         process->write_to_stdin("get letterbox\n");
91         process->write_to_stdin("get fullscreen\n");
92         process->write_to_stdin("get ontop\n");
93         process->write_to_stdin("get offset\n");
94         process->write_to_stdin("get osdcfg\n");
95         int timeout = 40;
96         if (wait && knownstate !=127 && --timeout) {
97                 usleep(50000);
98                 sched_yield();
99         }
100 }
101
102 void
103 VideoMonitor::quit ()
104 {
105         if (!is_started()) return;
106         if (state_connection.connected()) { state_connection.disconnect(); }
107         if (clock_connection.connected()) { clock_connection.disconnect(); }
108         query_full_state(true);
109         process->write_to_stdin("quit\n");
110         /* the 'quit' command should result in process termination
111          * but in case it fails (communication failure, SIGSTOP, ??)
112          * here's a timeout..
113          */
114         int timeout = 40;
115         while (is_started() && --timeout) {
116                 usleep(50000);
117                 sched_yield();
118         }
119         if (timeout <= 0) {
120                 process->terminate();
121         }
122 }
123
124 void
125 VideoMonitor::open (std::string filename)
126 {
127         if (!is_started()) return;
128         manually_seeked_frame = 0;
129         osdmode = 10; // 1: frameno, 2: timecode, 8: box
130         sync_by_manual_seek = false;
131         starting = 15;
132         process->write_to_stdin("load " + filename + "\n");
133         process->write_to_stdin("set fps -1\n");
134         process->write_to_stdin("window resize 100%\n");
135         process->write_to_stdin("window ontop on\n");
136         process->write_to_stdin("set seekmode 1\n");
137         /* override bitwise flags -- see xjadeo.h
138          * 0x01 : ignore 'q', ESC  / quite
139          * 0x02 : ignore "window closed by WM" / quit
140          * 0x04 : (osx only) menu-exit / quit
141          * 0x08 : ignore mouse-button 1 -- resize
142          * 0x10 : no A/V offset
143          * 0x20 : don't use jack-session
144          * 0x40 : no jack-transport control play/pause/rewind
145          */
146         process->write_to_stdin("set override 120\n");
147         process->write_to_stdin("notify keyboard\n");
148         process->write_to_stdin("notify settings\n");
149         process->write_to_stdin("window letterbox on\n");
150         process->write_to_stdin("osd mode 10\n");
151         for(XJSettings::const_iterator it = xjadeo_settings.begin(); it != xjadeo_settings.end(); ++it) {
152                 if (skip_setting(it->first)) { continue; }
153                 process->write_to_stdin(it->first + " " + it->second + "\n");
154         }
155         if (!state_connection.connected()) {
156                 starting = 15;
157                 querystate();
158                 state_clk_divide = 0;
159                 /* TODO once every two second or so -- state_clk_divide hack below */
160                 state_connection = ARDOUR_UI::RapidScreenUpdate.connect (sigc::mem_fun (*this, &VideoMonitor::querystate));
161         }
162         xjadeo_sync_setup();
163 }
164
165 void
166 VideoMonitor::querystate ()
167 {
168         /* clock-divider hack -- RapidScreenUpdate == every_point_one_seconds */
169         state_clk_divide = (state_clk_divide + 1) % 300; // 30 secs
170         if (state_clk_divide == 0) {
171                 // every 30 seconds
172                 query_full_state(false);
173                 return;
174         }
175         if (state_clk_divide%25 != 0) {
176                 return;
177         }
178         // every 2.5 seconds:
179         process->write_to_stdin("get fullscreen\n");
180         process->write_to_stdin("get ontop\n");
181         process->write_to_stdin("get osdcfg\n");
182         process->write_to_stdin("get letterbox\n");
183 }
184
185 bool
186 VideoMonitor::skip_setting (std::string which)
187 {
188         if (_restore_settings_mask & XJ_OSD && which == "osd mode") { return true; }
189         if (_restore_settings_mask & XJ_LETTERBOX && which == "window letterbox") { return true; }
190         if (_restore_settings_mask & XJ_WINDOW_SIZE && which == "window size") { return true; }
191         if (_restore_settings_mask & XJ_WINDOW_POS && which == "window xy") { return true; }
192         if (_restore_settings_mask & XJ_WINDOW_ONTOP && which == "window ontop") { return true; }
193         if (_restore_settings_mask & XJ_LETTERBOX && which == "window letterbox") { return true; }
194         if (_restore_settings_mask & XJ_OFFSET && which == "set offset") { return true; }
195         if (_restore_settings_mask & XJ_FULLSCREEN && which == "window zoom") { return true; }
196         return false;
197 }
198
199 void
200 VideoMonitor::send_cmd (int what, int param)
201 {
202         bool osd_update = false;
203         int prev_osdmode = osdmode;
204         if (!is_started()) return;
205         printf("VideoMonitor::send_cmd %d %d\n", what, param); fflush(stdout);
206         switch (what) {
207                 case 1:
208                         if (param) process->write_to_stdin("window ontop on\n");
209                         else process->write_to_stdin("window ontop off\n");
210                         break;
211                 case 2:
212                         if (param) osdmode |= 2;
213                         else osdmode &= ~2;
214                         osd_update = (prev_osdmode != osdmode);
215                         break;
216                 case 3:
217                         if (param) osdmode |= 1;
218                         else osdmode &= ~1;
219                         osd_update = (prev_osdmode != osdmode);
220                         break;
221                 case 4:
222                         if (param) osdmode |= 8;
223                         else osdmode &= ~8;
224                         osd_update = (prev_osdmode != osdmode);
225                         break;
226                 case 5:
227                         if (param) process->write_to_stdin("window zoom on\n");
228                         else process->write_to_stdin("window zoom off\n");
229                         break;
230                 case 6:
231                         if (param) process->write_to_stdin("window letterbox on\n");
232                         else process->write_to_stdin("window letterbox off\n");
233                         break;
234                 case 7:
235                         process->write_to_stdin("window resize 100%");
236                         break;
237                 default:
238                         break;
239         }
240         if (osd_update) {
241                 std::ostringstream osstream; osstream << "osd mode " << osdmode << "\n";
242                 process->write_to_stdin(osstream.str());
243         }
244 }
245
246 bool
247 VideoMonitor::is_started ()
248 {
249         return process->is_running();
250 }
251
252 void
253 VideoMonitor::forward_keyevent (unsigned int keyval)
254 {
255         Editor* ed = dynamic_cast<Editor*>(&PublicEditor::instance());
256         if (!ed) return;
257         emulate_key_event(ed, keyval);
258 }
259
260 void
261 VideoMonitor::parse_output (std::string d, size_t /*s*/)
262 {
263         std::string line = d;
264         std::string::size_type start = 0;
265         std::string::size_type end = 0;
266
267         while (1) {
268                 end = d.find('\n', start);
269                 if (end == std::string::npos) break;
270                 line = d.substr(start,end-start);
271                 start=end+1;
272                 if (line.length() <4 || line.at(0)!='@') continue;
273 #if 1 /* DEBUG */
274                 if (debug_enable) {
275                         printf("xjadeo: '%s'\n", line.c_str());
276                 }
277 #endif
278                 int status = atoi(line.substr(1,3));
279                 switch(status / 100) {
280                         case 4: /* errors */
281                                 if (status == 403) {
282                                         PBD::warning << _("Video Monitor: File Not Found.") << endmsg;
283                                         /* check: we should only write from the main thread.
284                                          * However it should not matter for 'quit'.
285                                          */
286                                         process->write_to_stdin("quit\n");
287                                 }
288 #ifdef DEBUG_XJCOM
289                         else
290                                 printf("xjadeo: error '%s'\n", line.c_str());
291 #endif
292                         break;
293                         case 3: /* async notifications */
294                         {
295                                 std::string::size_type equalsign = line.find('=');
296                                 std::string::size_type comment = line.find('#');
297                                 if (comment != std::string::npos) { line = line.substr(0,comment); }
298                                 if (equalsign != std::string::npos) {
299                                         std::string key = line.substr(5, equalsign - 5);
300                                         std::string value = line.substr(equalsign + 1);
301
302                                         if (status == 310 && key=="keypress") {
303                                                 /* keyboard event */
304                                                 XJKeyEvent((unsigned int)atoi(value));
305                                         }
306 #ifdef DEBUG_XJCOM
307                                         else {
308                                                 std::string msg = line.substr(5);
309                                                 printf("xjadeo: async '%s' -> '%s'\n", key, value);
310                                         }
311 #endif
312                                 }
313 #ifdef DEBUG_XJCOM
314                                 else {
315                                         std::string msg = line.substr(5);
316                                         printf("xjadeo: async '%s'\n", msg.c_str());
317                                 }
318 #endif
319                         } break;
320                         case 1: /* text messages - command reply */
321                                 break;
322                         case 8: /* comments / info for humans */
323                                 break;
324                         case 2:
325 /* replies:
326  * 201: var=<int>
327  * 202: var=<double>
328  * 210: var=<int>x<int>
329  * 220: var=<string>
330  * 228: var=<smpte-string>
331  */
332                         {
333                                 std::string::size_type equalsign = line.find('=');
334                                 std::string::size_type comment = line.find('#');
335                                 if (comment != std::string::npos) { line = line.substr(0,comment); }
336                                 if (equalsign != std::string::npos) {
337                                         std::string key = line.substr(5, equalsign - 5);
338                                         std::string value = line.substr(equalsign + 1);
339 #if 0 /* DEBUG */
340                                         std::cout << "parsed: " << key << " => " << value << std::endl;
341 #endif
342                                         if       (key ==  "windowpos") {
343                                                 knownstate |= 16;
344                                                 if (xjadeo_settings["window xy"] != value) {
345                                                         if (!starting && _session) _session->set_dirty ();
346                                                 }
347                                                 xjadeo_settings["window xy"] = value;
348                                         } else if(key ==  "windowsize") {
349                                                 knownstate |= 32;
350                                                 if (xjadeo_settings["window size"] != value) {
351                                                         if (!starting && _session) _session->set_dirty ();
352                                                 }
353                                                 xjadeo_settings["window size"] = value;
354                                         } else if(key ==  "windowontop") {
355                                                 knownstate |= 2;
356                                                 if (starting || xjadeo_settings["window ontop"] != value) {
357                                                         if (!starting && _session) _session->set_dirty ();
358                                                         if (atoi(value)) { UiState("xjadeo-window-ontop-on"); }
359                                                         else { UiState("xjadeo-window-ontop-off"); }
360                                                         starting &= ~2;
361                                                 }
362                                                 xjadeo_settings["window ontop"] = value;
363                                         } else if(key ==  "fullscreen") {
364                                                 knownstate |= 4;
365                                                 if (starting || xjadeo_settings["window zoom"] != value) {
366                                                         if (!starting && _session) _session->set_dirty ();
367                                                         if (atoi(value)) { UiState("xjadeo-window-fullscreen-on"); }
368                                                         else { UiState("xjadeo-window-fullscreen-off"); }
369                                                         starting &= ~4;
370                                                 }
371                                                 xjadeo_settings["window zoom"] = value;
372                                         } else if(key ==  "letterbox") {
373                                                 knownstate |= 8;
374                                                 if (starting || xjadeo_settings["window letterbox"] != value) {
375                                                         if (!starting && _session) _session->set_dirty ();
376                                                         if (atoi(value)) { UiState("xjadeo-window-letterbox-on"); }
377                                                         else { UiState("xjadeo-window-letterbox-off"); }
378                                                         starting &= ~8;
379                                                 }
380                                                 xjadeo_settings["window letterbox"] = value;
381                                         } else if(key ==  "osdmode") {
382                                                 knownstate |= 1;
383                                                 osdmode = atoi(value);
384                                                 if (starting || atoi(xjadeo_settings["osd mode"]) != osdmode) {
385                                                         if (!starting && _session) _session->set_dirty ();
386                                                         if ((osdmode & 1) == 1) { UiState("xjadeo-window-osd-frame-on"); }
387                                                         if ((osdmode & 1) == 0) { UiState("xjadeo-window-osd-frame-off"); }
388                                                         if ((osdmode & 2) == 2) { UiState("xjadeo-window-osd-timecode-on"); }
389                                                         if ((osdmode & 2) == 0) { UiState("xjadeo-window-osd-timecode-off"); }
390                                                         if ((osdmode & 8) == 8) { UiState("xjadeo-window-osd-box-on"); }
391                                                         if ((osdmode & 8) == 0) { UiState("xjadeo-window-osd-box-off"); }
392                                                 }
393                                                 starting &= ~1;
394                                                 xjadeo_settings["osd mode"] = value;
395                                         } else if(key ==  "offset") {
396                                                 knownstate |= 64;
397                                                 if (xjadeo_settings["set offset"] != value) {
398                                                         if (!starting && _session) _session->set_dirty ();
399                                                 }
400                                                 xjadeo_settings["set offset"] = value;
401 #ifdef DEBUG_XJCOM
402                                         } else {
403                                                 printf("xjadeo: '%s' -> '%s'\n", key.c_str(), value.c_str());
404 #endif
405                                         }
406                                 }
407                         }
408                                 break;
409                         default:
410                                 break;
411                 }
412         }
413 }
414
415 void
416 VideoMonitor::terminated ()
417 {
418         process->terminate(); // from gui-context clean up
419         Terminated();
420 }
421
422 void
423 VideoMonitor::save_session ()
424 {
425         if (!_session) { return; }
426         XMLNode* node = _session->extra_xml (X_("XJSettings"));
427         if (!node) return;
428         node->remove_nodes_and_delete("XJSetting");
429
430         for(XJSettings::const_iterator it = xjadeo_settings.begin(); it != xjadeo_settings.end(); ++it) {
431           XMLNode* child = node->add_child (X_("XJSetting"));
432                 child->add_property (X_("k"), it->first);
433                 child->add_property (X_("v"), it->second);
434         }
435 }
436
437
438 void
439 VideoMonitor::set_session (ARDOUR::Session *s)
440 {
441         SessionHandlePtr::set_session (s);
442         if (!_session) { return; }
443         _session->config.ParameterChanged.connect (*this, invalidator (*this), ui_bind (&VideoMonitor::parameter_changed, this, _1), gui_context());
444         XMLNode* node = _session->extra_xml (X_("XJSettings"));
445         if (!node) { return;}
446         xjadeo_settings.clear();
447
448         XMLNodeList nlist = node->children();
449         XMLNodeConstIterator niter;
450         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
451                 xjadeo_settings[(*niter)->property(X_("k"))->value()] = (*niter)->property(X_("v"))->value();
452   }
453 }
454
455 void
456 VideoMonitor::clear_session_state ()
457 {
458         xjadeo_settings.clear();
459         if (!_session) { return; }
460         XMLNode* node = new XMLNode(X_("XJSettings"));
461         _session->add_extra_xml (*node);
462         _session->set_dirty ();
463 }
464
465 bool
466 VideoMonitor::set_custom_setting (const std::string k, const std::string v)
467 {
468         xjadeo_settings[k] = v;
469         return true; /* TODO: check if key is valid */
470 }
471
472 const std::string
473 VideoMonitor::get_custom_setting (const std::string k)
474 {
475         return (xjadeo_settings[k]);
476 }
477
478 #define NO_OFFSET (1<<31) //< skip setting or modifying offset --  TODO check ARDOUR::frameoffset_t max value.
479 void
480 VideoMonitor::srsupdate ()
481 {
482         if (!_session) { return; }
483         if (editor->dragging_playhead()) { return ;}
484         manual_seek(_session->audible_frame(), false, NO_OFFSET);
485 }
486
487 void
488 VideoMonitor::set_offset (ARDOUR::frameoffset_t offset)
489 {
490         if (!is_started()) { return; }
491         if (!_session) { return; }
492         if (offset == NO_OFFSET ) { return; }
493
494         framecnt_t video_frame_offset;
495         framecnt_t audio_frame_rate;
496         if (_session->config.get_videotimeline_pullup()) {
497                 audio_frame_rate = _session->frame_rate();
498         } else {
499                 audio_frame_rate = _session->nominal_frame_rate();
500         }
501
502         /* Note: pull-up/down are applied here: frame_rate() vs. nominal_frame_rate() */
503         if (_session->config.get_use_video_file_fps()) {
504                 video_frame_offset = floor(offset * fps / audio_frame_rate);
505         } else {
506                 video_frame_offset = floor(offset * _session->timecode_frames_per_second() / audio_frame_rate);
507         }
508
509         // TODO remember if changed..
510         std::ostringstream osstream1; osstream1 << -1 * video_frame_offset;
511         process->write_to_stdin("set offset " + osstream1.str() + "\n");
512 }
513
514 void
515 VideoMonitor::manual_seek (framepos_t when, bool /*force*/, ARDOUR::frameoffset_t offset)
516 {
517         if (!is_started()) { return; }
518         if (!_session) { return; }
519         framecnt_t video_frame;
520         framecnt_t audio_frame_rate;
521         if (_session->config.get_videotimeline_pullup()) {
522                 audio_frame_rate = _session->frame_rate();
523         } else {
524                 audio_frame_rate = _session->nominal_frame_rate();
525         }
526
527         /* Note: pull-up/down are applied here: frame_rate() vs. nominal_frame_rate() */
528         if (_session->config.get_use_video_file_fps()) {
529                 video_frame = floor(when * fps / audio_frame_rate);
530         } else {
531                 video_frame = floor(when * _session->timecode_frames_per_second() / audio_frame_rate);
532         }
533         if (video_frame < 0 ) video_frame = 0;
534
535         if (video_frame == manually_seeked_frame) { return; }
536         manually_seeked_frame = video_frame;
537
538 #if 0 /* DEBUG */
539         std::cout <<"seek: " << video_frame << std::endl;
540 #endif
541         std::ostringstream osstream; osstream << video_frame;
542         process->write_to_stdin("seek " + osstream.str() + "\n");
543
544         set_offset(offset);
545 }
546
547 void
548 VideoMonitor::parameter_changed (std::string const & p)
549 {
550         if (!is_started()) { return; }
551         if (!_session) { return; }
552         if (p != "external-sync" && p != "sync-source") {
553                 return;
554         }
555         xjadeo_sync_setup();
556 }
557
558 void
559 VideoMonitor::xjadeo_sync_setup ()
560 {
561         if (!is_started()) { return; }
562         if (!_session) { return; }
563
564         bool my_manual_seek = true;
565         if (_session->config.get_external_sync()) {
566                 if (ARDOUR::Config->get_sync_source() == ARDOUR::JACK)
567                         my_manual_seek = false;
568         }
569
570         if (my_manual_seek != sync_by_manual_seek) {
571                 if (sync_by_manual_seek) {
572                         if (clock_connection.connected()) {
573                                 clock_connection.disconnect();
574                         }
575                         process->write_to_stdin("jack connect\n");
576                 } else {
577                         process->write_to_stdin("jack disconnect\n");
578                         clock_connection = ARDOUR_UI::SuperRapidScreenUpdate.connect (sigc::mem_fun (*this, &VideoMonitor::srsupdate));
579                 }
580                 sync_by_manual_seek = my_manual_seek;
581         }
582 }