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     case GST_QUERY_URI:
521     {
522         gst_query_set_uri(query, src->priv->uri);
523         result = TRUE;
524         break;
525     }
526     default:
527         break;
528     }
529
530     if (!result)
531         result = gst_pad_query_default(pad, query);
532
533     gst_object_unref(src);
534     return result;
535 }
536
537 // uri handler interface
538
539 static GstURIType webKitWebSrcUriGetType(void)
540 {
541     return GST_URI_SRC;
542 }
543
544 static gchar** webKitWebSrcGetProtocols(void)
545 {
546     static gchar* protocols[] = {(gchar*) "http", (gchar*) "https", 0 };
547
548     return protocols;
549 }
550
551 static const gchar* webKitWebSrcGetUri(GstURIHandler* handler)
552 {
553     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
554     WebKitWebSrcPrivate* priv = src->priv;
555
556     return priv->uri;
557 }
558
559 static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri)
560 {
561     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
562     WebKitWebSrcPrivate* priv = src->priv;
563
564     if (GST_STATE(src) >= GST_STATE_PAUSED) {
565         GST_ERROR_OBJECT(src, "URI can only be set in states < PAUSED");
566         return FALSE;
567     }
568
569     g_free(priv->uri);
570     priv->uri = 0;
571
572     if (!uri)
573         return TRUE;
574
575     KURL url(KURL(), uri);
576
577     if (!url.isValid() || !url.protocolInHTTPFamily()) {
578         GST_ERROR_OBJECT(src, "Invalid URI '%s'", uri);
579         return FALSE;
580     }
581
582     priv->uri = g_strdup(url.string().utf8().data());
583     return TRUE;
584 }
585
586 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer ifaceData)
587 {
588     GstURIHandlerInterface* iface = (GstURIHandlerInterface *) gIface;
589
590     iface->get_type = webKitWebSrcUriGetType;
591     iface->get_protocols = webKitWebSrcGetProtocols;
592     iface->get_uri = webKitWebSrcGetUri;
593     iface->set_uri = webKitWebSrcSetUri;
594 }
595
596 // appsrc callbacks
597
598 static gboolean webKitWebSrcNeedDataMainCb(WebKitWebSrc* src)
599 {
600     WebKitWebSrcPrivate* priv = src->priv;
601
602     priv->resourceHandle->setDefersLoading(false);
603
604     GST_OBJECT_LOCK(src);
605     priv->paused = FALSE;
606     priv->needDataID = 0;
607     GST_OBJECT_UNLOCK(src);
608     return FALSE;
609 }
610
611 static void webKitWebSrcNeedDataCb(GstAppSrc* appsrc, guint length, gpointer userData)
612 {
613     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
614     WebKitWebSrcPrivate* priv = src->priv;
615
616     GST_DEBUG_OBJECT(src, "Need more data: %u", length);
617
618     GST_OBJECT_LOCK(src);
619     if (priv->needDataID || !priv->paused) {
620         GST_OBJECT_UNLOCK(src);
621         return;
622     }
623
624     priv->needDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcNeedDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
625     GST_OBJECT_UNLOCK(src);
626 }
627
628 static gboolean webKitWebSrcEnoughDataMainCb(WebKitWebSrc* src)
629 {
630     WebKitWebSrcPrivate* priv = src->priv;
631
632     priv->resourceHandle->setDefersLoading(true);
633
634     GST_OBJECT_LOCK(src);
635     priv->paused = TRUE;
636     priv->enoughDataID = 0;
637     GST_OBJECT_UNLOCK(src);
638
639     return FALSE;
640 }
641
642 static void webKitWebSrcEnoughDataCb(GstAppSrc* appsrc, gpointer userData)
643 {
644     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
645     WebKitWebSrcPrivate* priv = src->priv;
646
647     GST_DEBUG_OBJECT(src, "Have enough data");
648
649     GST_OBJECT_LOCK(src);
650     if (priv->enoughDataID || priv->paused) {
651         GST_OBJECT_UNLOCK(src);
652         return;
653     }
654
655     priv->enoughDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcEnoughDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
656     GST_OBJECT_UNLOCK(src);
657 }
658
659 static gboolean webKitWebSrcSeekMainCb(WebKitWebSrc* src)
660 {
661     webKitWebSrcStop(src, true);
662     webKitWebSrcStart(src);
663
664     return FALSE;
665 }
666
667 static gboolean webKitWebSrcSeekDataCb(GstAppSrc* appsrc, guint64 offset, gpointer userData)
668 {
669     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
670     WebKitWebSrcPrivate* priv = src->priv;
671
672     GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, offset);
673     if (offset == priv->offset)
674         return TRUE;
675
676     if (!priv->seekable)
677         return FALSE;
678     if (offset > priv->size)
679         return FALSE;
680
681     GST_DEBUG_OBJECT(src, "Doing range-request seek");
682     priv->requestedOffset = offset;
683
684     GST_OBJECT_LOCK(src);
685     if (priv->seekID)
686         g_source_remove(priv->seekID);
687     priv->seekID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcSeekMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
688     GST_OBJECT_UNLOCK(src);
689     
690     return TRUE;
691 }
692
693 void webKitWebSrcSetFrame(WebKitWebSrc* src, WebCore::Frame* frame)
694 {
695     WebKitWebSrcPrivate* priv = src->priv;
696
697     priv->frame = frame;
698 }
699
700 StreamingClient::StreamingClient(WebKitWebSrc* src) : m_src(src)
701 {
702
703 }
704
705 StreamingClient::~StreamingClient()
706 {
707
708 }
709
710 void StreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
711 {
712 }
713
714 void StreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
715 {
716     WebKitWebSrcPrivate* priv = m_src->priv;
717
718     GST_DEBUG_OBJECT(m_src, "Received response: %d", response.httpStatusCode());
719
720     // If we seeked we need 206 == PARTIAL_CONTENT
721     if (priv->requestedOffset && response.httpStatusCode() != 206) {
722         GST_ELEMENT_ERROR(m_src, RESOURCE, READ, (0), (0));
723         gst_app_src_end_of_stream(priv->appsrc);
724         webKitWebSrcStop(m_src, false);
725         return;
726     }
727
728     long long length = response.expectedContentLength();
729     if (length > 0) {
730         length += priv->requestedOffset;
731         gst_app_src_set_size(priv->appsrc, length);
732         if (!priv->haveAppSrc27) {
733             gst_segment_set_duration(&GST_BASE_SRC(priv->appsrc)->segment, GST_FORMAT_BYTES, length);
734             gst_element_post_message(GST_ELEMENT(priv->appsrc),
735                                      gst_message_new_duration(GST_OBJECT(priv->appsrc),
736                                                               GST_FORMAT_BYTES, length));
737         }
738     }
739
740     priv->size = length >= 0 ? length : 0;
741     priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField("Accept-Ranges").utf8().data());
742
743     // icecast stuff
744     String value = response.httpHeaderField("icy-metaint");
745     if (!value.isEmpty()) {
746         gchar* endptr = 0;
747         gint64 icyMetaInt = g_ascii_strtoll(value.utf8().data(), &endptr, 10);
748             
749         if (endptr && *endptr == '\0' && icyMetaInt > 0) {
750             GstCaps* caps = gst_caps_new_simple("application/x-icy", "metadata-interval", G_TYPE_INT, (gint) icyMetaInt, NULL);
751
752             gst_app_src_set_caps(priv->appsrc, caps);
753             gst_caps_unref(caps);
754         }
755     }
756
757     GstTagList* tags = gst_tag_list_new();
758     value = response.httpHeaderField("icy-name");
759     if (!value.isEmpty()) {
760         g_free(priv->iradioName);
761         priv->iradioName = g_strdup(value.utf8().data());
762         g_object_notify(G_OBJECT(m_src), "iradio-name");
763         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
764     }
765     value = response.httpHeaderField("icy-genre");
766     if (!value.isEmpty()) {
767         g_free(priv->iradioGenre);
768         priv->iradioGenre = g_strdup(value.utf8().data());
769         g_object_notify(G_OBJECT(m_src), "iradio-genre");
770         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
771     }
772     value = response.httpHeaderField("icy-url");
773     if (!value.isEmpty()) {
774         g_free(priv->iradioUrl);
775         priv->iradioUrl = g_strdup(value.utf8().data());
776         g_object_notify(G_OBJECT(m_src), "iradio-url");
777         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
778     }
779     value = response.httpHeaderField("icy-title");
780     if (!value.isEmpty()) {
781         g_free(priv->iradioTitle);
782         priv->iradioTitle = g_strdup(value.utf8().data());
783         g_object_notify(G_OBJECT(m_src), "iradio-title");
784         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
785     }
786
787     if (gst_tag_list_is_empty(tags))
788         gst_tag_list_free(tags);
789     else
790         gst_element_found_tags_for_pad(GST_ELEMENT(m_src), m_src->priv->srcpad, tags);
791 }
792
793 void StreamingClient::didReceiveData(ResourceHandle* handle, const char* data, int length, int lengthReceived)
794 {
795     WebKitWebSrcPrivate* priv = m_src->priv;
796
797     GST_LOG_OBJECT(m_src, "Have %d bytes of data", length);
798
799     if (priv->seekID || handle != priv->resourceHandle) {
800         GST_DEBUG_OBJECT(m_src, "Seek in progress, ignoring data");
801         return;
802     }
803
804     GstBuffer* buffer = gst_buffer_new_and_alloc(length);
805
806     memcpy(GST_BUFFER_DATA(buffer), data, length);
807     GST_BUFFER_OFFSET(buffer) = priv->offset;
808     priv->offset += length;
809     GST_BUFFER_OFFSET_END(buffer) = priv->offset;
810
811     GstFlowReturn ret = gst_app_src_push_buffer(priv->appsrc, buffer);
812     if (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED)
813         GST_ELEMENT_ERROR(m_src, CORE, FAILED, (0), (0));
814 }
815
816 void StreamingClient::didFinishLoading(ResourceHandle*, double)
817 {
818     WebKitWebSrcPrivate* priv = m_src->priv;
819
820     GST_DEBUG_OBJECT(m_src, "Have EOS");
821
822     if (!priv->seekID)
823         gst_app_src_end_of_stream(m_src->priv->appsrc);
824 }
825
826 void StreamingClient::didFail(ResourceHandle*, const ResourceError& error)
827 {
828     GST_ERROR_OBJECT(m_src, "Have failure: %s", error.localizedDescription().utf8().data());
829     GST_ELEMENT_ERROR(m_src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
830     gst_app_src_end_of_stream(m_src->priv->appsrc);
831 }
832
833 void StreamingClient::wasBlocked(ResourceHandle*)
834 {
835     GST_ERROR_OBJECT(m_src, "Request was blocked");
836     GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", m_src->priv->uri), (0));
837 }
838
839 void StreamingClient::cannotShowURL(ResourceHandle*)
840 {
841     GST_ERROR_OBJECT(m_src, "Cannot show URL");
842     GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", m_src->priv->uri), (0));
843 }
844
845 #endif // USE(GSTREAMER)
846