Merge branch 'cairocanvas'
[ardour.git] / gtk2_ardour / video_timeline.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 <algorithm>
21 #include <sigc++/bind.h>
22 #include "ardour/tempo.h"
23
24 #include "pbd/file_utils.h"
25 #include "pbd/convert.h"
26 #include "ardour/session_directory.h"
27
28 #ifdef PLATFORM_WINDOWS
29 #include <windows.h>
30 #include <shlobj.h> // CSIDL_*
31 #include "pbd/windows_special_dirs.h"
32 #endif
33
34 #include "ardour_ui.h"
35 #include "public_editor.h"
36 #include "gui_thread.h"
37 #include "utils_videotl.h"
38 #include "rgb_macros.h"
39 #include "video_timeline.h"
40
41 #include <gtkmm2ext/utils.h>
42 #include <pthread.h>
43 #include <curl/curl.h>
44
45 #ifdef PLATFORM_WINDOWS
46 #include <windows.h>
47 #endif
48
49 #include "i18n.h"
50
51 using namespace std;
52 using namespace ARDOUR;
53 using namespace PBD;
54 using namespace Timecode;
55 using namespace VideoUtils;
56
57 VideoTimeLine::VideoTimeLine (PublicEditor *ed, ArdourCanvas::Container *vbg, int initial_height)
58         : editor (ed)
59                 , videotl_group(vbg)
60                 , bar_height(initial_height)
61 {
62         video_start_offset = 0L;
63         video_offset = 0L;
64         video_offset_p = 0L;
65         video_duration = 0L;
66         auto_set_session_fps = false;
67         video_offset_lock = false;
68         video_aspect_ratio = 4.0/3.0;
69         Config->ParameterChanged.connect (*this, invalidator (*this), ui_bind (&VideoTimeLine::parameter_changed, this, _1), gui_context());
70         video_server_url = video_get_server_url(Config);
71         server_docroot   = video_get_docroot(Config);
72         video_filename = "";
73         local_file = true;
74         video_file_fps = 25.0;
75         flush_frames = false;
76         vmonitor=0;
77         reopen_vmonitor=false;
78         find_xjadeo();
79
80         VtlUpdate.connect (*this, invalidator (*this), boost::bind (&PublicEditor::queue_visual_videotimeline_update, editor), gui_context());
81         GuiUpdate.connect (*this, invalidator (*this), boost::bind (&VideoTimeLine::gui_update, this, _1), gui_context());
82 }
83
84 VideoTimeLine::~VideoTimeLine ()
85 {
86         close_session();
87 }
88
89 /* close and save settings */
90 void
91 VideoTimeLine::save_session ()
92 {
93         if (!_session) {
94                 return;
95         }
96
97         LocaleGuard lg (X_("POSIX"));
98
99         XMLNode* node = new XMLNode(X_("Videomonitor"));
100         if (!node) return;
101         node->add_property (X_("active"), (vmonitor && vmonitor->is_started())?"yes":"no");
102         _session->add_extra_xml (*node);
103
104         if (vmonitor) {
105                 if (vmonitor->is_started()) {
106                         vmonitor->query_full_state(true);
107                 }
108                 vmonitor->save_session();
109         }
110
111         /* VTL settings */
112         node = _session->extra_xml (X_("Videotimeline"));
113         if (!node) return;
114         node->add_property (X_("id"), id().to_s());
115         node->add_property (X_("Height"), editor->get_videotl_bar_height());
116         node->add_property (X_("VideoOffsetLock"), video_offset_lock?X_("1"):X_("0"));
117         node->add_property (X_("VideoOffset"), video_offset);
118         node->add_property (X_("AutoFPS"), auto_set_session_fps?X_("1"):X_("0"));
119 }
120
121 /* close and save settings */
122 void
123 VideoTimeLine::close_session ()
124 {
125         if (video_duration == 0) {
126                 return;
127         }
128         sessionsave.disconnect();
129         close_video_monitor();
130
131         remove_frames();
132         video_filename = "";
133         video_duration = 0;
134         GuiUpdate("set-xjadeo-sensitive-off");
135         GuiUpdate("video-unavailable");
136 }
137
138 void
139 VideoTimeLine::sync_session_state ()
140 {
141         if (!_session || !vmonitor || !vmonitor->is_started()) {
142                 return;
143         }
144         save_session();
145 }
146
147 /** load settings from session */
148 void
149 VideoTimeLine::set_session (ARDOUR::Session *s)
150 {
151         SessionHandlePtr::set_session (s);
152         if (!_session) { return ; }
153
154         _session->SaveSession.connect_same_thread (sessionsave, boost::bind (&VideoTimeLine::save_session, this));
155         LocaleGuard lg (X_("POSIX"));
156
157         XMLNode* node = _session->extra_xml (X_("Videotimeline"));
158
159         if (!node || !node->property (X_("Filename"))) {
160                 return;
161         }
162
163         ARDOUR_UI::instance()->start_video_server((Gtk::Window*)0, false);
164
165         set_id(*node);
166
167         const XMLProperty* proph = node->property (X_("Height"));
168         if (proph) {
169                 editor->set_video_timeline_height(atoi(proph->value()));
170         }
171 #if 0 /* TODO THINK: set FPS first time only ?! */
172         const XMLProperty* propasfps = node->property (X_("AutoFPS"));
173         if (propasfps) {
174                 auto_set_session_fps = atoi(propasfps->value())?true:false;
175         }
176 #endif
177
178         const XMLProperty* propoffset = node->property (X_("VideoOffset"));
179         if (propoffset) {
180                 video_offset = atoll(propoffset->value());
181                 video_offset_p = video_offset;
182         }
183
184         const XMLProperty* proplock = node->property (X_("VideoOffsetLock"));
185         if (proplock) {
186                 video_offset_lock = atoi(proplock->value())?true:false;
187         }
188
189         const XMLProperty* localfile = node->property (X_("LocalFile"));
190         if (localfile) {
191                 local_file = atoi(localfile->value())?true:false;
192         }
193
194         const XMLProperty* propf = node->property (X_("Filename"));
195         video_file_info(propf->value(), local_file);
196
197         if ((node = _session->extra_xml (X_("Videomonitor")))) {
198                 const XMLProperty* prop = node->property (X_("active"));
199                 if (prop && prop->value() == "yes" && found_xjadeo() && !video_filename.empty() && local_file) {
200                         open_video_monitor();
201                 }
202         }
203
204         _session->register_with_memento_command_factory(id(), this);
205         _session->config.ParameterChanged.connect (*this, invalidator (*this), ui_bind (&VideoTimeLine::parameter_changed, this, _1), gui_context());
206 }
207
208 void
209 VideoTimeLine::set_offset_locked (bool v) {
210         if (_session && v != video_offset_lock) {
211                 _session->set_dirty ();
212         }
213         video_offset_lock = v;
214 }
215
216 void
217 VideoTimeLine::toggle_offset_locked () {
218         video_offset_lock = !video_offset_lock;
219         if (_session) {
220                 _session->set_dirty ();
221         }
222 }
223
224 void
225 VideoTimeLine::save_undo ()
226 {
227         if (_session && video_offset_p != video_offset) {
228                 _session->set_dirty ();
229         }
230         video_offset_p = video_offset;
231 }
232
233 int
234 VideoTimeLine::set_state (const XMLNode& node, int /*version*/)
235 {
236         LocaleGuard lg (X_("POSIX"));
237         const XMLProperty* propoffset = node.property (X_("VideoOffset"));
238         if (propoffset) {
239                 video_offset = atoll(propoffset->value());
240         }
241         ARDOUR_UI::instance()->flush_videotimeline_cache(true);
242         return 0;
243 }
244
245 XMLNode&
246 VideoTimeLine::get_state ()
247 {
248         XMLNode* node = new XMLNode (X_("Videotimeline"));
249         LocaleGuard lg (X_("POSIX"));
250         node->add_property (X_("VideoOffset"), video_offset_p);
251         return *node;
252 }
253
254 void
255 VideoTimeLine::remove_frames ()
256 {
257         for (VideoFrames::iterator i = video_frames.begin(); i != video_frames.end(); ++i ) {
258                 VideoImageFrame *frame = (*i);
259                 delete frame;
260                 (*i) = 0;
261         }
262         video_frames.clear();
263 }
264
265 VideoImageFrame *
266 VideoTimeLine::get_video_frame (framepos_t vfn, int cut, int rightend)
267 {
268         if (vfn==0) cut=0;
269         for (VideoFrames::iterator i = video_frames.begin(); i != video_frames.end(); ++i) {
270                 VideoImageFrame *frame = (*i);
271                 if (abs(frame->get_video_frame_number()-vfn)<=cut
272                     && frame->get_rightend() == rightend) { return frame; }
273         }
274         return 0;
275 }
276
277 float
278 VideoTimeLine::get_apv()
279 {
280         // XXX: dup code - TODO use this fn in update_video_timeline()
281         float apv = -1; /* audio samples per video frame; */
282         if (!_session) return apv;
283
284         if (_session->config.get_use_video_file_fps()) {
285                 if (video_file_fps == 0 ) return apv;
286         } else {
287                 if (_session->timecode_frames_per_second() == 0 ) return apv;
288         }
289
290         if (_session->config.get_videotimeline_pullup()) {
291                 apv = _session->frame_rate();
292         } else {
293                 apv = _session->nominal_frame_rate();
294         }
295         if (_session->config.get_use_video_file_fps()) {
296                 apv /= video_file_fps;
297         } else {
298                 apv /= _session->timecode_frames_per_second();
299         }
300         return apv;
301 }
302
303 void
304 VideoTimeLine::update_video_timeline()
305 {
306         if (!_session) return;
307
308         if (_session->config.get_use_video_file_fps()) {
309                 if (video_file_fps == 0 ) return;
310         } else {
311                 if (_session->timecode_frames_per_second() == 0 ) return;
312         }
313
314         const double samples_per_pixel = editor->get_current_zoom();
315         const framepos_t leftmost_sample =  editor->leftmost_sample();
316
317         /* Outline:
318          * 1) calculate how many frames there should be in current zoom (plus 1 page on each side)
319          * 2) calculate first frame and distance between video-frames (according to zoom)
320          * 3) destroy/add frames
321          * 4) reposition existing frames
322          * 5) assign framenumber to frames -> request/decode video.
323          */
324
325         /* video-file and session properties */
326         double display_vframe_width; /* unit: pixels ; width of one thumbnail in the timeline */
327         float apv; /* audio samples per video frame; */
328         framepos_t leftmost_video_frame; /* unit: video-frame number ; temporary var -> vtl_start */
329
330         /* variables needed to render videotimeline -- what needs to computed first */
331         framepos_t vtl_start; /* unit: audio-samples ; first displayed video-frame */
332         framepos_t vtl_dist;  /* unit: audio-samples ; distance between displayed video-frames */
333         unsigned int visible_video_frames; /* number of frames that fit on current canvas */
334
335         if (_session->config.get_videotimeline_pullup()) {
336                 apv = _session->frame_rate();
337         } else {
338                 apv = _session->nominal_frame_rate();
339         }
340         if (_session->config.get_use_video_file_fps()) {
341                 apv /= video_file_fps;
342         } else {
343                 apv /= _session->timecode_frames_per_second();
344         }
345
346         display_vframe_width = bar_height * video_aspect_ratio;
347
348         if (apv > samples_per_pixel * display_vframe_width) {
349                 /* high-zoom: need space between successive video-frames */
350                 vtl_dist = rint(apv);
351         } else {
352                 /* continous timeline: skip video-frames */
353                 vtl_dist = ceil(display_vframe_width * samples_per_pixel / apv) * apv;
354         }
355
356         assert (vtl_dist > 0);
357         assert (apv > 0);
358
359         leftmost_video_frame = floor (floor((long double)(leftmost_sample - video_start_offset - video_offset ) / vtl_dist) * vtl_dist / apv);
360
361         vtl_start = rint (video_offset + video_start_offset + leftmost_video_frame * apv);
362         visible_video_frames = 2 + ceil((double)editor->current_page_samples() / vtl_dist); /* +2 left+right partial frames */
363
364         /* expand timeline (cache next/prev page images) */
365         vtl_start -= visible_video_frames * vtl_dist;
366         visible_video_frames *=3;
367
368         if (vtl_start < video_offset ) {
369                 visible_video_frames += ceil((double)vtl_start/vtl_dist);
370                 vtl_start = video_offset;
371         }
372
373         /* apply video-file constraints */
374         if (vtl_start > video_start_offset + video_duration + video_offset ) {
375                 visible_video_frames = 0;
376         }
377         /* TODO optimize: compute rather than iterate */
378         while (visible_video_frames > 0 && vtl_start + (visible_video_frames-1) * vtl_dist >= video_start_offset + video_duration + video_offset) {
379                 --visible_video_frames;
380         }
381
382         if (flush_frames) {
383                 remove_frames();
384                 flush_frames=false;
385         }
386
387         while (video_frames.size() < visible_video_frames) {
388                 VideoImageFrame *frame;
389                 frame = new VideoImageFrame(*editor, *videotl_group, display_vframe_width, bar_height, video_server_url, translated_filename());
390                 frame->ImgChanged.connect (*this, invalidator (*this), boost::bind (&PublicEditor::queue_visual_videotimeline_update, editor), gui_context());
391                 video_frames.push_back(frame);
392         }
393
394         VideoFrames outdated_video_frames;
395         std::list<int> remaining;
396
397         outdated_video_frames = video_frames;
398
399 #if 1
400         /* when zoomed out, ignore shifts by +-1 frame
401          * which can occur due to rounding errors when
402          * scrolling to a new leftmost-audio frame.
403          */
404         int cut =1;
405         if (vtl_dist/apv < 3.0) cut =0;
406 #else
407         int cut =0;
408 #endif
409
410         for (unsigned int vfcount=0; vfcount < visible_video_frames; ++vfcount){
411                 framepos_t vfpos = vtl_start + vfcount * vtl_dist; /* unit: audio-frames */
412                 framepos_t vframeno = rint ( (vfpos - video_offset) / apv); /* unit: video-frames */
413                 vfpos = (vframeno * apv ) + video_offset; /* audio-frame  corresponding to /rounded/ video-frame */
414
415                 int rightend = -1; /* unit: pixels */
416                 if (vfpos + vtl_dist > video_start_offset + video_duration + video_offset) {
417                         rightend = display_vframe_width * (video_start_offset + video_duration + video_offset - vfpos) / vtl_dist;
418                         //printf("lf(e): %lu\n", vframeno); // XXX
419                 }
420                 VideoImageFrame * frame = get_video_frame(vframeno, cut, rightend);
421                 if (frame) {
422                   frame->set_position(vfpos);
423                         outdated_video_frames.remove(frame);
424                 } else {
425                         remaining.push_back(vfcount);
426                 }
427         }
428
429         for (VideoFrames::iterator i = outdated_video_frames.begin(); i != outdated_video_frames.end(); ++i ) {
430                 VideoImageFrame *frame = (*i);
431                 if (remaining.empty()) {
432                   frame->set_position(-2 * vtl_dist + leftmost_sample); /* move off screen */
433                 } else {
434                         int vfcount=remaining.front();
435                         remaining.pop_front();
436                         framepos_t vfpos = vtl_start + vfcount * vtl_dist; /* unit: audio-frames */
437                         framepos_t vframeno = rint ((vfpos - video_offset) / apv);  /* unit: video-frames */
438                         int rightend = -1; /* unit: pixels */
439                         if (vfpos + vtl_dist > video_start_offset + video_duration + video_offset) {
440                                 rightend = display_vframe_width * (video_start_offset + video_duration + video_offset - vfpos) / vtl_dist;
441                                 //printf("lf(n): %lu\n", vframeno); // XXX
442                         }
443                         frame->set_position(vfpos);
444                         frame->set_videoframe(vframeno, rightend);
445                 }
446         }
447 }
448
449 std::string
450 VideoTimeLine::translated_filename ()
451 {
452         if (!local_file){
453                 return video_filename;
454         } else {
455                 return video_map_path(server_docroot, video_filename);
456         }
457 }
458
459 bool
460 VideoTimeLine::video_file_info (std::string filename, bool local)
461 {
462
463         local_file = local;
464         if (Glib::path_is_absolute(filename) || !local_file)
465         {
466                 video_filename = filename;
467         }  else {
468                 video_filename = Glib::build_filename (_session->session_directory().video_path(), filename);
469         }
470
471         long long int _duration;
472         double _start_offset;
473
474         if (!video_query_info(
475                         video_server_url, translated_filename(),
476                         video_file_fps, _duration, _start_offset, video_aspect_ratio)) {
477                 warning << _("Parsing video file info failed. Is the Video Server running? Is the file readable by the Video Server? Does the docroot match? Is it a video file?") << endmsg;
478                 video_duration = 0;
479                 GuiUpdate("set-xjadeo-sensitive-off");
480                 GuiUpdate("video-unavailable");
481                 return false;
482         }
483         video_duration = _duration * _session->nominal_frame_rate() / video_file_fps;
484         video_start_offset = _start_offset * _session->nominal_frame_rate();
485
486         if (auto_set_session_fps && video_file_fps != _session->timecode_frames_per_second()) {
487                 switch ((int)floorf(video_file_fps*1000.0)) {
488                         case 23976:
489                                 _session->config.set_timecode_format(timecode_23976);
490                                 break;
491                         case 24000:
492                                 _session->config.set_timecode_format(timecode_24);
493                                 break;
494                         case 24975:
495                         case 24976:
496                                 _session->config.set_timecode_format(timecode_24976);
497                                 break;
498                         case 25000:
499                                 _session->config.set_timecode_format(timecode_25);
500                                 break;
501                         case 29970:
502                                 _session->config.set_timecode_format(timecode_2997drop);
503                                 break;
504                         case 30000:
505                                 _session->config.set_timecode_format(timecode_30);
506                                 break;
507                         case 59940:
508                                 _session->config.set_timecode_format(timecode_5994);
509                                 break;
510                         case 60000:
511                                 _session->config.set_timecode_format(timecode_60);
512                                 break;
513                         default:
514                                 warning << string_compose (
515                                                 _("Failed to set session-framerate: '%1' does not have a corresponding option setting in %2."),
516                                                 video_file_fps, PROGRAM_NAME ) << endmsg;
517                                 break;
518                 }
519                 _session->config.set_video_pullup(0); /* TODO only set if set_timecode_format() was successful ?!*/
520         }
521         if (floor(video_file_fps*100) != floor(_session->timecode_frames_per_second()*100)) {
522                 warning << string_compose(
523                                 _("Video file's framerate is not equal to %1 session timecode's framerate: '%2' vs '%3'"),
524                                         PROGRAM_NAME, video_file_fps, _session->timecode_frames_per_second())
525                                 << endmsg;
526         }
527         flush_local_cache ();
528
529         if (found_xjadeo() && local_file) {
530                 GuiUpdate("set-xjadeo-sensitive-on");
531                 if (vmonitor && vmonitor->is_started()) {
532 #if 1
533                         /* xjadeo <= 0.6.4 has a bug where changing the video-file may segfauls
534                          * if the geometry changes to a different line-size alignment
535                          */
536                         reopen_vmonitor = true;
537                         vmonitor->quit();
538 #else
539                         vmonitor->set_fps(video_file_fps);
540                         vmonitor->open(video_filename);
541 #endif
542                 }
543         } else if (!local_file) {
544 #if 1 /* temp debug/devel message */
545                 // TODO - call xjremote remotely.
546                 printf("the given video file can not be accessed on localhost, video monitoring is not currently supported for this case\n");
547                 GuiUpdate("set-xjadeo-sensitive-off");
548 #endif
549         }
550         VtlUpdate();
551         GuiUpdate("video-available");
552         return true;
553 }
554
555 bool
556 VideoTimeLine::check_server ()
557 {
558         bool ok = false;
559         char url[1024];
560         snprintf(url, sizeof(url), "%s%sstatus"
561                         , video_server_url.c_str()
562                         , (video_server_url.length()>0 && video_server_url.at(video_server_url.length()-1) == '/')?"":"/"
563                         );
564         char *res=a3_curl_http_get(url, NULL);
565         if (res) {
566                 if (strstr(res, "status: ok, online.")) { ok = true; }
567                 free(res);
568         }
569         return ok;
570 }
571
572 bool
573 VideoTimeLine::check_server_docroot ()
574 {
575         bool ok = true;
576         char url[1024];
577         std::vector<std::vector<std::string> > lines;
578
579         if (video_server_url.find("/localhost:") == string::npos) {
580                 return true;
581         }
582         snprintf(url, sizeof(url), "%s%src?format=csv"
583                         , video_server_url.c_str()
584                         , (video_server_url.length()>0 && video_server_url.at(video_server_url.length()-1) == '/')?"":"/"
585                         );
586         char *res=a3_curl_http_get(url, NULL);
587         if (!res) {
588                 return false;
589         }
590
591         ParseCSV(std::string(res), lines);
592         if (   lines.empty()
593                         || lines.at(0).empty()
594                         || lines.at(0).at(0) != video_get_docroot(Config)) {
595                 warning << string_compose(
596                                 _("Video-server docroot mismatch. %1: '%2', video-server: '%3'. This usually means that the video server was not started by %1 and uses a different document-root."),
597                                 PROGRAM_NAME, video_get_docroot(Config), lines.at(0).at(0))
598                 << endmsg;
599                 ok = false; // TODO allow to override
600         }
601         free(res);
602         return ok;
603 }
604
605 void
606 VideoTimeLine::gui_update(std::string const & t) {
607         /* this is to be called via GuiUpdate() only. */
608         ENSURE_GUI_THREAD (*this, &VideoTimeLine::queue_visual_videotimeline_update)
609         if (t == "videotimeline-update") {
610                 editor->queue_visual_videotimeline_update();
611         } else if (t == "set-xjadeo-active-off") {
612                 editor->toggle_xjadeo_proc(0);
613         } else if (t == "set-xjadeo-active-on") {
614                 editor->toggle_xjadeo_proc(1);
615         } else if (t == "set-xjadeo-sensitive-on") {
616                 editor->set_xjadeo_sensitive(true);
617         } else if (t == "set-xjadeo-sensitive-off") {
618                 editor->toggle_xjadeo_proc(0);
619                 //close_video_monitor();
620                 editor->set_xjadeo_sensitive(false);
621         } else if (t == "xjadeo-window-ontop-on") {
622                 editor->toggle_xjadeo_viewoption(1, 1);
623         } else if (t == "xjadeo-window-ontop-off") {
624                 editor->toggle_xjadeo_viewoption(1, 0);
625         } else if (t == "xjadeo-window-osd-timecode-on") {
626                 editor->toggle_xjadeo_viewoption(2, 1);
627         } else if (t == "xjadeo-window-osd-timecode-off") {
628                 editor->toggle_xjadeo_viewoption(2, 0);
629         } else if (t == "xjadeo-window-osd-frame-on") {
630                 editor->toggle_xjadeo_viewoption(3, 1);
631         } else if (t == "xjadeo-window-osd-frame-off") {
632                 editor->toggle_xjadeo_viewoption(3, 0);
633         } else if (t == "xjadeo-window-osd-box-on") {
634                 editor->toggle_xjadeo_viewoption(4, 1);
635         } else if (t == "xjadeo-window-osd-box-off") {
636                 editor->toggle_xjadeo_viewoption(4, 0);
637         } else if (t == "xjadeo-window-fullscreen-on") {
638                 editor->toggle_xjadeo_viewoption(5, 1);
639         } else if (t == "xjadeo-window-fullscreen-off") {
640                 editor->toggle_xjadeo_viewoption(5, 0);
641         } else if (t == "xjadeo-window-letterbox-on") {
642                 editor->toggle_xjadeo_viewoption(6, 1);
643         } else if (t == "xjadeo-window-letterbox-off") {
644                 editor->toggle_xjadeo_viewoption(6, 0);
645         } else if (t == "video-available") {
646                 editor->set_close_video_sensitive(true);
647         } else if (t == "video-unavailable") {
648                 editor->set_close_video_sensitive(false);
649         }
650 }
651
652 void
653 VideoTimeLine::set_height (int height) {
654         if (_session && bar_height != height) {
655                 _session->set_dirty ();
656         }
657         bar_height = height;
658         flush_local_cache();
659 }
660
661 void
662 VideoTimeLine::vmon_update () {
663         if (vmonitor && vmonitor->is_started()) {
664                 vmonitor->set_offset(video_offset); // TODO proper re-init xjadeo w/o restart not just offset.
665         }
666 }
667
668 void
669 VideoTimeLine::flush_local_cache () {
670         flush_frames = true;
671         vmon_update();
672 }
673
674 void
675 VideoTimeLine::flush_cache () {
676         flush_local_cache();
677         char url[1024];
678         snprintf(url, sizeof(url), "%s%sadmin/flush_cache"
679                         , video_server_url.c_str()
680                         , (video_server_url.length()>0 && video_server_url.at(video_server_url.length()-1) == '/')?"":"/"
681                         );
682         char *res=a3_curl_http_get(url, NULL);
683         if (res) {
684                 free (res);
685         }
686         if (vmonitor && vmonitor->is_started()) {
687                 reopen_vmonitor=true;
688                 vmonitor->quit();
689         }
690         video_file_info(video_filename, local_file);
691 }
692
693 /* config */
694 void
695 VideoTimeLine::parameter_changed (std::string const & p)
696 {
697         if (p == "video-server-url") {
698                 set_video_server_url (video_get_server_url(Config));
699         } else if (p == "video-server-docroot") {
700                 set_video_server_docroot (video_get_docroot(Config));
701         } else if (p == "video-advanced-setup") {
702                 set_video_server_url (video_get_server_url(Config));
703                 set_video_server_docroot (video_get_docroot(Config));
704         }
705         if (p == "use-video-file-fps" || p == "videotimeline-pullup" ) { /* session->config parameter */
706                 VtlUpdate();
707         }
708 }
709
710 void
711 VideoTimeLine::set_video_server_url(std::string vsu) {
712         flush_local_cache ();
713         video_server_url = vsu;
714         VtlUpdate();
715 }
716
717 void
718 VideoTimeLine::set_video_server_docroot(std::string vsr) {
719         flush_local_cache ();
720         server_docroot = vsr;
721         VtlUpdate();
722 }
723
724 /* video-monitor for this timeline */
725 void
726 VideoTimeLine::xjadeo_readversion (std::string d, size_t /* s */) {
727         xjadeo_version += d;
728 }
729
730 void
731 VideoTimeLine::find_xjadeo () {
732         std::string xjadeo_file_path;
733 #ifdef PLATFORM_WINDOWS
734         HKEY key;
735         DWORD size = PATH_MAX;
736         char tmp[PATH_MAX+1];
737         const char *program_files = PBD::get_win_special_folder (CSIDL_PROGRAM_FILES);
738 #endif
739         if (getenv("XJREMOTE")) {
740                 _xjadeo_bin = getenv("XJREMOTE");
741         } else if (find_file (Searchpath(Glib::getenv("PATH")), X_("xjremote"), xjadeo_file_path)) {
742                 _xjadeo_bin = xjadeo_file_path;
743         } else if (find_file (Searchpath(Glib::getenv("PATH")), X_("xjadeo"), xjadeo_file_path)) {
744                 _xjadeo_bin = xjadeo_file_path;
745         }
746 #ifdef __APPLE__
747         else if (Glib::file_test(X_("/Applications/Xjadeo.app/Contents/MacOS/xjremote"), Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_EXECUTABLE)) {
748                 _xjadeo_bin = X_("/Applications/Xjadeo.app/Contents/MacOS/xjremote");
749         }
750         else if (Glib::file_test(X_("/Applications/Jadeo.app/Contents/MacOS/xjremote"), Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_EXECUTABLE)) {
751                 _xjadeo_bin = X_("/Applications/Jadeo.app/Contents/MacOS/xjremote");
752         }
753 #endif
754 #ifdef PLATFORM_WINDOWS
755         else if ( (ERROR_SUCCESS == RegOpenKeyExA (HKEY_LOCAL_MACHINE, "Software\\RSS\\xjadeo", 0, KEY_READ, &key))
756                         &&  (ERROR_SUCCESS == RegQueryValueExA (key, "Install_Dir", 0, NULL, reinterpret_cast<LPBYTE>(tmp), &size))
757                         )
758         {
759                 _xjadeo_bin = std::string(g_build_filename(Glib::locale_to_utf8(tmp).c_str(), "xjadeo.exe", 0));
760         }
761         else if (program_files && Glib::file_test(g_build_filename(program_files, "xjadeo", "xjadeo.exe", 0), Glib::FILE_TEST_EXISTS))
762         {
763                 _xjadeo_bin = std::string(g_build_filename(program_files, "xjadeo", "xjadeo.exe", 0));
764         }
765         /* generic fallback to try */
766         else if (Glib::file_test(X_("C:\\Program Files\\xjadeo\\xjadeo.exe"), Glib::FILE_TEST_EXISTS)) {
767                 _xjadeo_bin = X_("C:\\Program Files\\xjadeo\\xjadeo.exe");
768         }
769 #endif
770         else  {
771                 _xjadeo_bin = X_("");
772                 warning << _("Video-monitor 'xjadeo' was not found. Please install http://xjadeo.sf.net/ "
773                                 "(a custom path to xjadeo can be specified by setting the XJREMOTE environment variable. "
774                                 "It should point to an application compatible with xjadeo's remote-control interface 'xjremote').\n"
775                                 "\n"
776                                 "see also http://manual.ardour.org/video-timeline/setup/")
777                         << endmsg;
778         }
779         if (found_xjadeo ()) {
780                 ARDOUR::SystemExec version_check(_xjadeo_bin, X_("--version"));
781                 xjadeo_version = "";
782                 version_check.ReadStdout.connect_same_thread (*this, boost::bind (&VideoTimeLine::xjadeo_readversion, this, _1 ,_2));
783                 version_check.Terminated.connect_same_thread (*this, boost::bind (&VideoTimeLine::xjadeo_readversion, this, "\n" ,1));
784                 if (version_check.start(2)) {
785                         warning << _(
786                                         "Video-monitor 'xjadeo' cannot be launched."
787                                         ) << endmsg;
788                         _xjadeo_bin = X_("");
789                         return;
790                 }
791
792                 version_check.wait ();
793                 int timeout = 300;
794                 while (xjadeo_version.empty() && --timeout) {
795                         Glib::usleep(10000);
796                 }
797
798                 bool v_ok = false;
799                 size_t vo = xjadeo_version.find(" version ");
800                 if (vo != string::npos) {
801                         int v_major, v_minor, v_micro;
802                         if(sscanf(xjadeo_version.substr(vo + 9, string::npos).c_str(),"%d.%d.%d",
803                                                 &v_major, &v_minor, &v_micro) == 3)
804                         {
805                                 if (v_major >= 1) v_ok = true;
806                                 else if (v_major == 0 && v_minor >= 8) v_ok = true;
807                                 else if (v_major == 0 && v_minor >= 7 && v_micro >= 7) v_ok = true;
808                         }
809                 }
810                 if (!v_ok) {
811                         _xjadeo_bin = X_("");
812                         warning << _(
813                                         "Video-monitor 'xjadeo' is too old. "
814                                         "Please install xjadeo version 0.7.7 or later. http://xjadeo.sf.net/"
815                                         ) << endmsg;
816                 }
817         }
818 }
819
820 void
821 VideoTimeLine::open_video_monitor() {
822         if (!found_xjadeo()) return;
823         if (!vmonitor) {
824                 vmonitor = new VideoMonitor(editor, _xjadeo_bin);
825                 vmonitor->set_session(_session);
826                 vmonitor->set_offset(video_offset);
827                 vmonitor->Terminated.connect (sigc::mem_fun (*this, &VideoTimeLine::terminated_video_monitor));
828                 vmonitor->UiState.connect (*this, invalidator (*this), boost::bind (&VideoTimeLine::gui_update, this, _1), gui_context());
829         } else if (vmonitor->is_started()) {
830                 return;
831         }
832
833 #if 0
834         /* unused for now.
835          * the idea is to selective ignore certain monitor window
836          * states if xjadeo is not running on the same host as ardour.
837          * However with the removal of the video-monitor-startup-dialogue
838          * (git rev 5a4d0fff0) these settings are currently not accessible.
839          */
840         int xj_settings_mask = vmonitor->restore_settings_mask();
841         if (_session) {
842                 /* load mask from Session */
843                 XMLNode* node = _session->extra_xml (X_("XJRestoreSettings"));
844                 if (node) {
845                         const XMLProperty* prop = node->property (X_("mask"));
846                         if (prop) {
847                                 xj_settings_mask = atoi(prop->value());
848                         }
849                 }
850         }
851
852         vmonitor->restore_settings_mask(xj_settings_mask);
853 #endif
854
855         if (!vmonitor->start()) {
856                 warning << "launching xjadeo failed.." << endmsg;
857                 close_video_monitor();
858         } else {
859                 GuiUpdate("set-xjadeo-active-on");
860                 vmonitor->set_fps(video_file_fps);
861                 vmonitor->open(video_filename);
862
863                 if (_session) {
864                         XMLNode* node = _session->extra_xml (X_("Videomonitor"));
865                         if (node) {
866                                 const XMLProperty* prop = node->property (X_("active"));
867                                 if (prop && prop->value() != "yes") _session->set_dirty ();
868                         } else {
869                                 _session->set_dirty ();
870                         }
871                 }
872
873         }
874 }
875
876 void
877 VideoTimeLine::close_video_monitor() {
878         if (vmonitor && vmonitor->is_started()) {
879                 vmonitor->quit();
880         }
881 }
882
883 void
884 VideoTimeLine::control_video_monitor(int what, int param) {
885         if (!vmonitor || !vmonitor->is_started()) {
886                 return;
887         }
888         vmonitor->send_cmd(what, param);
889 }
890
891
892 void
893 VideoTimeLine::terminated_video_monitor () {
894         if (vmonitor) {
895                 vmonitor->save_session();
896                 delete vmonitor;
897         }
898         vmonitor=0;
899         GuiUpdate("set-xjadeo-active-off");
900         if (reopen_vmonitor) {
901                 reopen_vmonitor=false;
902                 open_video_monitor();
903         } else {
904                 if (_session) {
905                         _session->set_dirty ();
906                 }
907         }
908 }
909
910 void
911 VideoTimeLine::manual_seek_video_monitor (framepos_t pos)
912 {
913         if (!vmonitor) { return; }
914         if (!vmonitor->is_started()) { return; }
915         if (!vmonitor->synced_by_manual_seeks()) { return; }
916         vmonitor->manual_seek(pos, false, video_offset); // XXX -> set offset in xjadeo
917 }