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