Merge branch 'master' into cairocanvas
[ardour.git] / gtk2_ardour / video_image_frame.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 #ifdef WITH_VIDEOTIMELINE
21
22 #include <sigc++/bind.h>
23 #include "ardour/tempo.h"
24
25 #include "ardour_ui.h"
26 #include "video_image_frame.h"
27 #include "public_editor.h"
28 #include "utils.h"
29 #include "canvas/group.h"
30 #include "rgb_macros.h"
31 #include "utils_videotl.h"
32
33 #include <gtkmm2ext/utils.h>
34 #include <pthread.h>
35
36 #include "i18n.h"
37
38 using namespace std;
39 using namespace ARDOUR;
40
41 VideoImageFrame::VideoImageFrame (PublicEditor& ed, ArdourCanvas::Group& parent, int w, int h, std::string vsurl, std::string vfn)
42         : editor (ed)
43         , _parent(&parent)
44         , clip_width(w)
45         , clip_height(h)
46         , video_server_url(vsurl)
47         , video_filename(vfn)
48 {
49         pthread_mutex_init(&request_lock, NULL);
50         pthread_mutex_init(&queue_lock, NULL);
51         queued_request=false;
52         video_frame_number = -1;
53         rightend = -1;
54         frame_position = 0;
55         thread_active=false;
56
57 #if 0 /* DEBUG */
58         printf("New VideoImageFrame (%ix%i) %s - %s\n", w, h, vsurl.c_str(), vfn.c_str());
59 #endif
60
61         unit_position = editor.frame_to_unit (frame_position);
62         group = new ArdourCanvas::Group (_parent, ArdourCanvas::Duple(unit_position, 1.0));
63         img_pixbuf = new ArdourCanvas::Pixbuf(group);
64
65         Glib::RefPtr<Gdk::Pixbuf> img;
66
67         img = Gdk::Pixbuf::create(Gdk::COLORSPACE_RGB, true, 8, clip_width, clip_height);
68         img->fill(RGBA_TO_UINT(0,0,0,255));
69         img_pixbuf->set(img);
70
71         draw_line();
72         video_draw_cross(img_pixbuf->pixbuf());
73         img_pixbuf->set(img_pixbuf->pixbuf());
74
75         group->Event.connect (sigc::bind (sigc::mem_fun (editor, &PublicEditor::canvas_videotl_bar_event), _parent));
76 }
77
78 VideoImageFrame::~VideoImageFrame ()
79 {
80         if (thread_active) pthread_join(thread_id_tt, NULL);
81         delete img_pixbuf;
82         delete group;
83         pthread_mutex_destroy(&request_lock);
84         pthread_mutex_destroy(&queue_lock);
85 }
86
87 void
88 VideoImageFrame::set_position (framepos_t frame)
89 {
90         double new_unit_position = editor.frame_to_unit (frame);
91         group->move (ArdourCanvas::Duple (new_unit_position - unit_position, 0.0));
92         frame_position = frame;
93         unit_position = new_unit_position;
94 }
95
96 void
97 VideoImageFrame::reposition ()
98 {
99         set_position (frame_position);
100 }
101
102 void
103 VideoImageFrame::exposeimg ()
104 {
105         img_pixbuf->show();
106         /* Note: we can not use this thread to update the window
107          * it needs to be done from the Editor's thread idle_update */
108         ImgChanged(); /* EMIT SIGNAL */
109 }
110
111 void
112 VideoImageFrame::set_videoframe (framepos_t videoframenumber, int re)
113 {
114         if (video_frame_number == videoframenumber && rightend == re) return;
115
116         video_frame_number = videoframenumber;
117         rightend = re;
118 #if 0 /* dummy mode: print framenumber */
119         gchar buf[16];
120         snprintf (buf, sizeof(buf), "%li", (long int) videoframenumber);
121         img_pixbuf->pixbuf() = pixbuf_from_ustring(g_strdup (buf), get_font_for_style (N_("MarkerText")), 80, 60, Gdk::Color ("#C0C0C0"));
122         return;
123 #endif
124 #if 1 /* draw "empty frame" while we request the data */
125         Glib::RefPtr<Gdk::Pixbuf> img;
126         img = img_pixbuf->pixbuf();
127         img->fill(RGBA_TO_UINT(0,0,0,255));
128         video_draw_cross(img_pixbuf->pixbuf());
129         draw_line();
130         cut_rightend();
131         img_pixbuf->set(img);
132         exposeimg();
133 #endif
134         /* request video-frame from decoder in background thread */
135         http_get(video_frame_number);
136 }
137
138 void
139 VideoImageFrame::draw_line ()
140 {
141         Glib::RefPtr<Gdk::Pixbuf> img;
142         img = img_pixbuf->pixbuf();
143
144         int rowstride = img->get_rowstride();
145         int clip_height = img->get_height();
146         int n_channels = img->get_n_channels();
147         guchar *pixels, *p;
148         pixels = img->get_pixels();
149
150         int y;
151         for (y=0;y<clip_height;y++) {
152                 p = pixels + y * rowstride;
153                 p[0] = 255; p[1] = 255; p[2] = 255;
154                 if (n_channels>3) p[3] = 255;
155         }
156 }
157
158 void
159 VideoImageFrame::cut_rightend ()
160 {
161         if (rightend < 0 ) { return; }
162         Glib::RefPtr<Gdk::Pixbuf> img;
163         img = img_pixbuf->pixbuf();
164
165         int rowstride = img->get_rowstride();
166         int clip_height = img->get_height();
167         int clip_width = img->get_width();
168         int n_channels = img->get_n_channels();
169         guchar *pixels, *p;
170         pixels = img->get_pixels();
171         if (rightend > clip_width) { return; }
172
173         int x,y;
174         for (y=0;y<clip_height;++y) {
175                 p = pixels + y * rowstride + rightend * n_channels;
176                 p[0] = 192; p[1] = 127; p[2] = 127;
177                 if (n_channels>3) p[3] = 255;
178                 for (x=rightend+1; x<clip_width; ++x) {
179                         p = pixels + y * rowstride + x * n_channels;
180                         p[0] = 0; p[1] = 0; p[2] = 0;
181                         if (n_channels>3) p[3] = 0;
182                 }
183         }
184 }
185
186 void *
187 http_get_thread (void *arg) {
188         VideoImageFrame *vif = static_cast<VideoImageFrame *>(arg);
189         char url[2048];
190         pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
191         pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
192         snprintf(url, sizeof(url), "%s?frame=%li&w=%d&h=%di&file=%s&format=rgb",
193           vif->get_video_server_url().c_str(),
194           (long int) vif->get_req_frame(), vif->get_width(), vif->get_height(),
195           vif->get_video_filename().c_str()
196         );
197         int status = 0;
198         int timeout = 1000; // * 5ms -> 5sec
199         char *res = NULL;
200         do {
201                 res=curl_http_get(url, &status);
202                 if (status == 503) usleep(5000); // try-again
203         } while (status == 503 && --timeout > 0);
204
205         if (status != 200 || !res) {
206                 printf("no-video frame: video-server returned http-status: %d\n", status);
207         }
208
209         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
210         vif->http_download_done(res);
211         pthread_exit(0);
212         return 0;
213 }
214
215 void
216 VideoImageFrame::http_download_done (char *data){
217         if (queued_request) {
218                 http_get_again(want_video_frame_number);
219                 return;
220         }
221
222         if (!data) {
223                 /* Image request failed (HTTP error or timeout) */
224                 Glib::RefPtr<Gdk::Pixbuf> img;
225                 img = img_pixbuf->pixbuf();
226                 img->fill(RGBA_TO_UINT(128,0,0,255));
227                 video_draw_cross(img_pixbuf->pixbuf());
228                 cut_rightend();
229                 draw_line();
230                 cut_rightend();
231                 img_pixbuf->set(img);
232                 /* TODO: mark as invalid:
233                  * video_frame_number = -1;
234                  * TODO: but prevent live-loops when calling update again
235                  */
236         } else {
237                 Glib::RefPtr<Gdk::Pixbuf> tmp, img;
238 #if 0 // RGBA
239                 tmp = Gdk::Pixbuf::create_from_data ((guint8*) data, Gdk::COLORSPACE_RGB, true, 8, clip_width, clip_height, clip_width*4);
240 #else // RGB
241                 tmp = Gdk::Pixbuf::create_from_data ((guint8*) data, Gdk::COLORSPACE_RGB, false, 8, clip_width, clip_height, clip_width*3);
242 #endif
243                 img = img_pixbuf->pixbuf();
244                 tmp->copy_area (0, 0, clip_width, clip_height, img, 0, 0);
245                 free(data);
246                 draw_line();
247                 cut_rightend();
248                 img_pixbuf->set(img);
249         }
250
251         exposeimg();
252         /* don't request frames too quickly, wait after user has zoomed */
253         usleep(40000);
254
255         if (queued_request) {
256                 http_get_again(want_video_frame_number);
257         }
258         pthread_mutex_unlock(&request_lock);
259 }
260
261
262 void
263 VideoImageFrame::http_get(framepos_t fn) {
264         if (pthread_mutex_trylock(&request_lock)) {
265                 /* remember last request and schedule after the lock has been released. */
266                 pthread_mutex_lock(&queue_lock);
267                 queued_request=true;
268                 want_video_frame_number=fn;
269                 pthread_mutex_unlock(&queue_lock);
270 #if 0
271                 /* TODO: cancel request and start a new one
272                  *  but only if we're waiting for curl request.
273                  *  don't interrupt http_download_done()
274                  *
275                  *  This should work, but requires testing:
276                  */
277                 if (!pthread_cancel(thread_id_tt)) {
278                         pthread_mutex_unlock(&request_lock);
279                 } else return;
280 #else
281                 return;
282 #endif
283         }
284         if (thread_active) pthread_join(thread_id_tt, NULL);
285         pthread_mutex_lock(&queue_lock);
286         queued_request=false;
287         req_video_frame_number=fn;
288         pthread_mutex_unlock(&queue_lock);
289         int rv = pthread_create(&thread_id_tt, NULL, http_get_thread, this);
290         thread_active=true;
291         if (rv) {
292                 thread_active=false;
293                 printf("thread creation failed. %i\n",rv);
294                 http_download_done(NULL);
295         }
296 }
297
298 void
299 VideoImageFrame::http_get_again(framepos_t fn) {
300         pthread_mutex_lock(&queue_lock);
301         queued_request=false;
302         req_video_frame_number=want_video_frame_number;
303         pthread_mutex_unlock(&queue_lock);
304
305         http_get_thread(this);
306 }
307
308
309 extern "C" {
310 #include <curl/curl.h>
311
312         struct MemoryStruct {
313                 char *data;
314                 size_t size;
315         };
316
317         static size_t
318         WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) {
319                 size_t realsize = size * nmemb;
320                 struct MemoryStruct *mem = (struct MemoryStruct *)data;
321
322                 mem->data = (char *)realloc(mem->data, mem->size + realsize + 1);
323                 if (mem->data) {
324                         memcpy(&(mem->data[mem->size]), ptr, realsize);
325                         mem->size += realsize;
326                         mem->data[mem->size] = 0;
327                 }
328                 return realsize;
329         }
330
331         char *curl_http_get (const char *u, int *status) {
332                 CURL *curl;
333                 CURLcode res;
334                 struct MemoryStruct chunk;
335                 long int httpstatus;
336                 if (status) *status = 0;
337                 //usleep(500000); return NULL; // TEST & DEBUG
338                 if (strncmp("http://", u, 7)) return NULL;
339
340                 chunk.data=NULL;
341                 chunk.size=0;
342
343                 curl = curl_easy_init();
344                 if(!curl) return NULL;
345                 curl_easy_setopt(curl, CURLOPT_URL, u);
346
347                 curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
348                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
349                 curl_easy_setopt(curl, CURLOPT_USERAGENT, ARDOUR_USER_AGENT);
350                 curl_easy_setopt(curl, CURLOPT_TIMEOUT, ARDOUR_CURL_TIMEOUT);
351                 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
352 #define CURLERRORDEBUG /* XXX */
353 #ifdef CURLERRORDEBUG
354                 char curlerror[CURL_ERROR_SIZE] = "";
355                 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curlerror);
356 #endif
357
358                 res = curl_easy_perform(curl);
359                 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpstatus);
360                 curl_easy_cleanup(curl);
361                 if (status) *status = httpstatus;
362                 if (res) {
363 #ifdef CURLERRORDEBUG
364                         printf("curl_http_get() failed: %s\n", curlerror);
365 #endif
366                         return NULL;
367                 }
368                 if (httpstatus != 200) {
369                         free (chunk.data);
370                         chunk.data = NULL;
371                 }
372                 return (chunk.data);
373         }
374
375 } /* end extern "C" */
376
377 #endif /* WITH_VIDEOTIMELINE */