2011-02-21 Andoni Morales Alastruey <amorales@flumotion.com>
[WebKit-https.git] / Source / WebCore / platform / graphics / gstreamer / WebKitWebSourceGStreamer.cpp
1 /*
2  *  Copyright (C) 2009, 2010 Sebastian Dröge <sebastian.droege@collabora.co.uk>
3  *
4  *  This library is free software; you can redistribute it and/or
5  *  modify it under the terms of the GNU Lesser General Public
6  *  License as published by the Free Software Foundation; either
7  *  version 2 of the License, or (at your option) any later version.
8  *
9  *  This library is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  *  Lesser General Public License for more details.
13  *
14  *  You should have received a copy of the GNU Lesser General Public
15  *  License along with this library; if not, write to the Free Software
16  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18
19 #include "config.h"
20 #include "WebKitWebSourceGStreamer.h"
21 #if USE(GSTREAMER)
22
23 #include "Document.h"
24 #include "GOwnPtr.h"
25 #include "GRefPtr.h"
26 #include "NetworkingContext.h"
27 #include "Noncopyable.h"
28 #include "NotImplemented.h"
29 #include "ResourceHandleClient.h"
30 #include "ResourceHandleInternal.h"
31 #include "ResourceRequest.h"
32 #include "ResourceResponse.h"
33 #include <wtf/text/CString.h>
34 #include <gst/app/gstappsrc.h>
35 #include <gst/pbutils/missing-plugins.h>
36
37 using namespace WebCore;
38
39 class StreamingClient : public ResourceHandleClient {
40     WTF_MAKE_NONCOPYABLE(StreamingClient);
41     public:
42         StreamingClient(WebKitWebSrc*);
43         virtual ~StreamingClient();
44
45         virtual void willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&);
46         virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
47         virtual void didReceiveData(ResourceHandle*, const char*, int, int);
48         virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
49         virtual void didFail(ResourceHandle*, const ResourceError&);
50         virtual void wasBlocked(ResourceHandle*);
51         virtual void cannotShowURL(ResourceHandle*);
52
53     private:
54         WebKitWebSrc* m_src;
55 };
56
57 #define WEBKIT_WEB_SRC_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), WEBKIT_TYPE_WEB_SRC, WebKitWebSrcPrivate))
58 struct _WebKitWebSrcPrivate {
59     GstAppSrc* appsrc;
60     GstPad* srcpad;
61     gchar* uri;
62
63     RefPtr<WebCore::Frame> frame;
64
65     StreamingClient* client;
66     RefPtr<ResourceHandle> resourceHandle;
67
68     guint64 offset;
69     guint64 size;
70     gboolean seekable;
71     gboolean paused;
72
73     guint64 requestedOffset;
74
75     guint needDataID;
76     guint enoughDataID;
77     guint seekID;
78
79     // icecast stuff
80     gboolean iradioMode;
81     gchar* iradioName;
82     gchar* iradioGenre;
83     gchar* iradioUrl;
84     gchar* iradioTitle;
85
86     // TRUE if appsrc's version is >= 0.10.27, see
87     // https://bugzilla.gnome.org/show_bug.cgi?id=609423
88     gboolean haveAppSrc27;
89 };
90
91 enum {
92     PROP_IRADIO_MODE = 1,
93     PROP_IRADIO_NAME,
94     PROP_IRADIO_GENRE,
95     PROP_IRADIO_URL,
96     PROP_IRADIO_TITLE,
97     PROP_LOCATION
98 };
99
100 static GstStaticPadTemplate srcTemplate = GST_STATIC_PAD_TEMPLATE("src",
101                                                                   GST_PAD_SRC,
102                                                                   GST_PAD_ALWAYS,
103                                                                   GST_STATIC_CAPS_ANY);
104
105 GST_DEBUG_CATEGORY_STATIC(webkit_web_src_debug);
106 #define GST_CAT_DEFAULT webkit_web_src_debug
107
108 static void webKitWebSrcUriHandlerInit(gpointer gIface,
109                                             gpointer ifaceData);
110
111 static void webKitWebSrcFinalize(GObject* object);
112 static void webKitWebSrcSetProperty(GObject* object, guint propID, const GValue* value, GParamSpec* pspec);
113 static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value, GParamSpec* pspec);
114 static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStateChange transition);
115 static gboolean webKitWebSrcQuery(GstPad* pad, GstQuery* query);
116
117 static void webKitWebSrcNeedDataCb(GstAppSrc* appsrc, guint length, gpointer userData);
118 static void webKitWebSrcEnoughDataCb(GstAppSrc* appsrc, gpointer userData);
119 static gboolean webKitWebSrcSeekDataCb(GstAppSrc* appsrc, guint64 offset, gpointer userData);
120
121 static void webKitWebSrcStop(WebKitWebSrc* src, bool seeking);
122 static gboolean webKitWebSrcSetUri(GstURIHandler*, const gchar*);
123 static const gchar* webKitWebSrcGetUri(GstURIHandler*);
124
125 static GstAppSrcCallbacks appsrcCallbacks = {
126     webKitWebSrcNeedDataCb,
127     webKitWebSrcEnoughDataCb,
128     webKitWebSrcSeekDataCb,
129     { 0 }
130 };
131
132 static void doInit(GType gtype)
133 {
134     static const GInterfaceInfo uriHandlerInfo = {
135         webKitWebSrcUriHandlerInit,
136         0, 0
137     };
138
139     GST_DEBUG_CATEGORY_INIT(webkit_web_src_debug, "webkitwebsrc", 0, "websrc element");
140     g_type_add_interface_static(gtype, GST_TYPE_URI_HANDLER,
141                                 &uriHandlerInfo);
142 }
143
144 GST_BOILERPLATE_FULL(WebKitWebSrc, webkit_web_src, GstBin, GST_TYPE_BIN, doInit);
145
146 static void webkit_web_src_base_init(gpointer klass)
147 {
148     GstElementClass* eklass = GST_ELEMENT_CLASS(klass);
149
150     gst_element_class_add_pad_template(eklass,
151                                        gst_static_pad_template_get(&srcTemplate));
152     gst_element_class_set_details_simple(eklass,
153                                          (gchar*) "WebKit Web source element",
154                                          (gchar*) "Source",
155                                          (gchar*) "Handles HTTP/HTTPS uris",
156                                          (gchar*) "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
157 }
158
159 static void webkit_web_src_class_init(WebKitWebSrcClass* klass)
160 {
161     GObjectClass* oklass = G_OBJECT_CLASS(klass);
162     GstElementClass* eklass = GST_ELEMENT_CLASS(klass);
163
164     oklass->finalize = webKitWebSrcFinalize;
165     oklass->set_property = webKitWebSrcSetProperty;
166     oklass->get_property = webKitWebSrcGetProperty;
167
168     // icecast stuff
169     g_object_class_install_property(oklass,
170                                     PROP_IRADIO_MODE,
171                                     g_param_spec_boolean("iradio-mode",
172                                                          "iradio-mode",
173                                                          "Enable internet radio mode (extraction of shoutcast/icecast metadata)",
174                                                          FALSE,
175                                                          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
176
177     g_object_class_install_property(oklass,
178                                     PROP_IRADIO_NAME,
179                                     g_param_spec_string("iradio-name",
180                                                         "iradio-name",
181                                                         "Name of the stream",
182                                                         0,
183                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
184
185     g_object_class_install_property(oklass,
186                                     PROP_IRADIO_GENRE,
187                                     g_param_spec_string("iradio-genre",
188                                                         "iradio-genre",
189                                                         "Genre of the stream",
190                                                         0,
191                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
192                                                         
193     g_object_class_install_property(oklass,
194                                     PROP_IRADIO_URL,
195                                     g_param_spec_string("iradio-url",
196                                                         "iradio-url",
197                                                         "Homepage URL for radio stream",
198                                                         0,
199                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
200
201     g_object_class_install_property(oklass,
202                                     PROP_IRADIO_TITLE,
203                                     g_param_spec_string("iradio-title",
204                                                         "iradio-title",
205                                                         "Name of currently playing song",
206                                                         0,
207                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
208
209
210     /* Allows setting the uri using the 'location' property, which is used
211      * for example by gst_element_make_from_uri() */
212     g_object_class_install_property(oklass,
213                                     PROP_LOCATION,
214                                     g_param_spec_string("location",
215                                                         "location",
216                                                         "Location to read from",
217                                                         0,
218                                                         (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
219     eklass->change_state = webKitWebSrcChangeState;
220
221     g_type_class_add_private(klass, sizeof(WebKitWebSrcPrivate));
222 }
223
224 static void webkit_web_src_init(WebKitWebSrc* src,
225                                 WebKitWebSrcClass* gKlass)
226 {
227     GstPadTemplate* padTemplate = gst_static_pad_template_get(&srcTemplate);
228     GstPad* targetpad;
229     WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC_GET_PRIVATE(src);
230
231     src->priv = priv;
232
233     priv->client = new StreamingClient(src);
234
235     priv->srcpad = gst_ghost_pad_new_no_target_from_template("src",
236                                                              padTemplate);
237
238     gst_element_add_pad(GST_ELEMENT(src), priv->srcpad);
239     gst_pad_set_query_function(priv->srcpad, webKitWebSrcQuery);
240
241     priv->appsrc = GST_APP_SRC(gst_element_factory_make("appsrc", 0));
242     if (!priv->appsrc) {
243         GST_ERROR_OBJECT(src, "Failed to create appsrc");
244         return;
245     }
246
247     GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(priv->appsrc)->elementfactory);
248     priv->haveAppSrc27 = gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 27);
249
250     gst_bin_add(GST_BIN(src), GST_ELEMENT(priv->appsrc));
251
252     targetpad = gst_element_get_static_pad(GST_ELEMENT(priv->appsrc), "src");
253     gst_ghost_pad_set_target(GST_GHOST_PAD(priv->srcpad), targetpad);
254     gst_object_unref(targetpad);
255
256     gst_app_src_set_callbacks(priv->appsrc, &appsrcCallbacks, src, 0);
257     gst_app_src_set_emit_signals(priv->appsrc, FALSE);
258     gst_app_src_set_stream_type(priv->appsrc, GST_APP_STREAM_TYPE_SEEKABLE);
259
260     // 512k is a abitrary number but we should choose a value
261     // here to not pause/unpause the SoupMessage too often and
262     // to make sure there's always some data available for
263     // GStreamer to handle.
264     gst_app_src_set_max_bytes(priv->appsrc, 512 * 1024);
265
266     // Emit the need-data signal if the queue contains less
267     // than 20% of data. Without this the need-data signal
268     // is emitted when the queue is empty, we then dispatch
269     // the soup message unpausing to the main loop and from
270     // there unpause the soup message. This already takes
271     // quite some time and libsoup even needs some more time
272     // to actually provide data again. If we do all this
273     // already if the queue is 20% empty, it's much more
274     // likely that libsoup already provides new data before
275     // the queue is really empty.
276     // This might need tweaking for ports not using libsoup.
277     if (priv->haveAppSrc27)
278         g_object_set(priv->appsrc, "min-percent", 20, NULL);
279
280     webKitWebSrcStop(src, false);
281 }
282
283 static void webKitWebSrcFinalize(GObject* object)
284 {
285     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
286     WebKitWebSrcPrivate* priv = src->priv;
287
288     delete priv->client;
289
290     g_free(priv->uri);
291
292     GST_CALL_PARENT(G_OBJECT_CLASS, finalize, ((GObject* )(src)));
293 }
294
295 static void webKitWebSrcSetProperty(GObject* object, guint propID, const GValue* value, GParamSpec* pspec)
296 {
297     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
298     WebKitWebSrcPrivate* priv = src->priv;
299
300     switch (propID) {
301     case PROP_IRADIO_MODE:
302         priv->iradioMode = g_value_get_boolean(value);
303         break;
304     case PROP_LOCATION:
305         webKitWebSrcSetUri(reinterpret_cast<GstURIHandler*>(src), g_value_get_string(value));
306         break;
307     default:
308         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
309         break;
310     }
311 }
312
313 static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value, GParamSpec* pspec)
314 {
315     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
316     WebKitWebSrcPrivate* priv = src->priv;
317
318     switch (propID) {
319     case PROP_IRADIO_MODE:
320         g_value_set_boolean(value, priv->iradioMode);
321         break;
322     case PROP_IRADIO_NAME:
323         g_value_set_string(value, priv->iradioName);
324         break;
325     case PROP_IRADIO_GENRE:
326         g_value_set_string(value, priv->iradioGenre);
327         break;
328     case PROP_IRADIO_URL:
329         g_value_set_string(value, priv->iradioUrl);
330         break;
331     case PROP_IRADIO_TITLE:
332         g_value_set_string(value, priv->iradioTitle);
333         break;
334     case PROP_LOCATION:
335         g_value_set_string(value, webKitWebSrcGetUri(reinterpret_cast<GstURIHandler*>(src)));
336         break;
337     default:
338         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
339         break;
340     }
341 }
342
343
344 static void webKitWebSrcStop(WebKitWebSrc* src, bool seeking)
345 {
346     WebKitWebSrcPrivate* priv = src->priv;
347
348     if (priv->resourceHandle) {
349         priv->resourceHandle->cancel();
350         priv->resourceHandle.release();
351     }
352     priv->resourceHandle = 0;
353
354     if (priv->frame)
355         priv->frame.release();
356
357     GST_OBJECT_LOCK(src);
358     if (priv->needDataID)
359         g_source_remove(priv->needDataID);
360     priv->needDataID = 0;
361
362     if (priv->enoughDataID)
363         g_source_remove(priv->enoughDataID);
364     priv->enoughDataID = 0;
365
366     if (priv->seekID)
367         g_source_remove(priv->seekID);
368     priv->seekID = 0;
369
370     priv->paused = FALSE;
371     GST_OBJECT_UNLOCK(src);
372
373     g_free(priv->iradioName);
374     priv->iradioName = 0;
375
376     g_free(priv->iradioGenre);
377     priv->iradioGenre = 0;
378
379     g_free(priv->iradioUrl);
380     priv->iradioUrl = 0;
381
382     g_free(priv->iradioTitle);
383     priv->iradioTitle = 0;
384
385     if (priv->appsrc) {
386         gst_app_src_set_caps(priv->appsrc, 0);
387         if (!seeking)
388             gst_app_src_set_size(priv->appsrc, -1);
389     }
390
391     priv->offset = 0;
392     priv->seekable = FALSE;
393
394     if (!seeking) {
395         priv->size = 0;
396         priv->requestedOffset = 0;
397     }
398
399     GST_DEBUG_OBJECT(src, "Stopped request");
400 }
401
402 static bool webKitWebSrcStart(WebKitWebSrc* src)
403 {
404     WebKitWebSrcPrivate* priv = src->priv;
405
406     if (!priv->uri) {
407         GST_ERROR_OBJECT(src, "No URI provided");
408         return false;
409     }
410     
411     KURL url = KURL(KURL(), priv->uri);
412
413     ResourceRequest request(url);
414     request.setTargetType(ResourceRequestBase::TargetIsMedia);
415     request.setAllowCookies(true);
416
417     NetworkingContext* context = 0;
418     if (priv->frame) {
419         Document* document = priv->frame->document();
420         if (document)
421             request.setHTTPReferrer(document->documentURI());
422
423         FrameLoader* loader = priv->frame->loader();
424         if (loader) {
425             loader->addExtraFieldsToSubresourceRequest(request);
426             context = loader->networkingContext();
427         }
428     }
429
430     // Let Apple web servers know we want to access their nice movie trailers.
431     if (!g_ascii_strcasecmp("movies.apple.com", url.host().utf8().data())
432         || !g_ascii_strcasecmp("trailers.apple.com", url.host().utf8().data()))
433         request.setHTTPUserAgent("Quicktime/7.6.6");
434
435     if (priv->requestedOffset) {
436         GOwnPtr<gchar> val;
437
438         val.set(g_strdup_printf("bytes=%" G_GUINT64_FORMAT "-", priv->requestedOffset));
439         request.setHTTPHeaderField("Range", val.get());
440     }
441
442     if (priv->iradioMode)
443         request.setHTTPHeaderField("icy-metadata", "1");
444
445     // Needed to use DLNA streaming servers
446     request.setHTTPHeaderField("transferMode.dlna", "Streaming");
447
448     priv->resourceHandle = ResourceHandle::create(context, request, priv->client, false, false);
449     if (!priv->resourceHandle) {
450         GST_ERROR_OBJECT(src, "Failed to create ResourceHandle");
451         return false;
452     }
453
454     GST_DEBUG_OBJECT(src, "Started request");
455
456     return true;
457 }
458
459 static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStateChange transition)
460 {
461     GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
462     WebKitWebSrc* src = WEBKIT_WEB_SRC(element);
463     WebKitWebSrcPrivate* priv = src->priv;
464
465     switch (transition) {
466     case GST_STATE_CHANGE_NULL_TO_READY:
467         if (!priv->appsrc) {
468             gst_element_post_message(element,
469                                      gst_missing_element_message_new(element, "appsrc"));
470             GST_ELEMENT_ERROR(src, CORE, MISSING_PLUGIN, (0), ("no appsrc"));
471             return GST_STATE_CHANGE_FAILURE;
472         }
473         break;
474     default:
475         break;
476     }
477
478     ret = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition);
479     if (G_UNLIKELY(ret == GST_STATE_CHANGE_FAILURE)) {
480         GST_DEBUG_OBJECT(src, "State change failed");
481         return ret;
482     }
483
484     switch (transition) {
485     case GST_STATE_CHANGE_READY_TO_PAUSED:
486         GST_DEBUG_OBJECT(src, "READY->PAUSED");
487         if (!webKitWebSrcStart(src))
488             ret = GST_STATE_CHANGE_FAILURE;
489         break;
490     case GST_STATE_CHANGE_PAUSED_TO_READY:
491         GST_DEBUG_OBJECT(src, "PAUSED->READY");
492         webKitWebSrcStop(src, false);
493         break;
494     default:
495         break;
496     }
497
498     return ret;
499 }
500
501 static gboolean webKitWebSrcQuery(GstPad* pad, GstQuery* query)
502 {
503     WebKitWebSrc* src = WEBKIT_WEB_SRC(gst_pad_get_parent(pad));
504     gboolean result = FALSE;
505
506     switch (GST_QUERY_TYPE(query)) {
507     case GST_QUERY_DURATION:
508     {
509         GstFormat format;
510
511         gst_query_parse_duration(query, &format, NULL);
512
513         GST_DEBUG_OBJECT(src, "duration query in format %s", gst_format_get_name(format));
514         if ((format == GST_FORMAT_BYTES) && (src->priv->size > 0)) {
515             gst_query_set_duration(query, format, src->priv->size);
516             result = TRUE;
517         }
518         break;
519     }
520     default:
521         break;
522     }
523
524     if (!result)
525         result = gst_pad_query_default(pad, query);
526
527     gst_object_unref(src);
528     return result;
529 }
530
531 // uri handler interface
532
533 static GstURIType webKitWebSrcUriGetType(void)
534 {
535     return GST_URI_SRC;
536 }
537
538 static gchar** webKitWebSrcGetProtocols(void)
539 {
540     static gchar* protocols[] = {(gchar*) "http", (gchar*) "https", 0 };
541
542     return protocols;
543 }
544
545 static const gchar* webKitWebSrcGetUri(GstURIHandler* handler)
546 {
547     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
548     WebKitWebSrcPrivate* priv = src->priv;
549
550     return priv->uri;
551 }
552
553 static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri)
554 {
555     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
556     WebKitWebSrcPrivate* priv = src->priv;
557
558     if (GST_STATE(src) >= GST_STATE_PAUSED) {
559         GST_ERROR_OBJECT(src, "URI can only be set in states < PAUSED");
560         return FALSE;
561     }
562
563     g_free(priv->uri);
564     priv->uri = 0;
565
566     if (!uri)
567         return TRUE;
568
569     KURL url(KURL(), uri);
570
571     if (!url.isValid() || !url.protocolInHTTPFamily()) {
572         GST_ERROR_OBJECT(src, "Invalid URI '%s'", uri);
573         return FALSE;
574     }
575
576     priv->uri = g_strdup(url.string().utf8().data());
577     return TRUE;
578 }
579
580 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer ifaceData)
581 {
582     GstURIHandlerInterface* iface = (GstURIHandlerInterface *) gIface;
583
584     iface->get_type = webKitWebSrcUriGetType;
585     iface->get_protocols = webKitWebSrcGetProtocols;
586     iface->get_uri = webKitWebSrcGetUri;
587     iface->set_uri = webKitWebSrcSetUri;
588 }
589
590 // appsrc callbacks
591
592 static gboolean webKitWebSrcNeedDataMainCb(WebKitWebSrc* src)
593 {
594     WebKitWebSrcPrivate* priv = src->priv;
595
596     priv->resourceHandle->setDefersLoading(false);
597
598     GST_OBJECT_LOCK(src);
599     priv->paused = FALSE;
600     priv->needDataID = 0;
601     GST_OBJECT_UNLOCK(src);
602     return FALSE;
603 }
604
605 static void webKitWebSrcNeedDataCb(GstAppSrc* appsrc, guint length, gpointer userData)
606 {
607     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
608     WebKitWebSrcPrivate* priv = src->priv;
609
610     GST_DEBUG_OBJECT(src, "Need more data: %u", length);
611
612     GST_OBJECT_LOCK(src);
613     if (priv->needDataID || !priv->paused) {
614         GST_OBJECT_UNLOCK(src);
615         return;
616     }
617
618     priv->needDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcNeedDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
619     GST_OBJECT_UNLOCK(src);
620 }
621
622 static gboolean webKitWebSrcEnoughDataMainCb(WebKitWebSrc* src)
623 {
624     WebKitWebSrcPrivate* priv = src->priv;
625
626     priv->resourceHandle->setDefersLoading(true);
627
628     GST_OBJECT_LOCK(src);
629     priv->paused = TRUE;
630     priv->enoughDataID = 0;
631     GST_OBJECT_UNLOCK(src);
632
633     return FALSE;
634 }
635
636 static void webKitWebSrcEnoughDataCb(GstAppSrc* appsrc, gpointer userData)
637 {
638     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
639     WebKitWebSrcPrivate* priv = src->priv;
640
641     GST_DEBUG_OBJECT(src, "Have enough data");
642
643     GST_OBJECT_LOCK(src);
644     if (priv->enoughDataID || priv->paused) {
645         GST_OBJECT_UNLOCK(src);
646         return;
647     }
648
649     priv->enoughDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcEnoughDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
650     GST_OBJECT_UNLOCK(src);
651 }
652
653 static gboolean webKitWebSrcSeekMainCb(WebKitWebSrc* src)
654 {
655     webKitWebSrcStop(src, true);
656     webKitWebSrcStart(src);
657
658     return FALSE;
659 }
660
661 static gboolean webKitWebSrcSeekDataCb(GstAppSrc* appsrc, guint64 offset, gpointer userData)
662 {
663     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
664     WebKitWebSrcPrivate* priv = src->priv;
665
666     GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, offset);
667     if (offset == priv->offset)
668         return TRUE;
669
670     if (!priv->seekable)
671         return FALSE;
672     if (offset > priv->size)
673         return FALSE;
674
675     GST_DEBUG_OBJECT(src, "Doing range-request seek");
676     priv->requestedOffset = offset;
677
678     GST_OBJECT_LOCK(src);
679     if (priv->seekID)
680         g_source_remove(priv->seekID);
681     priv->seekID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcSeekMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
682     GST_OBJECT_UNLOCK(src);
683     
684     return TRUE;
685 }
686
687 void webKitWebSrcSetFrame(WebKitWebSrc* src, WebCore::Frame* frame)
688 {
689     WebKitWebSrcPrivate* priv = src->priv;
690
691     priv->frame = frame;
692 }
693
694 StreamingClient::StreamingClient(WebKitWebSrc* src) : m_src(src)
695 {
696
697 }
698
699 StreamingClient::~StreamingClient()
700 {
701
702 }
703
704 void StreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
705 {
706 }
707
708 void StreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
709 {
710     WebKitWebSrcPrivate* priv = m_src->priv;
711
712     GST_DEBUG_OBJECT(m_src, "Received response: %d", response.httpStatusCode());
713
714     // If we seeked we need 206 == PARTIAL_CONTENT
715     if (priv->requestedOffset && response.httpStatusCode() != 206) {
716         GST_ELEMENT_ERROR(m_src, RESOURCE, READ, (0), (0));
717         gst_app_src_end_of_stream(priv->appsrc);
718         webKitWebSrcStop(m_src, false);
719         return;
720     }
721
722     long long length = response.expectedContentLength();
723     if (length > 0) {
724         length += priv->requestedOffset;
725         gst_app_src_set_size(priv->appsrc, length);
726         if (!priv->haveAppSrc27) {
727             gst_segment_set_duration(&GST_BASE_SRC(priv->appsrc)->segment, GST_FORMAT_BYTES, length);
728             gst_element_post_message(GST_ELEMENT(priv->appsrc),
729                                      gst_message_new_duration(GST_OBJECT(priv->appsrc),
730                                                               GST_FORMAT_BYTES, length));
731         }
732     }
733
734     priv->size = length >= 0 ? length : 0;
735     priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField("Accept-Ranges").utf8().data());
736
737     // icecast stuff
738     String value = response.httpHeaderField("icy-metaint");
739     if (!value.isEmpty()) {
740         gchar* endptr = 0;
741         gint64 icyMetaInt = g_ascii_strtoll(value.utf8().data(), &endptr, 10);
742             
743         if (endptr && *endptr == '\0' && icyMetaInt > 0) {
744             GstCaps* caps = gst_caps_new_simple("application/x-icy", "metadata-interval", G_TYPE_INT, (gint) icyMetaInt, NULL);
745
746             gst_app_src_set_caps(priv->appsrc, caps);
747             gst_caps_unref(caps);
748         }
749     }
750
751     GstTagList* tags = gst_tag_list_new();
752     value = response.httpHeaderField("icy-name");
753     if (!value.isEmpty()) {
754         g_free(priv->iradioName);
755         priv->iradioName = g_strdup(value.utf8().data());
756         g_object_notify(G_OBJECT(m_src), "iradio-name");
757         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
758     }
759     value = response.httpHeaderField("icy-genre");
760     if (!value.isEmpty()) {
761         g_free(priv->iradioGenre);
762         priv->iradioGenre = g_strdup(value.utf8().data());
763         g_object_notify(G_OBJECT(m_src), "iradio-genre");
764         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
765     }
766     value = response.httpHeaderField("icy-url");
767     if (!value.isEmpty()) {
768         g_free(priv->iradioUrl);
769         priv->iradioUrl = g_strdup(value.utf8().data());
770         g_object_notify(G_OBJECT(m_src), "iradio-url");
771         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
772     }
773     value = response.httpHeaderField("icy-title");
774     if (!value.isEmpty()) {
775         g_free(priv->iradioTitle);
776         priv->iradioTitle = g_strdup(value.utf8().data());
777         g_object_notify(G_OBJECT(m_src), "iradio-title");
778         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
779     }
780
781     if (gst_tag_list_is_empty(tags))
782         gst_tag_list_free(tags);
783     else
784         gst_element_found_tags_for_pad(GST_ELEMENT(m_src), m_src->priv->srcpad, tags);
785 }
786
787 void StreamingClient::didReceiveData(ResourceHandle* handle, const char* data, int length, int lengthReceived)
788 {
789     WebKitWebSrcPrivate* priv = m_src->priv;
790
791     GST_LOG_OBJECT(m_src, "Have %d bytes of data", length);
792
793     if (priv->seekID || handle != priv->resourceHandle) {
794         GST_DEBUG_OBJECT(m_src, "Seek in progress, ignoring data");
795         return;
796     }
797
798     GstBuffer* buffer = gst_buffer_new_and_alloc(length);
799
800     memcpy(GST_BUFFER_DATA(buffer), data, length);
801     GST_BUFFER_OFFSET(buffer) = priv->offset;
802     priv->offset += length;
803     GST_BUFFER_OFFSET_END(buffer) = priv->offset;
804
805     GstFlowReturn ret = gst_app_src_push_buffer(priv->appsrc, buffer);
806     if (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED)
807         GST_ELEMENT_ERROR(m_src, CORE, FAILED, (0), (0));
808 }
809
810 void StreamingClient::didFinishLoading(ResourceHandle*, double)
811 {
812     WebKitWebSrcPrivate* priv = m_src->priv;
813
814     GST_DEBUG_OBJECT(m_src, "Have EOS");
815
816     if (!priv->seekID)
817         gst_app_src_end_of_stream(m_src->priv->appsrc);
818 }
819
820 void StreamingClient::didFail(ResourceHandle*, const ResourceError& error)
821 {
822     GST_ERROR_OBJECT(m_src, "Have failure: %s", error.localizedDescription().utf8().data());
823     GST_ELEMENT_ERROR(m_src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
824     gst_app_src_end_of_stream(m_src->priv->appsrc);
825 }
826
827 void StreamingClient::wasBlocked(ResourceHandle*)
828 {
829     GST_ERROR_OBJECT(m_src, "Request was blocked");
830     GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", m_src->priv->uri), (0));
831 }
832
833 void StreamingClient::cannotShowURL(ResourceHandle*)
834 {
835     GST_ERROR_OBJECT(m_src, "Cannot show URL");
836     GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", m_src->priv->uri), (0));
837 }
838
839 #endif // USE(GSTREAMER)
840