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