[GStreamer] Lockup when playing Icecast radio
[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  *  Copyright (C) 2013 Collabora Ltd.
4  *
5  *  This library is free software; you can redistribute it and/or
6  *  modify it under the terms of the GNU Lesser General Public
7  *  License as published by the Free Software Foundation; either
8  *  version 2 of the License, or (at your option) any later version.
9  *
10  *  This library 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 GNU
13  *  Lesser General Public License for more details.
14  *
15  *  You should have received a copy of the GNU Lesser General Public
16  *  License along with this library; if not, write to the Free Software
17  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19
20 #include "config.h"
21 #include "WebKitWebSourceGStreamer.h"
22
23 #if ENABLE(VIDEO) && USE(GSTREAMER)
24
25 #include "CachedRawResource.h"
26 #include "CachedRawResourceClient.h"
27 #include "CachedResourceHandle.h"
28 #include "CachedResourceLoader.h"
29 #include "CachedResourceRequest.h"
30 #include "GRefPtrGStreamer.h"
31 #include "GStreamerUtilities.h"
32 #include "MediaPlayer.h"
33 #include "NotImplemented.h"
34 #include "ResourceHandle.h"
35 #include "ResourceHandleClient.h"
36 #include "ResourceRequest.h"
37 #include "ResourceResponse.h"
38 #include "SharedBuffer.h"
39 #include <gst/app/gstappsrc.h>
40 #include <gst/gst.h>
41 #include <gst/pbutils/missing-plugins.h>
42 #include <wtf/Noncopyable.h>
43 #include <wtf/gobject/GMutexLocker.h>
44 #include <wtf/gobject/GRefPtr.h>
45 #include <wtf/gobject/GUniquePtr.h>
46 #include <wtf/text/CString.h>
47
48 using namespace WebCore;
49
50 class StreamingClient {
51     public:
52         StreamingClient(WebKitWebSrc*);
53         virtual ~StreamingClient();
54
55         virtual bool loadFailed() const = 0;
56         virtual void setDefersLoading(bool) = 0;
57
58     protected:
59         char* createReadBuffer(size_t requestedSize, size_t& actualSize);
60         void handleResponseReceived(const ResourceResponse&);
61         void handleDataReceived(const char*, int);
62         void handleNotifyFinished();
63
64         GRefPtr<GstElement> m_src;
65 };
66
67 class CachedResourceStreamingClient : public CachedRawResourceClient, public StreamingClient {
68     WTF_MAKE_NONCOPYABLE(CachedResourceStreamingClient); WTF_MAKE_FAST_ALLOCATED;
69     public:
70         CachedResourceStreamingClient(WebKitWebSrc*, CachedResourceLoader*, const ResourceRequest&);
71         virtual ~CachedResourceStreamingClient();
72
73         // StreamingClient virtual methods.
74         virtual bool loadFailed() const;
75         virtual void setDefersLoading(bool);
76
77     private:
78         // CachedResourceClient virtual methods.
79         virtual char* getOrCreateReadBuffer(CachedResource*, size_t requestedSize, size_t& actualSize);
80         virtual void responseReceived(CachedResource*, const ResourceResponse&);
81         virtual void dataReceived(CachedResource*, const char*, int);
82         virtual void notifyFinished(CachedResource*);
83
84         CachedResourceHandle<CachedRawResource> m_resource;
85 };
86
87 class ResourceHandleStreamingClient : public ResourceHandleClient, public StreamingClient {
88     WTF_MAKE_NONCOPYABLE(ResourceHandleStreamingClient); WTF_MAKE_FAST_ALLOCATED;
89     public:
90         ResourceHandleStreamingClient(WebKitWebSrc*, const ResourceRequest&);
91         virtual ~ResourceHandleStreamingClient();
92
93         // StreamingClient virtual methods.
94         virtual bool loadFailed() const;
95         virtual void setDefersLoading(bool);
96
97     private:
98         // ResourceHandleClient virtual methods.
99         virtual char* getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize);
100         virtual void willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&);
101         virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
102         virtual void didReceiveData(ResourceHandle*, const char*, unsigned, int);
103         virtual void didReceiveBuffer(ResourceHandle*, PassRefPtr<SharedBuffer>, int encodedLength);
104         virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
105         virtual void didFail(ResourceHandle*, const ResourceError&);
106         virtual void wasBlocked(ResourceHandle*);
107         virtual void cannotShowURL(ResourceHandle*);
108
109         RefPtr<ResourceHandle> m_resource;
110 };
111
112 #define WEBKIT_WEB_SRC_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), WEBKIT_TYPE_WEB_SRC, WebKitWebSrcPrivate))
113 struct _WebKitWebSrcPrivate {
114     GstAppSrc* appsrc;
115     GstPad* srcpad;
116     gchar* uri;
117
118     WebCore::MediaPlayer* player;
119
120     StreamingClient* client;
121
122     guint64 offset;
123     guint64 size;
124     gboolean seekable;
125     gboolean paused;
126
127     guint64 requestedOffset;
128
129     guint startID;
130     guint stopID;
131     guint needDataID;
132     guint enoughDataID;
133     guint seekID;
134
135     GRefPtr<GstBuffer> buffer;
136
137     // icecast stuff
138     gboolean iradioMode;
139     gchar* iradioName;
140     gchar* iradioGenre;
141     gchar* iradioUrl;
142     gchar* iradioTitle;
143 };
144
145 enum {
146     PROP_IRADIO_MODE = 1,
147     PROP_IRADIO_NAME,
148     PROP_IRADIO_GENRE,
149     PROP_IRADIO_URL,
150     PROP_IRADIO_TITLE,
151     PROP_LOCATION
152 };
153
154 static GstStaticPadTemplate srcTemplate = GST_STATIC_PAD_TEMPLATE("src",
155                                                                   GST_PAD_SRC,
156                                                                   GST_PAD_ALWAYS,
157                                                                   GST_STATIC_CAPS_ANY);
158
159 GST_DEBUG_CATEGORY_STATIC(webkit_web_src_debug);
160 #define GST_CAT_DEFAULT webkit_web_src_debug
161
162 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer ifaceData);
163
164 static void webKitWebSrcDispose(GObject*);
165 static void webKitWebSrcFinalize(GObject*);
166 static void webKitWebSrcSetProperty(GObject*, guint propertyID, const GValue*, GParamSpec*);
167 static void webKitWebSrcGetProperty(GObject*, guint propertyID, GValue*, GParamSpec*);
168 static GstStateChangeReturn webKitWebSrcChangeState(GstElement*, GstStateChange);
169
170 static gboolean webKitWebSrcQueryWithParent(GstPad*, GstObject*, GstQuery*);
171
172 static void webKitWebSrcNeedDataCb(GstAppSrc*, guint length, gpointer userData);
173 static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData);
174 static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData);
175
176 static GstAppSrcCallbacks appsrcCallbacks = {
177     webKitWebSrcNeedDataCb,
178     webKitWebSrcEnoughDataCb,
179     webKitWebSrcSeekDataCb,
180     { 0 }
181 };
182
183 #define webkit_web_src_parent_class parent_class
184 // We split this out into another macro to avoid a check-webkit-style error.
185 #define WEBKIT_WEB_SRC_CATEGORY_INIT GST_DEBUG_CATEGORY_INIT(webkit_web_src_debug, "webkitwebsrc", 0, "websrc element");
186 G_DEFINE_TYPE_WITH_CODE(WebKitWebSrc, webkit_web_src, GST_TYPE_BIN,
187                          G_IMPLEMENT_INTERFACE(GST_TYPE_URI_HANDLER, webKitWebSrcUriHandlerInit);
188                          WEBKIT_WEB_SRC_CATEGORY_INIT);
189
190 static void webkit_web_src_class_init(WebKitWebSrcClass* klass)
191 {
192     GObjectClass* oklass = G_OBJECT_CLASS(klass);
193     GstElementClass* eklass = GST_ELEMENT_CLASS(klass);
194
195     oklass->dispose = webKitWebSrcDispose;
196     oklass->finalize = webKitWebSrcFinalize;
197     oklass->set_property = webKitWebSrcSetProperty;
198     oklass->get_property = webKitWebSrcGetProperty;
199
200     gst_element_class_add_pad_template(eklass,
201                                        gst_static_pad_template_get(&srcTemplate));
202     gst_element_class_set_metadata(eklass, "WebKit Web source element", "Source", "Handles HTTP/HTTPS uris",
203                                "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
204
205     // icecast stuff
206     g_object_class_install_property(oklass,
207                                     PROP_IRADIO_MODE,
208                                     g_param_spec_boolean("iradio-mode",
209                                                          "iradio-mode",
210                                                          "Enable internet radio mode (extraction of shoutcast/icecast metadata)",
211                                                          FALSE,
212                                                          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
213
214     g_object_class_install_property(oklass,
215                                     PROP_IRADIO_NAME,
216                                     g_param_spec_string("iradio-name",
217                                                         "iradio-name",
218                                                         "Name of the stream",
219                                                         0,
220                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
221
222     g_object_class_install_property(oklass,
223                                     PROP_IRADIO_GENRE,
224                                     g_param_spec_string("iradio-genre",
225                                                         "iradio-genre",
226                                                         "Genre of the stream",
227                                                         0,
228                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
229
230     g_object_class_install_property(oklass,
231                                     PROP_IRADIO_URL,
232                                     g_param_spec_string("iradio-url",
233                                                         "iradio-url",
234                                                         "Homepage URL for radio stream",
235                                                         0,
236                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
237
238     g_object_class_install_property(oklass,
239                                     PROP_IRADIO_TITLE,
240                                     g_param_spec_string("iradio-title",
241                                                         "iradio-title",
242                                                         "Name of currently playing song",
243                                                         0,
244                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
245
246
247     /* Allows setting the uri using the 'location' property, which is used
248      * for example by gst_element_make_from_uri() */
249     g_object_class_install_property(oklass,
250                                     PROP_LOCATION,
251                                     g_param_spec_string("location",
252                                                         "location",
253                                                         "Location to read from",
254                                                         0,
255                                                         (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
256     eklass->change_state = webKitWebSrcChangeState;
257
258     g_type_class_add_private(klass, sizeof(WebKitWebSrcPrivate));
259 }
260
261 static void webkit_web_src_init(WebKitWebSrc* src)
262 {
263     WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC_GET_PRIVATE(src);
264
265     src->priv = priv;
266
267     priv->appsrc = GST_APP_SRC(gst_element_factory_make("appsrc", 0));
268     if (!priv->appsrc) {
269         GST_ERROR_OBJECT(src, "Failed to create appsrc");
270         return;
271     }
272
273     gst_bin_add(GST_BIN(src), GST_ELEMENT(priv->appsrc));
274
275
276     GRefPtr<GstPad> targetPad = adoptGRef(gst_element_get_static_pad(GST_ELEMENT(priv->appsrc), "src"));
277     priv->srcpad = webkitGstGhostPadFromStaticTemplate(&srcTemplate, "src", targetPad.get());
278
279     gst_element_add_pad(GST_ELEMENT(src), priv->srcpad);
280
281     GST_OBJECT_FLAG_SET(priv->srcpad, GST_PAD_FLAG_NEED_PARENT);
282     gst_pad_set_query_function(priv->srcpad, webKitWebSrcQueryWithParent);
283
284     gst_app_src_set_callbacks(priv->appsrc, &appsrcCallbacks, src, 0);
285     gst_app_src_set_emit_signals(priv->appsrc, FALSE);
286     gst_app_src_set_stream_type(priv->appsrc, GST_APP_STREAM_TYPE_SEEKABLE);
287
288     // 512k is a abitrary number but we should choose a value
289     // here to not pause/unpause the SoupMessage too often and
290     // to make sure there's always some data available for
291     // GStreamer to handle.
292     gst_app_src_set_max_bytes(priv->appsrc, 512 * 1024);
293
294     // Emit the need-data signal if the queue contains less
295     // than 20% of data. Without this the need-data signal
296     // is emitted when the queue is empty, we then dispatch
297     // the soup message unpausing to the main loop and from
298     // there unpause the soup message. This already takes
299     // quite some time and libsoup even needs some more time
300     // to actually provide data again. If we do all this
301     // already if the queue is 20% empty, it's much more
302     // likely that libsoup already provides new data before
303     // the queue is really empty.
304     // This might need tweaking for ports not using libsoup.
305     g_object_set(priv->appsrc, "min-percent", 20, NULL);
306
307     gst_app_src_set_caps(priv->appsrc, 0);
308     gst_app_src_set_size(priv->appsrc, -1);
309 }
310
311 static void webKitWebSrcDispose(GObject* object)
312 {
313     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
314     WebKitWebSrcPrivate* priv = src->priv;
315
316     priv->player = 0;
317
318     GST_CALL_PARENT(G_OBJECT_CLASS, dispose, (object));
319 }
320
321 static void webKitWebSrcFinalize(GObject* object)
322 {
323     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
324     WebKitWebSrcPrivate* priv = src->priv;
325
326     g_free(priv->uri);
327
328     GST_CALL_PARENT(G_OBJECT_CLASS, finalize, (object));
329 }
330
331 static void webKitWebSrcSetProperty(GObject* object, guint propID, const GValue* value, GParamSpec* pspec)
332 {
333     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
334     WebKitWebSrcPrivate* priv = src->priv;
335
336     switch (propID) {
337     case PROP_IRADIO_MODE: {
338         GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
339         priv->iradioMode = g_value_get_boolean(value);
340         break;
341     }
342     case PROP_LOCATION:
343         gst_uri_handler_set_uri(reinterpret_cast<GstURIHandler*>(src), g_value_get_string(value), 0);
344         break;
345     default:
346         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
347         break;
348     }
349 }
350
351 static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value, GParamSpec* pspec)
352 {
353     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
354     WebKitWebSrcPrivate* priv = src->priv;
355
356     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
357     switch (propID) {
358     case PROP_IRADIO_MODE:
359         g_value_set_boolean(value, priv->iradioMode);
360         break;
361     case PROP_IRADIO_NAME:
362         g_value_set_string(value, priv->iradioName);
363         break;
364     case PROP_IRADIO_GENRE:
365         g_value_set_string(value, priv->iradioGenre);
366         break;
367     case PROP_IRADIO_URL:
368         g_value_set_string(value, priv->iradioUrl);
369         break;
370     case PROP_IRADIO_TITLE:
371         g_value_set_string(value, priv->iradioTitle);
372         break;
373     case PROP_LOCATION:
374         g_value_set_string(value, priv->uri);
375         break;
376     default:
377         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
378         break;
379     }
380 }
381
382 static void removeTimeoutSources(WebKitWebSrc* src)
383 {
384     WebKitWebSrcPrivate* priv = src->priv;
385
386     if (priv->startID)
387         g_source_remove(priv->startID);
388     priv->startID = 0;
389
390     if (priv->needDataID)
391         g_source_remove(priv->needDataID);
392     priv->needDataID = 0;
393
394     if (priv->enoughDataID)
395         g_source_remove(priv->enoughDataID);
396     priv->enoughDataID = 0;
397
398     if (priv->seekID)
399         g_source_remove(priv->seekID);
400     priv->seekID = 0;
401 }
402
403 static gboolean webKitWebSrcStop(WebKitWebSrc* src)
404 {
405     WebKitWebSrcPrivate* priv = src->priv;
406
407     ASSERT(isMainThread());
408
409     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
410
411     bool seeking = priv->seekID;
412
413     removeTimeoutSources(src);
414     priv->stopID = 0;
415
416     if (priv->client) {
417         delete priv->client;
418         priv->client = 0;
419     }
420
421     if (priv->buffer) {
422         unmapGstBuffer(priv->buffer.get());
423         priv->buffer.clear();
424     }
425
426     priv->paused = FALSE;
427
428     g_free(priv->iradioName);
429     priv->iradioName = 0;
430
431     g_free(priv->iradioGenre);
432     priv->iradioGenre = 0;
433
434     g_free(priv->iradioUrl);
435     priv->iradioUrl = 0;
436
437     g_free(priv->iradioTitle);
438     priv->iradioTitle = 0;
439
440     priv->offset = 0;
441     priv->seekable = FALSE;
442
443     if (!seeking) {
444         priv->size = 0;
445         priv->requestedOffset = 0;
446         priv->player = 0;
447     }
448
449     locker.unlock();
450
451     if (priv->appsrc) {
452         gst_app_src_set_caps(priv->appsrc, 0);
453         if (!seeking)
454             gst_app_src_set_size(priv->appsrc, -1);
455     }
456
457     GST_DEBUG_OBJECT(src, "Stopped request");
458
459     return FALSE;
460 }
461
462 static gboolean webKitWebSrcStart(WebKitWebSrc* src)
463 {
464     WebKitWebSrcPrivate* priv = src->priv;
465
466     ASSERT(isMainThread());
467
468     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
469
470     priv->startID = 0;
471
472     if (!priv->uri) {
473         GST_ERROR_OBJECT(src, "No URI provided");
474         locker.unlock();
475         webKitWebSrcStop(src);
476         return FALSE;
477     }
478
479     ASSERT(!priv->client);
480
481     URL url = URL(URL(), priv->uri);
482
483     ResourceRequest request(url);
484     request.setAllowCookies(true);
485
486     if (priv->player)
487         request.setHTTPReferrer(priv->player->referrer());
488
489 #if USE(SOUP)
490     // Let's disable HTTP Accept-Encoding here as we don't want the received response to be
491     // encoded in any way as we need to rely on the proper size of the returned data on
492     // didReceiveResponse.
493     // If Accept-Encoding is used, the server may send the data in encoded format and
494     // request.expectedContentLength() will have the "wrong" size (the size of the
495     // compressed data), even though the data received in didReceiveData is uncompressed.
496     request.setAcceptEncoding(false);
497 #endif
498
499     // Let Apple web servers know we want to access their nice movie trailers.
500     if (!g_ascii_strcasecmp("movies.apple.com", url.host().utf8().data())
501         || !g_ascii_strcasecmp("trailers.apple.com", url.host().utf8().data()))
502         request.setHTTPUserAgent("Quicktime/7.6.6");
503
504     if (priv->requestedOffset) {
505         GUniquePtr<gchar> val(g_strdup_printf("bytes=%" G_GUINT64_FORMAT "-", priv->requestedOffset));
506         request.setHTTPHeaderField("Range", val.get());
507     }
508     priv->offset = priv->requestedOffset;
509
510     if (priv->iradioMode)
511         request.setHTTPHeaderField("icy-metadata", "1");
512
513     // Needed to use DLNA streaming servers
514     request.setHTTPHeaderField("transferMode.dlna", "Streaming");
515
516     if (priv->player) {
517         if (CachedResourceLoader* loader = priv->player->cachedResourceLoader())
518             priv->client = new CachedResourceStreamingClient(src, loader, request);
519     }
520
521     if (!priv->client)
522         priv->client = new ResourceHandleStreamingClient(src, request);
523
524     if (!priv->client || priv->client->loadFailed()) {
525         GST_ERROR_OBJECT(src, "Failed to setup streaming client");
526         if (priv->client) {
527             delete priv->client;
528             priv->client = 0;
529         }
530         locker.unlock();
531         webKitWebSrcStop(src);
532         return FALSE;
533     }
534     GST_DEBUG_OBJECT(src, "Started request");
535     return FALSE;
536 }
537
538 static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStateChange transition)
539 {
540     GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
541     WebKitWebSrc* src = WEBKIT_WEB_SRC(element);
542     WebKitWebSrcPrivate* priv = src->priv;
543
544     switch (transition) {
545     case GST_STATE_CHANGE_NULL_TO_READY:
546         if (!priv->appsrc) {
547             gst_element_post_message(element,
548                                      gst_missing_element_message_new(element, "appsrc"));
549             GST_ELEMENT_ERROR(src, CORE, MISSING_PLUGIN, (0), ("no appsrc"));
550             return GST_STATE_CHANGE_FAILURE;
551         }
552         break;
553     default:
554         break;
555     }
556
557     ret = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition);
558     if (G_UNLIKELY(ret == GST_STATE_CHANGE_FAILURE)) {
559         GST_DEBUG_OBJECT(src, "State change failed");
560         return ret;
561     }
562
563     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
564     switch (transition) {
565     case GST_STATE_CHANGE_READY_TO_PAUSED:
566         GST_DEBUG_OBJECT(src, "READY->PAUSED");
567         priv->startID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcStart, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
568         break;
569     case GST_STATE_CHANGE_PAUSED_TO_READY:
570         GST_DEBUG_OBJECT(src, "PAUSED->READY");
571         // cancel pending sources
572         removeTimeoutSources(src);
573         priv->stopID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcStop, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
574         break;
575     default:
576         break;
577     }
578
579     return ret;
580 }
581
582 static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQuery* query)
583 {
584     WebKitWebSrc* src = WEBKIT_WEB_SRC(GST_ELEMENT(parent));
585     gboolean result = FALSE;
586
587     switch (GST_QUERY_TYPE(query)) {
588     case GST_QUERY_DURATION: {
589         GstFormat format;
590
591         gst_query_parse_duration(query, &format, NULL);
592
593         GST_DEBUG_OBJECT(src, "duration query in format %s", gst_format_get_name(format));
594         GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
595         if (format == GST_FORMAT_BYTES && src->priv->size > 0) {
596             gst_query_set_duration(query, format, src->priv->size);
597             result = TRUE;
598         }
599         break;
600     }
601     case GST_QUERY_URI: {
602         GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
603         gst_query_set_uri(query, src->priv->uri);
604         result = TRUE;
605         break;
606     }
607     default: {
608         GRefPtr<GstPad> target = adoptGRef(gst_ghost_pad_get_target(GST_GHOST_PAD_CAST(pad)));
609
610         // Forward the query to the proxy target pad.
611         if (target)
612             result = gst_pad_query(target.get(), query);
613         break;
614     }
615     }
616
617     return result;
618 }
619
620 static bool urlHasSupportedProtocol(const URL& url)
621 {
622     return url.isValid() && (url.protocolIsInHTTPFamily() || url.protocolIs("blob"));
623 }
624
625 // uri handler interface
626
627 static GstURIType webKitWebSrcUriGetType(GType)
628 {
629     return GST_URI_SRC;
630 }
631
632 const gchar* const* webKitWebSrcGetProtocols(GType)
633 {
634     static const char* protocols[] = {"http", "https", "blob", 0 };
635     return protocols;
636 }
637
638 static gchar* webKitWebSrcGetUri(GstURIHandler* handler)
639 {
640     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
641     gchar* ret;
642
643     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
644     ret = g_strdup(src->priv->uri);
645     return ret;
646 }
647
648 static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri, GError** error)
649 {
650     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
651     WebKitWebSrcPrivate* priv = src->priv;
652
653     if (GST_STATE(src) >= GST_STATE_PAUSED) {
654         GST_ERROR_OBJECT(src, "URI can only be set in states < PAUSED");
655         return FALSE;
656     }
657
658     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
659
660     g_free(priv->uri);
661     priv->uri = 0;
662
663     if (!uri)
664         return TRUE;
665
666     URL url(URL(), uri);
667     if (!urlHasSupportedProtocol(url)) {
668         g_set_error(error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI, "Invalid URI '%s'", uri);
669         return FALSE;
670     }
671
672     priv->uri = g_strdup(url.string().utf8().data());
673     return TRUE;
674 }
675
676 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer)
677 {
678     GstURIHandlerInterface* iface = (GstURIHandlerInterface *) gIface;
679
680     iface->get_type = webKitWebSrcUriGetType;
681     iface->get_protocols = webKitWebSrcGetProtocols;
682     iface->get_uri = webKitWebSrcGetUri;
683     iface->set_uri = webKitWebSrcSetUri;
684 }
685
686 // appsrc callbacks
687
688 static gboolean webKitWebSrcNeedDataMainCb(WebKitWebSrc* src)
689 {
690     WebKitWebSrcPrivate* priv = src->priv;
691
692     ASSERT(isMainThread());
693
694     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
695     // already stopped
696     if (!priv->needDataID)
697         return FALSE;
698
699     priv->paused = FALSE;
700     priv->needDataID = 0;
701     locker.unlock();
702
703     if (priv->client)
704         priv->client->setDefersLoading(false);
705     return FALSE;
706 }
707
708 static void webKitWebSrcNeedDataCb(GstAppSrc*, guint length, gpointer userData)
709 {
710     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
711     WebKitWebSrcPrivate* priv = src->priv;
712
713     GST_DEBUG_OBJECT(src, "Need more data: %u", length);
714
715     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
716     if (priv->needDataID || !priv->paused) {
717         return;
718     }
719
720     priv->needDataID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcNeedDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
721 }
722
723 static gboolean webKitWebSrcEnoughDataMainCb(WebKitWebSrc* src)
724 {
725     WebKitWebSrcPrivate* priv = src->priv;
726
727     ASSERT(isMainThread());
728
729     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
730     // already stopped
731     if (!priv->enoughDataID)
732         return FALSE;
733
734     priv->paused = TRUE;
735     priv->enoughDataID = 0;
736     locker.unlock();
737
738     if (priv->client)
739         priv->client->setDefersLoading(true);
740     return FALSE;
741 }
742
743 static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData)
744 {
745     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
746     WebKitWebSrcPrivate* priv = src->priv;
747
748     GST_DEBUG_OBJECT(src, "Have enough data");
749
750     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
751     if (priv->enoughDataID || priv->paused) {
752         return;
753     }
754
755     priv->enoughDataID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcEnoughDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
756 }
757
758 static gboolean webKitWebSrcSeekMainCb(WebKitWebSrc* src)
759 {
760     WebKitWebSrcPrivate* priv = src->priv;
761
762     ASSERT(isMainThread());
763
764     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
765     // already stopped
766     if (!priv->seekID)
767         return FALSE;
768     locker.unlock();
769
770     webKitWebSrcStop(src);
771     webKitWebSrcStart(src);
772
773     return FALSE;
774 }
775
776 static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData)
777 {
778     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
779     WebKitWebSrcPrivate* priv = src->priv;
780
781     GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, offset);
782     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
783     if (offset == priv->offset && priv->requestedOffset == priv->offset)
784         return TRUE;
785
786     if (!priv->seekable)
787         return FALSE;
788
789     GST_DEBUG_OBJECT(src, "Doing range-request seek");
790     priv->requestedOffset = offset;
791
792     if (priv->seekID)
793         g_source_remove(priv->seekID);
794     priv->seekID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcSeekMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
795     return TRUE;
796 }
797
798 void webKitWebSrcSetMediaPlayer(WebKitWebSrc* src, WebCore::MediaPlayer* player)
799 {
800     ASSERT(player);
801     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
802     src->priv->player = player;
803 }
804
805 StreamingClient::StreamingClient(WebKitWebSrc* src)
806     : m_src(adoptGRef(static_cast<GstElement*>(gst_object_ref(src))))
807 {
808 }
809
810 StreamingClient::~StreamingClient()
811 {
812 }
813
814 char* StreamingClient::createReadBuffer(size_t requestedSize, size_t& actualSize)
815 {
816     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
817     WebKitWebSrcPrivate* priv = src->priv;
818
819     ASSERT(!priv->buffer);
820
821     GstBuffer* buffer = gst_buffer_new_and_alloc(requestedSize);
822
823     mapGstBuffer(buffer);
824
825     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
826     priv->buffer = adoptGRef(buffer);
827     locker.unlock();
828
829     actualSize = gst_buffer_get_size(buffer);
830     return getGstBufferDataPointer(buffer);
831 }
832
833 void StreamingClient::handleResponseReceived(const ResourceResponse& response)
834 {
835     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
836     WebKitWebSrcPrivate* priv = src->priv;
837
838     GST_DEBUG_OBJECT(src, "Received response: %d", response.httpStatusCode());
839
840     if (response.httpStatusCode() >= 400) {
841         // Received error code
842         GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received %d HTTP error code", response.httpStatusCode()), (0));
843         gst_app_src_end_of_stream(priv->appsrc);
844         webKitWebSrcStop(src);
845         return;
846     }
847
848     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
849
850     if (priv->seekID) {
851         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring response");
852         return;
853     }
854
855     if (priv->requestedOffset) {
856         // Seeking ... we expect a 206 == PARTIAL_CONTENT
857         if (response.httpStatusCode() == 200) {
858             // Range request didn't have a ranged response; resetting offset.
859             priv->offset = 0;
860         } else if (response.httpStatusCode() != 206) {
861             // Range request completely failed.
862             locker.unlock();
863             GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received unexpected %d HTTP status code", response.httpStatusCode()), (0));
864             gst_app_src_end_of_stream(priv->appsrc);
865             webKitWebSrcStop(src);
866             return;
867         }
868     }
869
870     long long length = response.expectedContentLength();
871     if (length > 0 && priv->requestedOffset && response.httpStatusCode() == 206)
872         length += priv->requestedOffset;
873
874     priv->size = length >= 0 ? length : 0;
875     priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField("Accept-Ranges").utf8().data());
876
877     // Wait until we unlock to send notifications
878     g_object_freeze_notify(G_OBJECT(src));
879
880     GstTagList* tags = gst_tag_list_new_empty();
881     String value = response.httpHeaderField("icy-name");
882     if (!value.isEmpty()) {
883         g_free(priv->iradioName);
884         priv->iradioName = g_strdup(value.utf8().data());
885         g_object_notify(G_OBJECT(src), "iradio-name");
886         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
887     }
888     value = response.httpHeaderField("icy-genre");
889     if (!value.isEmpty()) {
890         g_free(priv->iradioGenre);
891         priv->iradioGenre = g_strdup(value.utf8().data());
892         g_object_notify(G_OBJECT(src), "iradio-genre");
893         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
894     }
895     value = response.httpHeaderField("icy-url");
896     if (!value.isEmpty()) {
897         g_free(priv->iradioUrl);
898         priv->iradioUrl = g_strdup(value.utf8().data());
899         g_object_notify(G_OBJECT(src), "iradio-url");
900         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
901     }
902     value = response.httpHeaderField("icy-title");
903     if (!value.isEmpty()) {
904         g_free(priv->iradioTitle);
905         priv->iradioTitle = g_strdup(value.utf8().data());
906         g_object_notify(G_OBJECT(src), "iradio-title");
907         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
908     }
909
910     locker.unlock();
911     g_object_thaw_notify(G_OBJECT(src));
912
913     // notify size/duration
914     if (length > 0) {
915         gst_app_src_set_size(priv->appsrc, length);
916     } else
917         gst_app_src_set_size(priv->appsrc, -1);
918
919     // icecast stuff
920     value = response.httpHeaderField("icy-metaint");
921     if (!value.isEmpty()) {
922         gchar* endptr = 0;
923         gint64 icyMetaInt = g_ascii_strtoll(value.utf8().data(), &endptr, 10);
924
925         if (endptr && *endptr == '\0' && icyMetaInt > 0) {
926             GRefPtr<GstCaps> caps = adoptGRef(gst_caps_new_simple("application/x-icy", "metadata-interval", G_TYPE_INT, (gint) icyMetaInt, NULL));
927
928             gst_app_src_set_caps(priv->appsrc, caps.get());
929         }
930     } else
931         gst_app_src_set_caps(priv->appsrc, 0);
932
933     // notify tags
934     if (gst_tag_list_is_empty(tags))
935         gst_tag_list_unref(tags);
936     else
937         gst_pad_push_event(priv->srcpad, gst_event_new_tag(tags));
938 }
939
940 void StreamingClient::handleDataReceived(const char* data, int length)
941 {
942     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
943     WebKitWebSrcPrivate* priv = src->priv;
944
945     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
946
947     GST_LOG_OBJECT(src, "Have %lld bytes of data", priv->buffer ? static_cast<long long>(gst_buffer_get_size(priv->buffer.get())) : length);
948
949     ASSERT(!priv->buffer || data == getGstBufferDataPointer(priv->buffer.get()));
950
951     if (priv->buffer)
952         unmapGstBuffer(priv->buffer.get());
953
954     if (priv->seekID) {
955         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring data");
956         priv->buffer.clear();
957         return;
958     }
959
960     if (priv->offset < priv->requestedOffset) {
961         // Range request failed; seeking manually.
962         if (priv->offset + length <= priv->requestedOffset) {
963             // Discard all the buffers coming before the requested seek position.
964             priv->offset += length;
965             priv->buffer.clear();
966             return;
967         }
968
969         if (priv->offset + length > priv->requestedOffset) {
970             guint64 offset = priv->requestedOffset - priv->offset;
971             data += offset;
972             length -= offset;
973             if (priv->buffer)
974                 gst_buffer_resize(priv->buffer.get(), offset, -1);
975             priv->offset = priv->requestedOffset;
976         }
977
978         priv->requestedOffset = 0;
979     }
980
981     // Ports using the GStreamer backend but not the soup implementation of ResourceHandle
982     // won't be using buffers provided by this client, the buffer is created here in that case.
983     if (!priv->buffer)
984         priv->buffer = adoptGRef(createGstBufferForData(data, length));
985     else
986         gst_buffer_set_size(priv->buffer.get(), static_cast<gssize>(length));
987
988     GST_BUFFER_OFFSET(priv->buffer.get()) = priv->offset;
989     if (priv->requestedOffset == priv->offset)
990         priv->requestedOffset += length;
991     priv->offset += length;
992     // priv->size == 0 if received length on didReceiveResponse < 0.
993     if (priv->size > 0 && priv->offset > priv->size) {
994         GST_DEBUG_OBJECT(src, "Updating internal size from %" G_GUINT64_FORMAT " to %" G_GUINT64_FORMAT, priv->size, priv->offset);
995         gst_app_src_set_size(priv->appsrc, priv->offset);
996         priv->size = priv->offset;
997     }
998     GST_BUFFER_OFFSET_END(priv->buffer.get()) = priv->offset;
999
1000     locker.unlock();
1001
1002     GstFlowReturn ret = gst_app_src_push_buffer(priv->appsrc, priv->buffer.leakRef());
1003     if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
1004         GST_ELEMENT_ERROR(src, CORE, FAILED, (0), (0));
1005 }
1006
1007 void StreamingClient::handleNotifyFinished()
1008 {
1009     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1010     WebKitWebSrcPrivate* priv = src->priv;
1011
1012     GST_DEBUG_OBJECT(src, "Have EOS");
1013
1014     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1015     if (!priv->seekID) {
1016         locker.unlock();
1017         gst_app_src_end_of_stream(priv->appsrc);
1018     }
1019 }
1020
1021 CachedResourceStreamingClient::CachedResourceStreamingClient(WebKitWebSrc* src, CachedResourceLoader* resourceLoader, const ResourceRequest& request)
1022     : StreamingClient(src)
1023 {
1024     DataBufferingPolicy bufferingPolicy = request.url().protocolIs("blob") ? BufferData : DoNotBufferData;
1025     CachedResourceRequest cacheRequest(request, ResourceLoaderOptions(SendCallbacks, DoNotSniffContent, bufferingPolicy, DoNotAllowStoredCredentials, DoNotAskClientForCrossOriginCredentials, DoSecurityCheck, UseDefaultOriginRestrictionsForType));
1026     m_resource = resourceLoader->requestRawResource(cacheRequest);
1027     if (m_resource)
1028         m_resource->addClient(this);
1029 }
1030
1031 CachedResourceStreamingClient::~CachedResourceStreamingClient()
1032 {
1033     if (m_resource) {
1034         m_resource->removeClient(this);
1035         m_resource = 0;
1036     }
1037 }
1038
1039 bool CachedResourceStreamingClient::loadFailed() const
1040 {
1041     return !m_resource;
1042 }
1043
1044 void CachedResourceStreamingClient::setDefersLoading(bool defers)
1045 {
1046     if (m_resource)
1047         m_resource->setDefersLoading(defers);
1048 }
1049
1050 char* CachedResourceStreamingClient::getOrCreateReadBuffer(CachedResource*, size_t requestedSize, size_t& actualSize)
1051 {
1052     return createReadBuffer(requestedSize, actualSize);
1053 }
1054
1055 void CachedResourceStreamingClient::responseReceived(CachedResource*, const ResourceResponse& response)
1056 {
1057     handleResponseReceived(response);
1058 }
1059
1060 void CachedResourceStreamingClient::dataReceived(CachedResource*, const char* data, int length)
1061 {
1062     handleDataReceived(data, length);
1063 }
1064
1065 void CachedResourceStreamingClient::notifyFinished(CachedResource* resource)
1066 {
1067     if (resource->loadFailedOrCanceled()) {
1068         WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1069
1070         if (!resource->wasCanceled()) {
1071             const ResourceError& error = resource->resourceError();
1072             GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
1073             GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
1074         }
1075         gst_app_src_end_of_stream(src->priv->appsrc);
1076         return;
1077     }
1078
1079     handleNotifyFinished();
1080 }
1081
1082 ResourceHandleStreamingClient::ResourceHandleStreamingClient(WebKitWebSrc* src, const ResourceRequest& request)
1083     : StreamingClient(src)
1084 {
1085     m_resource = ResourceHandle::create(0 /*context*/, request, this, false, false);
1086 }
1087
1088 ResourceHandleStreamingClient::~ResourceHandleStreamingClient()
1089 {
1090     if (m_resource) {
1091         m_resource->cancel();
1092         m_resource.release();
1093         m_resource = 0;
1094     }
1095 }
1096
1097 bool ResourceHandleStreamingClient::loadFailed() const
1098 {
1099     return !m_resource;
1100 }
1101
1102 void ResourceHandleStreamingClient::setDefersLoading(bool defers)
1103 {
1104     if (m_resource)
1105         m_resource->setDefersLoading(defers);
1106 }
1107
1108 char* ResourceHandleStreamingClient::getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize)
1109 {
1110     return createReadBuffer(requestedSize, actualSize);
1111 }
1112
1113 void ResourceHandleStreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
1114 {
1115 }
1116
1117 void ResourceHandleStreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
1118 {
1119     handleResponseReceived(response);
1120 }
1121
1122 void ResourceHandleStreamingClient::didReceiveData(ResourceHandle*, const char* data, unsigned length, int)
1123 {
1124     ASSERT_NOT_REACHED();
1125 }
1126
1127 void ResourceHandleStreamingClient::didReceiveBuffer(ResourceHandle*, PassRefPtr<SharedBuffer> buffer, int /* encodedLength */)
1128 {
1129     // This pattern is suggested by SharedBuffer.h.
1130     const char* segment;
1131     unsigned position = 0;
1132     while (unsigned length = buffer->getSomeData(segment, position)) {
1133         handleDataReceived(segment, length);
1134         position += length;
1135     }
1136 }
1137
1138 void ResourceHandleStreamingClient::didFinishLoading(ResourceHandle*, double)
1139 {
1140     handleNotifyFinished();
1141 }
1142
1143 void ResourceHandleStreamingClient::didFail(ResourceHandle*, const ResourceError& error)
1144 {
1145     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1146
1147     GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
1148     GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
1149     gst_app_src_end_of_stream(src->priv->appsrc);
1150 }
1151
1152 void ResourceHandleStreamingClient::wasBlocked(ResourceHandle*)
1153 {
1154     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1155     GUniquePtr<gchar> uri;
1156
1157     GST_ERROR_OBJECT(src, "Request was blocked");
1158
1159     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1160     uri.reset(g_strdup(src->priv->uri));
1161     locker.unlock();
1162
1163     GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", uri.get()), (0));
1164 }
1165
1166 void ResourceHandleStreamingClient::cannotShowURL(ResourceHandle*)
1167 {
1168     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1169     GUniquePtr<gchar> uri;
1170
1171     GST_ERROR_OBJECT(src, "Cannot show URL");
1172
1173     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1174     uri.reset(g_strdup(src->priv->uri));
1175     locker.unlock();
1176
1177     GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", uri.get()), (0));
1178 }
1179
1180 #endif // USE(GSTREAMER)
1181