Merge branch 'master' of git.ardour.org:ardour/ardour
[ardour.git] / gtk2_ardour / add_video_dialog.cc
1 /*
2     Copyright (C) 2010-2013 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 #ifdef WITH_VIDEOTIMELINE
21
22 #include <cstdio>
23 #include <cmath>
24
25 #include <sigc++/bind.h>
26 #include <curl/curl.h>
27
28 #include "pbd/error.h"
29 #include "pbd/convert.h"
30 #include "gtkmm2ext/utils.h"
31 #include "gtkmm2ext/rgb_macros.h"
32 #include "ardour/session_directory.h"
33 #include "ardour/profile.h"
34 #include "ardour/template_utils.h"
35 #include "ardour/session.h"
36 #include "ardour_ui.h"
37
38 #include "utils.h"
39 #include "add_video_dialog.h"
40 #include "utils_videotl.h"
41 #include "i18n.h"
42
43 using namespace Gtk;
44 using namespace std;
45 using namespace PBD;
46 using namespace ARDOUR;
47
48 #define PREVIEW_WIDTH (240)
49 #define PREVIEW_HEIGHT (180)
50
51 #ifndef MIN
52 #define MIN(a,b) ( (a) < (b) ? (a) : (b) )
53 #endif
54
55 AddVideoDialog::AddVideoDialog (Session* s)
56         : ArdourDialog (_("Set Video Track"))
57         , seek_slider (0,1000,1)
58         , preview_path ("")
59         , pi_duration ("-", Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, false)
60         , pi_aspect ("-", Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, false)
61         , pi_fps ("-", Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, false)
62         , chooser (FILE_CHOOSER_ACTION_OPEN)
63         , xjadeo_checkbox (_("Launch External Video Monitor"))
64         , set_session_fps_checkbox (_("Adjust Session Framerate to Match Video Framerate"))
65         , harvid_path ("")
66         , harvid_reset (_("Reload docroot"))
67         , harvid_list (ListStore::create(harvid_list_columns))
68         , harvid_list_view (harvid_list)
69 {
70         set_session (s);
71         set_name ("AddVideoDialog");
72         set_position (Gtk::WIN_POS_MOUSE);
73         set_modal (true);
74         set_skip_taskbar_hint (true);
75         set_resizable (true);
76         set_size_request (800, -1);
77
78         harvid_initialized = false;
79         std::string dstdir = video_dest_dir(_session->session_directory().video_path(), video_get_docroot(Config));
80
81         if (Config->get_video_advanced_setup()) {
82
83                 /* Harvid Browser */
84                 harvid_list_view.append_column("", pixBufRenderer);
85                 harvid_list_view.append_column(_("Filename"), harvid_list_columns.filename);
86
87                 harvid_list_view.get_column(0)->set_alignment(0.5);
88                 harvid_list_view.get_column(0)->add_attribute(pixBufRenderer, "stock-id", harvid_list_columns.id);
89                 harvid_list_view.get_column(1)->set_expand(true);
90                 harvid_list_view.get_column(1)->set_sort_column(harvid_list_columns.filename);
91                 harvid_list_view.set_enable_search(true);
92                 harvid_list_view.set_search_column(1);
93
94                 harvid_list_view.get_selection()->set_mode (SELECTION_SINGLE);
95
96                 harvid_list_view.get_selection()->signal_changed().connect(sigc::mem_fun(*this, &AddVideoDialog::harvid_list_view_selected));
97                 harvid_list_view.signal_row_activated().connect (sigc::mem_fun (*this, &AddVideoDialog::harvid_list_view_activated));
98
99                 VBox* vbox = manage (new VBox);
100                 Gtk::ScrolledWindow *scroll = manage(new ScrolledWindow);
101                 scroll->add(harvid_list_view);
102                 scroll->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
103
104                 HBox* hbox = manage (new HBox);
105                 harvid_path.set_alignment (0, 0.5);
106                 hbox->pack_start (harvid_path, true, true);
107                 hbox->pack_start (harvid_reset, false, false);
108
109                 vbox->pack_start (*hbox, false, false);
110                 vbox->pack_start (*scroll, true, true);
111
112                 notebook.append_page (*vbox, _("VideoServerIndex"));
113         } else {
114                 /* dummy entry */
115                 VBox* vbox = manage (new VBox);
116                 notebook.append_page (*vbox, _("VideoServerIndex"));
117         }
118
119         /* file chooser */
120         chooser.set_border_width (4);
121 #ifdef GTKOSX
122         /* some broken redraw behaviour - this is a bandaid */
123         chooser.signal_selection_changed().connect (mem_fun (chooser, &Widget::queue_draw));
124 #endif
125         chooser.set_current_folder (dstdir);
126
127         Gtk::FileFilter video_filter;
128         Gtk::FileFilter matchall_filter;
129         video_filter.add_custom (FILE_FILTER_FILENAME, mem_fun(*this, &AddVideoDialog::on_video_filter));
130         video_filter.set_name (_("Video files"));
131
132         matchall_filter.add_pattern ("*.*");
133         matchall_filter.set_name (_("All files"));
134
135         chooser.add_filter (video_filter);
136         chooser.add_filter (matchall_filter);
137         chooser.set_select_multiple (false);
138
139         VBox* vboxfb = manage (new VBox);
140         vboxfb->pack_start (chooser, true, true, 0);
141
142         if (video_get_docroot(Config).size() > 0 &&
143                         Config->get_video_advanced_setup()) {
144                 notebook.append_page (*vboxfb, _("Browse Files"));
145         }
146
147         /* Global Options*/
148         Gtk::Label* l;
149         VBox* options_box = manage (new VBox);
150
151         l = manage (new Label (_("<b>Options</b>"), Gtk::ALIGN_LEFT, Gtk::ALIGN_CENTER, false));
152         l->set_use_markup ();
153
154         options_box->pack_start (*l, false, true, 4);
155         options_box->pack_start (xjadeo_checkbox, false, true, 2);
156         options_box->pack_start (set_session_fps_checkbox, false, true, 2);
157
158         /* preview pane */
159         VBox* previewpane = manage (new VBox);
160         Gtk::Table *table = manage(new Table(4,2));
161
162         table->set_row_spacings(2);
163         table->set_col_spacings(4);
164
165         l = manage (new Label (_("<b>Video Information</b>"), Gtk::ALIGN_CENTER, Gtk::ALIGN_CENTER, false));
166         l->set_use_markup ();
167         table->attach (*l, 0, 2, 0, 1, FILL, FILL);
168         l = manage (new Label (_("Duration:"), Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, false));
169         table->attach (*l, 0, 1, 1, 2, FILL, FILL);
170         table->attach (pi_duration, 1, 2, 1, 2, FILL, FILL);
171         l = manage (new Label (_("Frame rate:"), Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, false));
172         table->attach (*l, 0, 1, 2, 3, FILL, FILL);
173         table->attach (pi_fps, 1, 2, 2, 3, FILL, FILL);
174         l = manage (new Label (_("Aspect Ratio:"), Gtk::ALIGN_RIGHT, Gtk::ALIGN_CENTER, false));
175         table->attach (*l, 0, 1, 3, 4, FILL, FILL);
176         table->attach (pi_aspect, 1, 2, 3, 4, FILL, FILL);
177
178         preview_image = manage(new Gtk::Image);
179
180         imgbuf = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true, 8, PREVIEW_WIDTH, PREVIEW_HEIGHT);
181         imgbuf->fill(RGBA_TO_UINT(127,0,0,255));
182         preview_image->set(imgbuf);
183         seek_slider.set_draw_value(false);
184
185         HBox* hbox = manage (new HBox);
186         hbox->pack_start (*table, true, false);
187
188         Gtk::Alignment *al = manage(new Gtk::Alignment());
189         al->set_size_request(-1, 20);
190
191         previewpane->pack_start (*al, false, false);
192         previewpane->pack_start (*hbox, true, true, 6);
193         previewpane->pack_start (*preview_image, false, false);
194         previewpane->pack_start (seek_slider, false, false);
195
196         /* Overall layout */
197         hbox = manage (new HBox);
198         if (Config->get_video_advanced_setup()) {
199                 hbox->pack_start (notebook, true, true);
200         } else {
201                 hbox->pack_start (*vboxfb, true, true);
202         }
203         hbox->pack_start (*previewpane, false, false);
204
205         get_vbox()->set_spacing (4);
206         get_vbox()->pack_start (*hbox, true, true);
207         get_vbox()->pack_start (*options_box, false, false);
208
209
210         /* xjadeo checkbox */
211         if (ARDOUR_UI::instance()->video_timeline->found_xjadeo()
212                         /* TODO xjadeo setup w/ xjremote */
213                         && video_get_docroot(Config).size() > 0) {
214                 xjadeo_checkbox.set_active(true);  /* set in ardour_ui.cpp ?! */
215         } else {
216                 printf("xjadeo was not found or video-server docroot is unset (remote video-server)\n");
217                 xjadeo_checkbox.set_active(false);
218                 xjadeo_checkbox.set_sensitive(false);
219         }
220
221         /* FPS checkbox */
222         set_session_fps_checkbox.set_active(true);
223
224         /* Buttons */
225         add_button (Stock::CANCEL, RESPONSE_CANCEL);
226         ok_button = add_button (Stock::OK, RESPONSE_ACCEPT);
227         //ok_button->set_sensitive(false);
228         set_action_ok(false);
229
230         /* connect signals after eveything has been initialized */
231         chooser.signal_selection_changed().connect (mem_fun (*this, &AddVideoDialog::file_selection_changed));
232         chooser.signal_file_activated().connect (mem_fun (*this, &AddVideoDialog::file_activated));
233         //chooser.signal_update_preview().connect(sigc::mem_fun(*this, &AddVideoDialog::update_preview));
234         notebook.signal_switch_page().connect (sigc::hide_return (sigc::hide (sigc::hide (sigc::mem_fun (*this, &AddVideoDialog::page_switch)))));
235         seek_slider.signal_value_changed().connect(sigc::mem_fun(*this, &AddVideoDialog::seek_preview));
236         harvid_reset.signal_clicked().connect (sigc::mem_fun (*this, &AddVideoDialog::harvid_load_docroot));
237
238         show_all_children ();
239 }
240
241 AddVideoDialog::~AddVideoDialog ()
242 {
243 }
244
245 void
246 AddVideoDialog::on_show ()
247 {
248         Dialog::on_show ();
249 }
250
251 static bool check_video_file_extension(std::string file)
252 {
253         const char* suffixes[] = {
254                 ".avi"     , ".AVI"     ,
255                 ".mov"     , ".MOV"     ,
256                 ".ogg"     , ".OGG"     ,
257                 ".ogv"     , ".OGV"     ,
258                 ".mpg"     , ".MPG"     ,
259                 ".mov"     , ".MOV"     ,
260                 ".mp4"     , ".MP4"     ,
261                 ".mkv"     , ".MKV"     ,
262                 ".vob"     , ".VOB"     ,
263                 ".asf"     , ".ASF"     ,
264                 ".avs"     , ".AVS"     ,
265                 ".dts"     , ".DTS"     ,
266                 ".flv"     , ".FLV"     ,
267                 ".m4v"     , ".M4V"     ,
268                 ".matroska", ".MATROSKA",
269                 ".h264"    , ".H264"    ,
270                 ".dv"      , ".DV"      ,
271                 ".dirac"   , ".DIRAC"   ,
272                 ".webm"    , ".WEBM"    ,
273         };
274
275         for (size_t n = 0; n < sizeof(suffixes)/sizeof(suffixes[0]); ++n) {
276                 if (file.rfind (suffixes[n]) == file.length() - strlen (suffixes[n])) {
277                         return true;
278                 }
279         }
280
281         return false;
282 }
283
284 bool
285 AddVideoDialog::on_video_filter (const FileFilter::Info& filter_info)
286 {
287         return check_video_file_extension(filter_info.filename);
288 }
289
290 std::string
291 AddVideoDialog::file_name (bool &local_file)
292 {
293         int n = notebook.get_current_page ();
294         if (n == 1 || ! Config->get_video_advanced_setup()) {
295                 local_file = true;
296                 return chooser.get_filename();
297         } else {
298                 local_file = false;
299                 Gtk::TreeModel::iterator iter = harvid_list_view.get_selection()->get_selected();
300                 if(!iter) return "";
301
302                 std::string uri = (*iter)[harvid_list_columns.uri];
303                 std::string video_server_url = video_get_server_url(Config);
304
305                 /* check if video server is running locally */
306                 if (video_get_docroot(Config).size() > 0
307                                 && !video_server_url.compare(0, 16, "http://localhost"))
308                 {
309                         /* check if the file can be accessed */
310                         int plen;
311                         CURL *curl;
312                         curl = curl_easy_init();
313                         char *ue = curl_easy_unescape(curl, uri.c_str(), uri.length(), &plen);
314                         std::string path = video_get_docroot(Config) + ue;
315                         if (!::access(path.c_str(), R_OK)) {
316                                 uri = path;
317                                 local_file = true;
318                         }
319                         curl_easy_cleanup(curl);
320                         curl_free(ue);
321                 }
322                 return uri;
323         }
324 }
325
326 enum VtlImportOption
327 AddVideoDialog::import_option ()
328 {
329         int n = notebook.get_current_page ();
330         if (n == 0 && Config->get_video_advanced_setup()) { return VTL_IMPORT_NONE; }
331         return VTL_IMPORT_TRANSCODE;
332 }
333
334 bool
335 AddVideoDialog::launch_xjadeo ()
336 {
337         return xjadeo_checkbox.get_active();
338 }
339
340 bool
341 AddVideoDialog::auto_set_session_fps ()
342 {
343         return set_session_fps_checkbox.get_active();
344 }
345
346 void
347 AddVideoDialog::set_action_ok (bool yn)
348 {
349         if (yn) {
350                 ok_button->set_sensitive(true);
351         } else {
352                 preview_path = "";
353                 pi_duration.set_text("-");
354                 pi_aspect.set_text("-");
355                 pi_fps.set_text("-");
356                 ok_button->set_sensitive(false);
357                 imgbuf->fill(RGBA_TO_UINT(0,0,0,255));
358                 video_draw_cross(imgbuf);
359                 preview_image->set(imgbuf);
360                 preview_image->show();
361         }
362 }
363
364 void
365 AddVideoDialog::file_selection_changed ()
366 {
367         if (chooser.get_filename().size() > 0) {
368                 std::string path = chooser.get_filename();
369                 bool ok =
370                                 check_video_file_extension(path)
371                                 &&  Glib::file_test(path.c_str(), Glib::FILE_TEST_IS_REGULAR | Glib::FILE_TEST_IS_SYMLINK)
372                                 && !Glib::file_test(path.c_str(), Glib::FILE_TEST_IS_DIR);
373                 set_action_ok(ok);
374                 if (ok) {
375                         request_preview(video_map_path(video_get_docroot(Config), path));
376                 }
377         } else {
378                 set_action_ok(false);
379         }
380 }
381
382 void
383 AddVideoDialog::file_activated ()
384 {
385         if (chooser.get_filename().size() > 0) {
386                 std::string path = chooser.get_filename();
387                 // TODO check docroot -> set import options
388                 bool ok =
389                                 check_video_file_extension(path)
390                                 &&  Glib::file_test(path.c_str(), Glib::FILE_TEST_IS_REGULAR | Glib::FILE_TEST_IS_SYMLINK)
391                                 && !Glib::file_test(path.c_str(), Glib::FILE_TEST_IS_DIR);
392                 if (ok) {
393                         Gtk::Dialog::response(RESPONSE_ACCEPT);
394                 }
395         }
396 }
397
398 /**** Tree List Interaction ***/
399
400 void
401 AddVideoDialog::harvid_list_view_selected () {
402         Gtk::TreeModel::iterator iter = harvid_list_view.get_selection()->get_selected();
403         // TODO check docroot -> set import options, xjadeo
404         if(!iter) {
405                 set_action_ok(false);
406                 return;
407         }
408         if ((std::string)((*iter)[harvid_list_columns.id]) == Stock::DIRECTORY.id) {
409                 set_action_ok(false);
410         } else {
411                 set_action_ok(true);
412                 request_preview((*iter)[harvid_list_columns.uri]);
413         }
414 }
415
416 void
417 AddVideoDialog::harvid_list_view_activated (const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn*) {
418         Gtk::TreeModel::iterator iter = harvid_list->get_iter(path);
419         if (!iter) return;
420         std::string type = (*iter)[harvid_list_columns.id];
421         std::string url = (*iter)[harvid_list_columns.uri];
422
423 #if 0
424         printf ("A: %s %s %s\n",
425                         ((std::string)((*iter)[harvid_list_columns.id])).c_str(),
426                         ((std::string)((*iter)[harvid_list_columns.uri])).c_str(),
427                         ((std::string)((*iter)[harvid_list_columns.filename])).c_str());
428 #endif
429
430         if (type == Gtk::Stock::DIRECTORY.id) {
431                 harvid_request(url.c_str());
432         } else {
433                 Gtk::Dialog::response(RESPONSE_ACCEPT);
434         }
435 }
436
437 void
438 AddVideoDialog::harvid_load_docroot() {
439         set_action_ok(false);
440
441         std::string video_server_url = video_get_server_url(Config);
442         char url[2048];
443         snprintf(url, sizeof(url), "%s%sindex/"
444                 , video_server_url.c_str()
445                 , (video_server_url.length()>0 && video_server_url.at(video_server_url.length()-1) == '/')?"":"/");
446         harvid_request(url);
447         harvid_initialized = true;
448 }
449
450 bool
451 AddVideoDialog::page_switch() {
452         if (notebook.get_current_page () == 1 || Config->get_video_advanced_setup()) {
453                 file_selection_changed();
454                 return true;
455         }
456
457         if (harvid_initialized) {
458                 harvid_list_view_selected();
459         } else {
460                 harvid_load_docroot();
461         }
462         return true;
463 }
464
465 /**** Harvid HTTP interface ***/
466 void
467 AddVideoDialog::harvid_request(std::string u)
468 {
469         char url[2048];
470         int status;
471         snprintf(url, sizeof(url), "%s?format=csv", u.c_str());
472
473         harvid_list->clear();
474
475         char *res = curl_http_get(url, &status);
476         if (status != 200) {
477                 printf("request failed\n"); // XXX
478                 harvid_path.set_text(" - request failed -");
479                 free(res);
480                 return;
481         }
482
483         /* add up-to-parent */
484         size_t se = u.find_last_of("/", u.size()-2);
485         size_t ss = u.find("/index/");
486         if (se != string::npos && ss != string::npos && se > ss) {
487                 TreeModel::iterator new_row = harvid_list->append();
488                 TreeModel::Row row = *new_row;
489                 row[harvid_list_columns.id      ] = Gtk::Stock::DIRECTORY.id;
490                 row[harvid_list_columns.uri     ] = u.substr(0, se + 1);
491                 row[harvid_list_columns.filename] = X_("..");
492         }
493         if (se != string::npos) {
494                 int plen;
495                 std::string path = u.substr(ss + 6);
496                 CURL *curl;
497                 curl = curl_easy_init();
498                 char *ue = curl_easy_unescape(curl, path.c_str(), path.length(), &plen);
499                 harvid_path.set_text(std::string(ue));
500                 curl_easy_cleanup(curl);
501                 curl_free(ue);
502         } else {
503                 harvid_path.set_text(" ??? ");
504         }
505
506         if (!res) return;
507
508         std::vector<std::vector<std::string> > lines;
509         ParseCSV(std::string(res), lines);
510         for (std::vector<std::vector<std::string> >::iterator i = lines.begin(); i != lines.end(); ++i) {
511                 TreeModel::iterator new_row = harvid_list->append();
512                 TreeModel::Row row = *new_row;
513
514                 if (i->at(0) == X_("D")) {
515                         row[harvid_list_columns.id      ] = Gtk::Stock::DIRECTORY.id;
516                         row[harvid_list_columns.uri     ] = i->at(1).c_str();
517                         row[harvid_list_columns.filename] = i->at(2).c_str();
518                 } else {
519                         row[harvid_list_columns.id      ] = Gtk::Stock::MEDIA_PLAY.id;
520                         row[harvid_list_columns.uri     ] = i->at(2).c_str();
521                         row[harvid_list_columns.filename] = i->at(3).c_str();
522                 }
523         }
524
525         free(res);
526 }
527
528 void
529 AddVideoDialog::seek_preview()
530 {
531         if (preview_path.size() > 0)
532                 request_preview(preview_path);
533 }
534
535 void
536 AddVideoDialog::request_preview(std::string u)
537 {
538         std::string video_server_url = video_get_server_url(Config);
539
540         double video_file_fps;
541         long long int video_duration;
542         double video_start_offset;
543         double video_aspect_ratio;
544
545         int clip_width = PREVIEW_WIDTH;
546         int clip_height = PREVIEW_HEIGHT;
547         int clip_xoff, clip_yoff;
548
549         if (!video_query_info(video_server_url, u,
550                         video_file_fps, video_duration, video_start_offset, video_aspect_ratio))
551         {
552                 printf("image preview info request failed\n");
553                 // set_action_ok(false); // XXX only if docroot mismatch
554                 preview_path = "";
555                 pi_duration.set_text("-");
556                 pi_aspect.set_text("-");
557                 pi_fps.set_text("-");
558                 return;
559         }
560
561         if ((PREVIEW_WIDTH / (double)PREVIEW_HEIGHT) > video_aspect_ratio ) {
562                 clip_width = MIN(PREVIEW_WIDTH, rint(clip_height * video_aspect_ratio));
563         } else {
564                 clip_height = MIN(PREVIEW_HEIGHT, rint(clip_width / video_aspect_ratio));
565         }
566
567         pi_duration.set_text(string_compose("%1 sec", video_duration / video_file_fps));
568         pi_aspect.set_text(string_compose("%1", video_aspect_ratio));
569         pi_fps.set_text(string_compose("%1 fps", video_file_fps));
570
571         clip_xoff = (PREVIEW_WIDTH - clip_width)/2;
572         clip_yoff = (PREVIEW_HEIGHT - clip_height)/2;
573
574         char url[2048];
575         snprintf(url, sizeof(url), "%s%s?frame=%lli&w=%d&h=%di&file=%s&format=rgb"
576                 , video_server_url.c_str()
577                 , (video_server_url.length()>0 && video_server_url.at(video_server_url.length()-1) == '/')?"":"/"
578                 , (long long) (video_duration * seek_slider.get_value() / 1000.0)
579                 , clip_width, clip_height, u.c_str());
580
581         char *data = curl_http_get(url, NULL);
582         if (!data) {
583                 printf("image preview request failed %s\n", url);
584                 imgbuf->fill(RGBA_TO_UINT(0,0,0,255));
585                 video_draw_cross(imgbuf);
586                 preview_path = "";
587         } else {
588                 Glib::RefPtr<Gdk::Pixbuf> tmp;
589                 tmp = Gdk::Pixbuf::create_from_data ((guint8*) data, Gdk::COLORSPACE_RGB, false, 8, clip_width, clip_height, clip_width*3);
590                 if (clip_width != PREVIEW_WIDTH || clip_height != PREVIEW_HEIGHT) {
591                         imgbuf->fill(RGBA_TO_UINT(0,0,0,255));
592                 }
593                 tmp->copy_area (0, 0, clip_width, clip_height, imgbuf, clip_xoff, clip_yoff);
594                 preview_path = u;
595                 free(data);
596         }
597         preview_image->set(imgbuf);
598         preview_image->show();
599 }
600
601 #endif /* WITH_VIDEOTIMELINE */