[GStreamer] Seeking fails on media content provided by servers not supporting Range...
[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 <gst/app/gstappsrc.h>
39 #include <gst/gst.h>
40 #include <gst/pbutils/missing-plugins.h>
41 #include <wtf/Noncopyable.h>
42 #include <wtf/gobject/GMutexLocker.h>
43 #include <wtf/gobject/GOwnPtr.h>
44 #include <wtf/gobject/GRefPtr.h>
45 #include <wtf/text/CString.h>
46
47 using namespace WebCore;
48
49 class StreamingClient {
50     public:
51         StreamingClient(WebKitWebSrc*);
52         virtual ~StreamingClient();
53
54         virtual bool loadFailed() const = 0;
55         virtual void setDefersLoading(bool) = 0;
56
57     protected:
58         char* createReadBuffer(size_t requestedSize, size_t& actualSize);
59         void handleResponseReceived(const ResourceResponse&);
60         void handleDataReceived(const char*, int);
61         void handleNotifyFinished();
62
63         GRefPtr<GstElement> m_src;
64 };
65
66 class CachedResourceStreamingClient : public CachedRawResourceClient, public StreamingClient {
67     WTF_MAKE_NONCOPYABLE(CachedResourceStreamingClient); WTF_MAKE_FAST_ALLOCATED;
68     public:
69         CachedResourceStreamingClient(WebKitWebSrc*, CachedResourceLoader*, const ResourceRequest&);
70         virtual ~CachedResourceStreamingClient();
71
72         // StreamingClient virtual methods.
73         virtual bool loadFailed() const;
74         virtual void setDefersLoading(bool);
75
76     private:
77         // CachedResourceClient virtual methods.
78         virtual char* getOrCreateReadBuffer(CachedResource*, size_t requestedSize, size_t& actualSize);
79         virtual void responseReceived(CachedResource*, const ResourceResponse&);
80         virtual void dataReceived(CachedResource*, const char*, int);
81         virtual void notifyFinished(CachedResource*);
82
83         CachedResourceHandle<CachedRawResource> m_resource;
84 };
85
86 class ResourceHandleStreamingClient : public ResourceHandleClient, public StreamingClient {
87     WTF_MAKE_NONCOPYABLE(ResourceHandleStreamingClient); WTF_MAKE_FAST_ALLOCATED;
88     public:
89         ResourceHandleStreamingClient(WebKitWebSrc*, const ResourceRequest&);
90         virtual ~ResourceHandleStreamingClient();
91
92         // StreamingClient virtual methods.
93         virtual bool loadFailed() const;
94         virtual void setDefersLoading(bool);
95
96     private:
97         // ResourceHandleClient virtual methods.
98         virtual char* getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize);
99         virtual void willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&);
100         virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
101         virtual void didReceiveData(ResourceHandle*, const char*, int, int);
102         virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
103         virtual void didFail(ResourceHandle*, const ResourceError&);
104         virtual void wasBlocked(ResourceHandle*);
105         virtual void cannotShowURL(ResourceHandle*);
106
107         RefPtr<ResourceHandle> m_resource;
108 };
109
110 #define WEBKIT_WEB_SRC_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), WEBKIT_TYPE_WEB_SRC, WebKitWebSrcPrivate))
111 struct _WebKitWebSrcPrivate {
112     GstAppSrc* appsrc;
113     GstPad* srcpad;
114     gchar* uri;
115
116     WebCore::MediaPlayer* player;
117
118     StreamingClient* client;
119
120     guint64 offset;
121     guint64 size;
122     gboolean seekable;
123     gboolean paused;
124
125     guint64 requestedOffset;
126
127     guint startID;
128     guint stopID;
129     guint needDataID;
130     guint enoughDataID;
131     guint seekID;
132
133     GRefPtr<GstBuffer> buffer;
134
135     // icecast stuff
136     gboolean iradioMode;
137     gchar* iradioName;
138     gchar* iradioGenre;
139     gchar* iradioUrl;
140     gchar* iradioTitle;
141 };
142
143 enum {
144     PROP_IRADIO_MODE = 1,
145     PROP_IRADIO_NAME,
146     PROP_IRADIO_GENRE,
147     PROP_IRADIO_URL,
148     PROP_IRADIO_TITLE,
149     PROP_LOCATION
150 };
151
152 static GstStaticPadTemplate srcTemplate = GST_STATIC_PAD_TEMPLATE("src",
153                                                                   GST_PAD_SRC,
154                                                                   GST_PAD_ALWAYS,
155                                                                   GST_STATIC_CAPS_ANY);
156
157 GST_DEBUG_CATEGORY_STATIC(webkit_web_src_debug);
158 #define GST_CAT_DEFAULT webkit_web_src_debug
159
160 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer ifaceData);
161
162 static void webKitWebSrcDispose(GObject*);
163 static void webKitWebSrcFinalize(GObject*);
164 static void webKitWebSrcSetProperty(GObject*, guint propertyID, const GValue*, GParamSpec*);
165 static void webKitWebSrcGetProperty(GObject*, guint propertyID, GValue*, GParamSpec*);
166 static GstStateChangeReturn webKitWebSrcChangeState(GstElement*, GstStateChange);
167
168 static gboolean webKitWebSrcQueryWithParent(GstPad*, GstObject*, GstQuery*);
169
170 static void webKitWebSrcNeedDataCb(GstAppSrc*, guint length, gpointer userData);
171 static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData);
172 static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData);
173
174 static GstAppSrcCallbacks appsrcCallbacks = {
175     webKitWebSrcNeedDataCb,
176     webKitWebSrcEnoughDataCb,
177     webKitWebSrcSeekDataCb,
178     { 0 }
179 };
180
181 #define webkit_web_src_parent_class parent_class
182 // We split this out into another macro to avoid a check-webkit-style error.
183 #define WEBKIT_WEB_SRC_CATEGORY_INIT GST_DEBUG_CATEGORY_INIT(webkit_web_src_debug, "webkitwebsrc", 0, "websrc element");
184 G_DEFINE_TYPE_WITH_CODE(WebKitWebSrc, webkit_web_src, GST_TYPE_BIN,
185                          G_IMPLEMENT_INTERFACE(GST_TYPE_URI_HANDLER, webKitWebSrcUriHandlerInit);
186                          WEBKIT_WEB_SRC_CATEGORY_INIT);
187
188 static void webkit_web_src_class_init(WebKitWebSrcClass* klass)
189 {
190     GObjectClass* oklass = G_OBJECT_CLASS(klass);
191     GstElementClass* eklass = GST_ELEMENT_CLASS(klass);
192
193     oklass->dispose = webKitWebSrcDispose;
194     oklass->finalize = webKitWebSrcFinalize;
195     oklass->set_property = webKitWebSrcSetProperty;
196     oklass->get_property = webKitWebSrcGetProperty;
197
198     gst_element_class_add_pad_template(eklass,
199                                        gst_static_pad_template_get(&srcTemplate));
200     gst_element_class_set_metadata(eklass, "WebKit Web source element", "Source", "Handles HTTP/HTTPS uris",
201                                "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
202
203     // icecast stuff
204     g_object_class_install_property(oklass,
205                                     PROP_IRADIO_MODE,
206                                     g_param_spec_boolean("iradio-mode",
207                                                          "iradio-mode",
208                                                          "Enable internet radio mode (extraction of shoutcast/icecast metadata)",
209                                                          FALSE,
210                                                          (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
211
212     g_object_class_install_property(oklass,
213                                     PROP_IRADIO_NAME,
214                                     g_param_spec_string("iradio-name",
215                                                         "iradio-name",
216                                                         "Name of the stream",
217                                                         0,
218                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
219
220     g_object_class_install_property(oklass,
221                                     PROP_IRADIO_GENRE,
222                                     g_param_spec_string("iradio-genre",
223                                                         "iradio-genre",
224                                                         "Genre of the stream",
225                                                         0,
226                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
227
228     g_object_class_install_property(oklass,
229                                     PROP_IRADIO_URL,
230                                     g_param_spec_string("iradio-url",
231                                                         "iradio-url",
232                                                         "Homepage URL for radio stream",
233                                                         0,
234                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
235
236     g_object_class_install_property(oklass,
237                                     PROP_IRADIO_TITLE,
238                                     g_param_spec_string("iradio-title",
239                                                         "iradio-title",
240                                                         "Name of currently playing song",
241                                                         0,
242                                                         (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
243
244
245     /* Allows setting the uri using the 'location' property, which is used
246      * for example by gst_element_make_from_uri() */
247     g_object_class_install_property(oklass,
248                                     PROP_LOCATION,
249                                     g_param_spec_string("location",
250                                                         "location",
251                                                         "Location to read from",
252                                                         0,
253                                                         (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
254     eklass->change_state = webKitWebSrcChangeState;
255
256     g_type_class_add_private(klass, sizeof(WebKitWebSrcPrivate));
257 }
258
259 static void webkit_web_src_init(WebKitWebSrc* src)
260 {
261     WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC_GET_PRIVATE(src);
262
263     src->priv = priv;
264
265     priv->appsrc = GST_APP_SRC(gst_element_factory_make("appsrc", 0));
266     if (!priv->appsrc) {
267         GST_ERROR_OBJECT(src, "Failed to create appsrc");
268         return;
269     }
270
271     gst_bin_add(GST_BIN(src), GST_ELEMENT(priv->appsrc));
272
273
274     GRefPtr<GstPad> targetPad = adoptGRef(gst_element_get_static_pad(GST_ELEMENT(priv->appsrc), "src"));
275     priv->srcpad = webkitGstGhostPadFromStaticTemplate(&srcTemplate, "src", targetPad.get());
276
277     gst_element_add_pad(GST_ELEMENT(src), priv->srcpad);
278
279     GST_OBJECT_FLAG_SET(priv->srcpad, GST_PAD_FLAG_NEED_PARENT);
280     gst_pad_set_query_function(priv->srcpad, webKitWebSrcQueryWithParent);
281
282     gst_app_src_set_callbacks(priv->appsrc, &appsrcCallbacks, src, 0);
283     gst_app_src_set_emit_signals(priv->appsrc, FALSE);
284     gst_app_src_set_stream_type(priv->appsrc, GST_APP_STREAM_TYPE_SEEKABLE);
285
286     // 512k is a abitrary number but we should choose a value
287     // here to not pause/unpause the SoupMessage too often and
288     // to make sure there's always some data available for
289     // GStreamer to handle.
290     gst_app_src_set_max_bytes(priv->appsrc, 512 * 1024);
291
292     // Emit the need-data signal if the queue contains less
293     // than 20% of data. Without this the need-data signal
294     // is emitted when the queue is empty, we then dispatch
295     // the soup message unpausing to the main loop and from
296     // there unpause the soup message. This already takes
297     // quite some time and libsoup even needs some more time
298     // to actually provide data again. If we do all this
299     // already if the queue is 20% empty, it's much more
300     // likely that libsoup already provides new data before
301     // the queue is really empty.
302     // This might need tweaking for ports not using libsoup.
303     g_object_set(priv->appsrc, "min-percent", 20, NULL);
304
305     gst_app_src_set_caps(priv->appsrc, 0);
306     gst_app_src_set_size(priv->appsrc, -1);
307 }
308
309 static void webKitWebSrcDispose(GObject* object)
310 {
311     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
312     WebKitWebSrcPrivate* priv = src->priv;
313
314     priv->player = 0;
315
316     GST_CALL_PARENT(G_OBJECT_CLASS, dispose, (object));
317 }
318
319 static void webKitWebSrcFinalize(GObject* object)
320 {
321     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
322     WebKitWebSrcPrivate* priv = src->priv;
323
324     g_free(priv->uri);
325
326     GST_CALL_PARENT(G_OBJECT_CLASS, finalize, (object));
327 }
328
329 static void webKitWebSrcSetProperty(GObject* object, guint propID, const GValue* value, GParamSpec* pspec)
330 {
331     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
332     WebKitWebSrcPrivate* priv = src->priv;
333
334     switch (propID) {
335     case PROP_IRADIO_MODE: {
336         GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
337         priv->iradioMode = g_value_get_boolean(value);
338         break;
339     }
340     case PROP_LOCATION:
341         gst_uri_handler_set_uri(reinterpret_cast<GstURIHandler*>(src), g_value_get_string(value), 0);
342         break;
343     default:
344         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
345         break;
346     }
347 }
348
349 static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value, GParamSpec* pspec)
350 {
351     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
352     WebKitWebSrcPrivate* priv = src->priv;
353
354     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
355     switch (propID) {
356     case PROP_IRADIO_MODE:
357         g_value_set_boolean(value, priv->iradioMode);
358         break;
359     case PROP_IRADIO_NAME:
360         g_value_set_string(value, priv->iradioName);
361         break;
362     case PROP_IRADIO_GENRE:
363         g_value_set_string(value, priv->iradioGenre);
364         break;
365     case PROP_IRADIO_URL:
366         g_value_set_string(value, priv->iradioUrl);
367         break;
368     case PROP_IRADIO_TITLE:
369         g_value_set_string(value, priv->iradioTitle);
370         break;
371     case PROP_LOCATION:
372         g_value_set_string(value, priv->uri);
373         break;
374     default:
375         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
376         break;
377     }
378 }
379
380 static void removeTimeoutSources(WebKitWebSrc* src)
381 {
382     WebKitWebSrcPrivate* priv = src->priv;
383
384     if (priv->startID)
385         g_source_remove(priv->startID);
386     priv->startID = 0;
387
388     if (priv->needDataID)
389         g_source_remove(priv->needDataID);
390     priv->needDataID = 0;
391
392     if (priv->enoughDataID)
393         g_source_remove(priv->enoughDataID);
394     priv->enoughDataID = 0;
395
396     if (priv->seekID)
397         g_source_remove(priv->seekID);
398     priv->seekID = 0;
399 }
400
401 static gboolean webKitWebSrcStop(WebKitWebSrc* src)
402 {
403     WebKitWebSrcPrivate* priv = src->priv;
404
405     ASSERT(isMainThread());
406
407     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
408
409     bool seeking = priv->seekID;
410
411     removeTimeoutSources(src);
412     priv->stopID = 0;
413
414     if (priv->client) {
415         delete priv->client;
416         priv->client = 0;
417     }
418
419     if (priv->buffer) {
420         unmapGstBuffer(priv->buffer.get());
421         priv->buffer.clear();
422     }
423
424     priv->paused = FALSE;
425
426     g_free(priv->iradioName);
427     priv->iradioName = 0;
428
429     g_free(priv->iradioGenre);
430     priv->iradioGenre = 0;
431
432     g_free(priv->iradioUrl);
433     priv->iradioUrl = 0;
434
435     g_free(priv->iradioTitle);
436     priv->iradioTitle = 0;
437
438     priv->offset = 0;
439     priv->seekable = FALSE;
440
441     if (!seeking) {
442         priv->size = 0;
443         priv->requestedOffset = 0;
444         priv->player = 0;
445     }
446
447     locker.unlock();
448
449     if (priv->appsrc) {
450         gst_app_src_set_caps(priv->appsrc, 0);
451         if (!seeking)
452             gst_app_src_set_size(priv->appsrc, -1);
453     }
454
455     GST_DEBUG_OBJECT(src, "Stopped request");
456
457     return FALSE;
458 }
459
460 static gboolean webKitWebSrcStart(WebKitWebSrc* src)
461 {
462     WebKitWebSrcPrivate* priv = src->priv;
463
464     ASSERT(isMainThread());
465
466     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
467
468     priv->startID = 0;
469
470     if (!priv->uri) {
471         GST_ERROR_OBJECT(src, "No URI provided");
472         locker.unlock();
473         webKitWebSrcStop(src);
474         return FALSE;
475     }
476
477     ASSERT(!priv->client);
478
479     URL url = URL(URL(), priv->uri);
480
481     ResourceRequest request(url);
482     request.setAllowCookies(true);
483
484     if (priv->player)
485         request.setHTTPReferrer(priv->player->referrer());
486
487 #if USE(SOUP)
488     // Let's disable HTTP Accept-Encoding here as we don't want the received response to be
489     // encoded in any way as we need to rely on the proper size of the returned data on
490     // didReceiveResponse.
491     // If Accept-Encoding is used, the server may send the data in encoded format and
492     // request.expectedContentLength() will have the "wrong" size (the size of the
493     // compressed data), even though the data received in didReceiveData is uncompressed.
494     request.setAcceptEncoding(false);
495 #endif
496
497     // Let Apple web servers know we want to access their nice movie trailers.
498     if (!g_ascii_strcasecmp("movies.apple.com", url.host().utf8().data())
499         || !g_ascii_strcasecmp("trailers.apple.com", url.host().utf8().data()))
500         request.setHTTPUserAgent("Quicktime/7.6.6");
501
502     if (priv->requestedOffset) {
503         GOwnPtr<gchar> val;
504
505         val.set(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     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
841
842     if (priv->seekID) {
843         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring response");
844         return;
845     }
846
847     if (priv->requestedOffset) {
848         // Seeking ... we expect a 206 == PARTIAL_CONTENT
849         if (response.httpStatusCode() == 200) {
850             // Range request didn't have a ranged response; resetting offset.
851             priv->offset = 0;
852         } else if (response.httpStatusCode() != 206) {
853             // Range request completely failed.
854             locker.unlock();
855             GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received unexpected %d HTTP status code", response.httpStatusCode()), (0));
856             gst_app_src_end_of_stream(priv->appsrc);
857             webKitWebSrcStop(src);
858             return;
859         }
860     }
861
862     long long length = response.expectedContentLength();
863     if (length > 0 && priv->requestedOffset && response.httpStatusCode() == 206)
864         length += priv->requestedOffset;
865
866     priv->size = length >= 0 ? length : 0;
867     priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField("Accept-Ranges").utf8().data());
868
869     GstTagList* tags = gst_tag_list_new_empty();
870     String value = response.httpHeaderField("icy-name");
871     if (!value.isEmpty()) {
872         g_free(priv->iradioName);
873         priv->iradioName = g_strdup(value.utf8().data());
874         g_object_notify(G_OBJECT(src), "iradio-name");
875         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
876     }
877     value = response.httpHeaderField("icy-genre");
878     if (!value.isEmpty()) {
879         g_free(priv->iradioGenre);
880         priv->iradioGenre = g_strdup(value.utf8().data());
881         g_object_notify(G_OBJECT(src), "iradio-genre");
882         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
883     }
884     value = response.httpHeaderField("icy-url");
885     if (!value.isEmpty()) {
886         g_free(priv->iradioUrl);
887         priv->iradioUrl = g_strdup(value.utf8().data());
888         g_object_notify(G_OBJECT(src), "iradio-url");
889         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
890     }
891     value = response.httpHeaderField("icy-title");
892     if (!value.isEmpty()) {
893         g_free(priv->iradioTitle);
894         priv->iradioTitle = g_strdup(value.utf8().data());
895         g_object_notify(G_OBJECT(src), "iradio-title");
896         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
897     }
898
899     locker.unlock();
900
901     // notify size/duration
902     if (length > 0) {
903         gst_app_src_set_size(priv->appsrc, length);
904     } else
905         gst_app_src_set_size(priv->appsrc, -1);
906
907     // icecast stuff
908     value = response.httpHeaderField("icy-metaint");
909     if (!value.isEmpty()) {
910         gchar* endptr = 0;
911         gint64 icyMetaInt = g_ascii_strtoll(value.utf8().data(), &endptr, 10);
912
913         if (endptr && *endptr == '\0' && icyMetaInt > 0) {
914             GRefPtr<GstCaps> caps = adoptGRef(gst_caps_new_simple("application/x-icy", "metadata-interval", G_TYPE_INT, (gint) icyMetaInt, NULL));
915
916             gst_app_src_set_caps(priv->appsrc, caps.get());
917         }
918     } else
919         gst_app_src_set_caps(priv->appsrc, 0);
920
921     // notify tags
922     if (gst_tag_list_is_empty(tags))
923         gst_tag_list_unref(tags);
924     else
925         gst_pad_push_event(priv->srcpad, gst_event_new_tag(tags));
926 }
927
928 void StreamingClient::handleDataReceived(const char* data, int length)
929 {
930     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
931     WebKitWebSrcPrivate* priv = src->priv;
932
933     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
934
935     GST_LOG_OBJECT(src, "Have %ld bytes of data", priv->buffer ? gst_buffer_get_size(priv->buffer.get()) : length);
936
937     ASSERT(!priv->buffer || data == getGstBufferDataPointer(priv->buffer.get()));
938
939     if (priv->buffer)
940         unmapGstBuffer(priv->buffer.get());
941
942     if (priv->seekID) {
943         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring data");
944         priv->buffer.clear();
945         return;
946     }
947
948     if (priv->offset < priv->requestedOffset) {
949         // Range request failed; seeking manually.
950         if (priv->offset + length <= priv->requestedOffset) {
951             // Discard all the buffers coming before the requested seek position.
952             priv->offset += length;
953             priv->buffer.clear();
954             return;
955         }
956
957         if (priv->offset + length > priv->requestedOffset) {
958             guint64 offset = priv->requestedOffset - priv->offset;
959             data += offset;
960             length -= offset;
961             if (priv->buffer)
962                 gst_buffer_resize(priv->buffer.get(), offset, -1);
963             priv->offset = priv->requestedOffset;
964         }
965
966         priv->requestedOffset = 0;
967     }
968
969     // Ports using the GStreamer backend but not the soup implementation of ResourceHandle
970     // won't be using buffers provided by this client, the buffer is created here in that case.
971     if (!priv->buffer)
972         priv->buffer = adoptGRef(createGstBufferForData(data, length));
973     else
974         gst_buffer_set_size(priv->buffer.get(), static_cast<gssize>(length));
975
976     GST_BUFFER_OFFSET(priv->buffer.get()) = priv->offset;
977     if (priv->requestedOffset == priv->offset)
978         priv->requestedOffset += length;
979     priv->offset += length;
980     // priv->size == 0 if received length on didReceiveResponse < 0.
981     if (priv->size > 0 && priv->offset > priv->size) {
982         GST_DEBUG_OBJECT(src, "Updating internal size from %" G_GUINT64_FORMAT " to %" G_GUINT64_FORMAT, priv->size, priv->offset);
983         gst_app_src_set_size(priv->appsrc, priv->offset);
984         priv->size = priv->offset;
985     }
986     GST_BUFFER_OFFSET_END(priv->buffer.get()) = priv->offset;
987
988     locker.unlock();
989
990     GstFlowReturn ret = gst_app_src_push_buffer(priv->appsrc, priv->buffer.leakRef());
991     if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
992         GST_ELEMENT_ERROR(src, CORE, FAILED, (0), (0));
993 }
994
995 void StreamingClient::handleNotifyFinished()
996 {
997     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
998     WebKitWebSrcPrivate* priv = src->priv;
999
1000     GST_DEBUG_OBJECT(src, "Have EOS");
1001
1002     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1003     if (!priv->seekID) {
1004         locker.unlock();
1005         gst_app_src_end_of_stream(priv->appsrc);
1006     }
1007 }
1008
1009 CachedResourceStreamingClient::CachedResourceStreamingClient(WebKitWebSrc* src, CachedResourceLoader* resourceLoader, const ResourceRequest& request)
1010     : StreamingClient(src)
1011 {
1012     DataBufferingPolicy bufferingPolicy = request.url().protocolIs("blob") ? BufferData : DoNotBufferData;
1013     CachedResourceRequest cacheRequest(request, ResourceLoaderOptions(SendCallbacks, DoNotSniffContent, bufferingPolicy, DoNotAllowStoredCredentials, DoNotAskClientForCrossOriginCredentials, DoSecurityCheck, UseDefaultOriginRestrictionsForType));
1014     m_resource = resourceLoader->requestRawResource(cacheRequest);
1015     if (m_resource)
1016         m_resource->addClient(this);
1017 }
1018
1019 CachedResourceStreamingClient::~CachedResourceStreamingClient()
1020 {
1021     if (m_resource) {
1022         m_resource->removeClient(this);
1023         m_resource = 0;
1024     }
1025 }
1026
1027 bool CachedResourceStreamingClient::loadFailed() const
1028 {
1029     return !m_resource;
1030 }
1031
1032 void CachedResourceStreamingClient::setDefersLoading(bool defers)
1033 {
1034     if (m_resource)
1035         m_resource->setDefersLoading(defers);
1036 }
1037
1038 char* CachedResourceStreamingClient::getOrCreateReadBuffer(CachedResource*, size_t requestedSize, size_t& actualSize)
1039 {
1040     return createReadBuffer(requestedSize, actualSize);
1041 }
1042
1043 void CachedResourceStreamingClient::responseReceived(CachedResource*, const ResourceResponse& response)
1044 {
1045     handleResponseReceived(response);
1046 }
1047
1048 void CachedResourceStreamingClient::dataReceived(CachedResource*, const char* data, int length)
1049 {
1050     handleDataReceived(data, length);
1051 }
1052
1053 void CachedResourceStreamingClient::notifyFinished(CachedResource* resource)
1054 {
1055     if (resource->loadFailedOrCanceled()) {
1056         WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1057
1058         if (!resource->wasCanceled()) {
1059             const ResourceError& error = resource->resourceError();
1060             GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
1061             GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
1062         }
1063         gst_app_src_end_of_stream(src->priv->appsrc);
1064         return;
1065     }
1066
1067     handleNotifyFinished();
1068 }
1069
1070 ResourceHandleStreamingClient::ResourceHandleStreamingClient(WebKitWebSrc* src, const ResourceRequest& request)
1071     : StreamingClient(src)
1072 {
1073     m_resource = ResourceHandle::create(0 /*context*/, request, this, false, false);
1074 }
1075
1076 ResourceHandleStreamingClient::~ResourceHandleStreamingClient()
1077 {
1078     if (m_resource) {
1079         m_resource->cancel();
1080         m_resource.release();
1081         m_resource = 0;
1082     }
1083 }
1084
1085 bool ResourceHandleStreamingClient::loadFailed() const
1086 {
1087     return !m_resource;
1088 }
1089
1090 void ResourceHandleStreamingClient::setDefersLoading(bool defers)
1091 {
1092     if (m_resource)
1093         m_resource->setDefersLoading(defers);
1094 }
1095
1096 char* ResourceHandleStreamingClient::getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize)
1097 {
1098     return createReadBuffer(requestedSize, actualSize);
1099 }
1100
1101 void ResourceHandleStreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
1102 {
1103 }
1104
1105 void ResourceHandleStreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
1106 {
1107     handleResponseReceived(response);
1108 }
1109
1110 void ResourceHandleStreamingClient::didReceiveData(ResourceHandle*, const char* data, int length, int)
1111 {
1112     handleDataReceived(data, length);
1113 }
1114
1115 void ResourceHandleStreamingClient::didFinishLoading(ResourceHandle*, double)
1116 {
1117     handleNotifyFinished();
1118 }
1119
1120 void ResourceHandleStreamingClient::didFail(ResourceHandle*, const ResourceError& error)
1121 {
1122     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1123
1124     GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
1125     GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
1126     gst_app_src_end_of_stream(src->priv->appsrc);
1127 }
1128
1129 void ResourceHandleStreamingClient::wasBlocked(ResourceHandle*)
1130 {
1131     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1132     GOwnPtr<gchar> uri;
1133
1134     GST_ERROR_OBJECT(src, "Request was blocked");
1135
1136     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1137     uri.set(g_strdup(src->priv->uri));
1138     locker.unlock();
1139
1140     GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", uri.get()), (0));
1141 }
1142
1143 void ResourceHandleStreamingClient::cannotShowURL(ResourceHandle*)
1144 {
1145     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1146     GOwnPtr<gchar> uri;
1147
1148     GST_ERROR_OBJECT(src, "Cannot show URL");
1149
1150     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1151     uri.set(g_strdup(src->priv->uri));
1152     locker.unlock();
1153
1154     GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", uri.get()), (0));
1155 }
1156
1157 #endif // USE(GSTREAMER)
1158