[WK2][Soup] Use didReceiveBuffer instead of didReceiveData
[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/GOwnPtr.h>
45 #include <wtf/gobject/GRefPtr.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*, int, 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         GOwnPtr<gchar> val;
506
507         val.set(g_strdup_printf("bytes=%" G_GUINT64_FORMAT "-", priv->requestedOffset));
508         request.setHTTPHeaderField("Range", val.get());
509     }
510     priv->offset = priv->requestedOffset;
511
512     if (priv->iradioMode)
513         request.setHTTPHeaderField("icy-metadata", "1");
514
515     // Needed to use DLNA streaming servers
516     request.setHTTPHeaderField("transferMode.dlna", "Streaming");
517
518     if (priv->player) {
519         if (CachedResourceLoader* loader = priv->player->cachedResourceLoader())
520             priv->client = new CachedResourceStreamingClient(src, loader, request);
521     }
522
523     if (!priv->client)
524         priv->client = new ResourceHandleStreamingClient(src, request);
525
526     if (!priv->client || priv->client->loadFailed()) {
527         GST_ERROR_OBJECT(src, "Failed to setup streaming client");
528         if (priv->client) {
529             delete priv->client;
530             priv->client = 0;
531         }
532         locker.unlock();
533         webKitWebSrcStop(src);
534         return FALSE;
535     }
536     GST_DEBUG_OBJECT(src, "Started request");
537     return FALSE;
538 }
539
540 static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStateChange transition)
541 {
542     GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
543     WebKitWebSrc* src = WEBKIT_WEB_SRC(element);
544     WebKitWebSrcPrivate* priv = src->priv;
545
546     switch (transition) {
547     case GST_STATE_CHANGE_NULL_TO_READY:
548         if (!priv->appsrc) {
549             gst_element_post_message(element,
550                                      gst_missing_element_message_new(element, "appsrc"));
551             GST_ELEMENT_ERROR(src, CORE, MISSING_PLUGIN, (0), ("no appsrc"));
552             return GST_STATE_CHANGE_FAILURE;
553         }
554         break;
555     default:
556         break;
557     }
558
559     ret = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition);
560     if (G_UNLIKELY(ret == GST_STATE_CHANGE_FAILURE)) {
561         GST_DEBUG_OBJECT(src, "State change failed");
562         return ret;
563     }
564
565     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
566     switch (transition) {
567     case GST_STATE_CHANGE_READY_TO_PAUSED:
568         GST_DEBUG_OBJECT(src, "READY->PAUSED");
569         priv->startID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcStart, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
570         break;
571     case GST_STATE_CHANGE_PAUSED_TO_READY:
572         GST_DEBUG_OBJECT(src, "PAUSED->READY");
573         // cancel pending sources
574         removeTimeoutSources(src);
575         priv->stopID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcStop, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
576         break;
577     default:
578         break;
579     }
580
581     return ret;
582 }
583
584 static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQuery* query)
585 {
586     WebKitWebSrc* src = WEBKIT_WEB_SRC(GST_ELEMENT(parent));
587     gboolean result = FALSE;
588
589     switch (GST_QUERY_TYPE(query)) {
590     case GST_QUERY_DURATION: {
591         GstFormat format;
592
593         gst_query_parse_duration(query, &format, NULL);
594
595         GST_DEBUG_OBJECT(src, "duration query in format %s", gst_format_get_name(format));
596         GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
597         if (format == GST_FORMAT_BYTES && src->priv->size > 0) {
598             gst_query_set_duration(query, format, src->priv->size);
599             result = TRUE;
600         }
601         break;
602     }
603     case GST_QUERY_URI: {
604         GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
605         gst_query_set_uri(query, src->priv->uri);
606         result = TRUE;
607         break;
608     }
609     default: {
610         GRefPtr<GstPad> target = adoptGRef(gst_ghost_pad_get_target(GST_GHOST_PAD_CAST(pad)));
611
612         // Forward the query to the proxy target pad.
613         if (target)
614             result = gst_pad_query(target.get(), query);
615         break;
616     }
617     }
618
619     return result;
620 }
621
622 static bool urlHasSupportedProtocol(const URL& url)
623 {
624     return url.isValid() && (url.protocolIsInHTTPFamily() || url.protocolIs("blob"));
625 }
626
627 // uri handler interface
628
629 static GstURIType webKitWebSrcUriGetType(GType)
630 {
631     return GST_URI_SRC;
632 }
633
634 const gchar* const* webKitWebSrcGetProtocols(GType)
635 {
636     static const char* protocols[] = {"http", "https", "blob", 0 };
637     return protocols;
638 }
639
640 static gchar* webKitWebSrcGetUri(GstURIHandler* handler)
641 {
642     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
643     gchar* ret;
644
645     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
646     ret = g_strdup(src->priv->uri);
647     return ret;
648 }
649
650 static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri, GError** error)
651 {
652     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
653     WebKitWebSrcPrivate* priv = src->priv;
654
655     if (GST_STATE(src) >= GST_STATE_PAUSED) {
656         GST_ERROR_OBJECT(src, "URI can only be set in states < PAUSED");
657         return FALSE;
658     }
659
660     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
661
662     g_free(priv->uri);
663     priv->uri = 0;
664
665     if (!uri)
666         return TRUE;
667
668     URL url(URL(), uri);
669     if (!urlHasSupportedProtocol(url)) {
670         g_set_error(error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI, "Invalid URI '%s'", uri);
671         return FALSE;
672     }
673
674     priv->uri = g_strdup(url.string().utf8().data());
675     return TRUE;
676 }
677
678 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer)
679 {
680     GstURIHandlerInterface* iface = (GstURIHandlerInterface *) gIface;
681
682     iface->get_type = webKitWebSrcUriGetType;
683     iface->get_protocols = webKitWebSrcGetProtocols;
684     iface->get_uri = webKitWebSrcGetUri;
685     iface->set_uri = webKitWebSrcSetUri;
686 }
687
688 // appsrc callbacks
689
690 static gboolean webKitWebSrcNeedDataMainCb(WebKitWebSrc* src)
691 {
692     WebKitWebSrcPrivate* priv = src->priv;
693
694     ASSERT(isMainThread());
695
696     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
697     // already stopped
698     if (!priv->needDataID)
699         return FALSE;
700
701     priv->paused = FALSE;
702     priv->needDataID = 0;
703     locker.unlock();
704
705     if (priv->client)
706         priv->client->setDefersLoading(false);
707     return FALSE;
708 }
709
710 static void webKitWebSrcNeedDataCb(GstAppSrc*, guint length, gpointer userData)
711 {
712     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
713     WebKitWebSrcPrivate* priv = src->priv;
714
715     GST_DEBUG_OBJECT(src, "Need more data: %u", length);
716
717     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
718     if (priv->needDataID || !priv->paused) {
719         return;
720     }
721
722     priv->needDataID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcNeedDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
723 }
724
725 static gboolean webKitWebSrcEnoughDataMainCb(WebKitWebSrc* src)
726 {
727     WebKitWebSrcPrivate* priv = src->priv;
728
729     ASSERT(isMainThread());
730
731     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
732     // already stopped
733     if (!priv->enoughDataID)
734         return FALSE;
735
736     priv->paused = TRUE;
737     priv->enoughDataID = 0;
738     locker.unlock();
739
740     if (priv->client)
741         priv->client->setDefersLoading(true);
742     return FALSE;
743 }
744
745 static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData)
746 {
747     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
748     WebKitWebSrcPrivate* priv = src->priv;
749
750     GST_DEBUG_OBJECT(src, "Have enough data");
751
752     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
753     if (priv->enoughDataID || priv->paused) {
754         return;
755     }
756
757     priv->enoughDataID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcEnoughDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
758 }
759
760 static gboolean webKitWebSrcSeekMainCb(WebKitWebSrc* src)
761 {
762     WebKitWebSrcPrivate* priv = src->priv;
763
764     ASSERT(isMainThread());
765
766     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
767     // already stopped
768     if (!priv->seekID)
769         return FALSE;
770     locker.unlock();
771
772     webKitWebSrcStop(src);
773     webKitWebSrcStart(src);
774
775     return FALSE;
776 }
777
778 static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData)
779 {
780     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
781     WebKitWebSrcPrivate* priv = src->priv;
782
783     GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, offset);
784     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
785     if (offset == priv->offset && priv->requestedOffset == priv->offset)
786         return TRUE;
787
788     if (!priv->seekable)
789         return FALSE;
790
791     GST_DEBUG_OBJECT(src, "Doing range-request seek");
792     priv->requestedOffset = offset;
793
794     if (priv->seekID)
795         g_source_remove(priv->seekID);
796     priv->seekID = g_idle_add_full(G_PRIORITY_DEFAULT, (GSourceFunc) webKitWebSrcSeekMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
797     return TRUE;
798 }
799
800 void webKitWebSrcSetMediaPlayer(WebKitWebSrc* src, WebCore::MediaPlayer* player)
801 {
802     ASSERT(player);
803     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
804     src->priv->player = player;
805 }
806
807 StreamingClient::StreamingClient(WebKitWebSrc* src)
808     : m_src(adoptGRef(static_cast<GstElement*>(gst_object_ref(src))))
809 {
810 }
811
812 StreamingClient::~StreamingClient()
813 {
814 }
815
816 char* StreamingClient::createReadBuffer(size_t requestedSize, size_t& actualSize)
817 {
818     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
819     WebKitWebSrcPrivate* priv = src->priv;
820
821     ASSERT(!priv->buffer);
822
823     GstBuffer* buffer = gst_buffer_new_and_alloc(requestedSize);
824
825     mapGstBuffer(buffer);
826
827     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
828     priv->buffer = adoptGRef(buffer);
829     locker.unlock();
830
831     actualSize = gst_buffer_get_size(buffer);
832     return getGstBufferDataPointer(buffer);
833 }
834
835 void StreamingClient::handleResponseReceived(const ResourceResponse& response)
836 {
837     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
838     WebKitWebSrcPrivate* priv = src->priv;
839
840     GST_DEBUG_OBJECT(src, "Received response: %d", response.httpStatusCode());
841
842     if (response.httpStatusCode() >= 400) {
843         // Received error code
844         GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received %d HTTP error code", response.httpStatusCode()), (0));
845         gst_app_src_end_of_stream(priv->appsrc);
846         webKitWebSrcStop(src);
847         return;
848     }
849
850     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
851
852     if (priv->seekID) {
853         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring response");
854         return;
855     }
856
857     if (priv->requestedOffset) {
858         // Seeking ... we expect a 206 == PARTIAL_CONTENT
859         if (response.httpStatusCode() == 200) {
860             // Range request didn't have a ranged response; resetting offset.
861             priv->offset = 0;
862         } else if (response.httpStatusCode() != 206) {
863             // Range request completely failed.
864             locker.unlock();
865             GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received unexpected %d HTTP status code", response.httpStatusCode()), (0));
866             gst_app_src_end_of_stream(priv->appsrc);
867             webKitWebSrcStop(src);
868             return;
869         }
870     }
871
872     long long length = response.expectedContentLength();
873     if (length > 0 && priv->requestedOffset && response.httpStatusCode() == 206)
874         length += priv->requestedOffset;
875
876     priv->size = length >= 0 ? length : 0;
877     priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField("Accept-Ranges").utf8().data());
878
879     GstTagList* tags = gst_tag_list_new_empty();
880     String value = response.httpHeaderField("icy-name");
881     if (!value.isEmpty()) {
882         g_free(priv->iradioName);
883         priv->iradioName = g_strdup(value.utf8().data());
884         g_object_notify(G_OBJECT(src), "iradio-name");
885         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
886     }
887     value = response.httpHeaderField("icy-genre");
888     if (!value.isEmpty()) {
889         g_free(priv->iradioGenre);
890         priv->iradioGenre = g_strdup(value.utf8().data());
891         g_object_notify(G_OBJECT(src), "iradio-genre");
892         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
893     }
894     value = response.httpHeaderField("icy-url");
895     if (!value.isEmpty()) {
896         g_free(priv->iradioUrl);
897         priv->iradioUrl = g_strdup(value.utf8().data());
898         g_object_notify(G_OBJECT(src), "iradio-url");
899         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
900     }
901     value = response.httpHeaderField("icy-title");
902     if (!value.isEmpty()) {
903         g_free(priv->iradioTitle);
904         priv->iradioTitle = g_strdup(value.utf8().data());
905         g_object_notify(G_OBJECT(src), "iradio-title");
906         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
907     }
908
909     locker.unlock();
910
911     // notify size/duration
912     if (length > 0) {
913         gst_app_src_set_size(priv->appsrc, length);
914     } else
915         gst_app_src_set_size(priv->appsrc, -1);
916
917     // icecast stuff
918     value = response.httpHeaderField("icy-metaint");
919     if (!value.isEmpty()) {
920         gchar* endptr = 0;
921         gint64 icyMetaInt = g_ascii_strtoll(value.utf8().data(), &endptr, 10);
922
923         if (endptr && *endptr == '\0' && icyMetaInt > 0) {
924             GRefPtr<GstCaps> caps = adoptGRef(gst_caps_new_simple("application/x-icy", "metadata-interval", G_TYPE_INT, (gint) icyMetaInt, NULL));
925
926             gst_app_src_set_caps(priv->appsrc, caps.get());
927         }
928     } else
929         gst_app_src_set_caps(priv->appsrc, 0);
930
931     // notify tags
932     if (gst_tag_list_is_empty(tags))
933         gst_tag_list_unref(tags);
934     else
935         gst_pad_push_event(priv->srcpad, gst_event_new_tag(tags));
936 }
937
938 void StreamingClient::handleDataReceived(const char* data, int length)
939 {
940     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
941     WebKitWebSrcPrivate* priv = src->priv;
942
943     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
944
945     GST_LOG_OBJECT(src, "Have %lld bytes of data", priv->buffer ? static_cast<long long>(gst_buffer_get_size(priv->buffer.get())) : length);
946
947     ASSERT(!priv->buffer || data == getGstBufferDataPointer(priv->buffer.get()));
948
949     if (priv->buffer)
950         unmapGstBuffer(priv->buffer.get());
951
952     if (priv->seekID) {
953         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring data");
954         priv->buffer.clear();
955         return;
956     }
957
958     if (priv->offset < priv->requestedOffset) {
959         // Range request failed; seeking manually.
960         if (priv->offset + length <= priv->requestedOffset) {
961             // Discard all the buffers coming before the requested seek position.
962             priv->offset += length;
963             priv->buffer.clear();
964             return;
965         }
966
967         if (priv->offset + length > priv->requestedOffset) {
968             guint64 offset = priv->requestedOffset - priv->offset;
969             data += offset;
970             length -= offset;
971             if (priv->buffer)
972                 gst_buffer_resize(priv->buffer.get(), offset, -1);
973             priv->offset = priv->requestedOffset;
974         }
975
976         priv->requestedOffset = 0;
977     }
978
979     // Ports using the GStreamer backend but not the soup implementation of ResourceHandle
980     // won't be using buffers provided by this client, the buffer is created here in that case.
981     if (!priv->buffer)
982         priv->buffer = adoptGRef(createGstBufferForData(data, length));
983     else
984         gst_buffer_set_size(priv->buffer.get(), static_cast<gssize>(length));
985
986     GST_BUFFER_OFFSET(priv->buffer.get()) = priv->offset;
987     if (priv->requestedOffset == priv->offset)
988         priv->requestedOffset += length;
989     priv->offset += length;
990     // priv->size == 0 if received length on didReceiveResponse < 0.
991     if (priv->size > 0 && priv->offset > priv->size) {
992         GST_DEBUG_OBJECT(src, "Updating internal size from %" G_GUINT64_FORMAT " to %" G_GUINT64_FORMAT, priv->size, priv->offset);
993         gst_app_src_set_size(priv->appsrc, priv->offset);
994         priv->size = priv->offset;
995     }
996     GST_BUFFER_OFFSET_END(priv->buffer.get()) = priv->offset;
997
998     locker.unlock();
999
1000     GstFlowReturn ret = gst_app_src_push_buffer(priv->appsrc, priv->buffer.leakRef());
1001     if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
1002         GST_ELEMENT_ERROR(src, CORE, FAILED, (0), (0));
1003 }
1004
1005 void StreamingClient::handleNotifyFinished()
1006 {
1007     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1008     WebKitWebSrcPrivate* priv = src->priv;
1009
1010     GST_DEBUG_OBJECT(src, "Have EOS");
1011
1012     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1013     if (!priv->seekID) {
1014         locker.unlock();
1015         gst_app_src_end_of_stream(priv->appsrc);
1016     }
1017 }
1018
1019 CachedResourceStreamingClient::CachedResourceStreamingClient(WebKitWebSrc* src, CachedResourceLoader* resourceLoader, const ResourceRequest& request)
1020     : StreamingClient(src)
1021 {
1022     DataBufferingPolicy bufferingPolicy = request.url().protocolIs("blob") ? BufferData : DoNotBufferData;
1023     CachedResourceRequest cacheRequest(request, ResourceLoaderOptions(SendCallbacks, DoNotSniffContent, bufferingPolicy, DoNotAllowStoredCredentials, DoNotAskClientForCrossOriginCredentials, DoSecurityCheck, UseDefaultOriginRestrictionsForType));
1024     m_resource = resourceLoader->requestRawResource(cacheRequest);
1025     if (m_resource)
1026         m_resource->addClient(this);
1027 }
1028
1029 CachedResourceStreamingClient::~CachedResourceStreamingClient()
1030 {
1031     if (m_resource) {
1032         m_resource->removeClient(this);
1033         m_resource = 0;
1034     }
1035 }
1036
1037 bool CachedResourceStreamingClient::loadFailed() const
1038 {
1039     return !m_resource;
1040 }
1041
1042 void CachedResourceStreamingClient::setDefersLoading(bool defers)
1043 {
1044     if (m_resource)
1045         m_resource->setDefersLoading(defers);
1046 }
1047
1048 char* CachedResourceStreamingClient::getOrCreateReadBuffer(CachedResource*, size_t requestedSize, size_t& actualSize)
1049 {
1050     return createReadBuffer(requestedSize, actualSize);
1051 }
1052
1053 void CachedResourceStreamingClient::responseReceived(CachedResource*, const ResourceResponse& response)
1054 {
1055     handleResponseReceived(response);
1056 }
1057
1058 void CachedResourceStreamingClient::dataReceived(CachedResource*, const char* data, int length)
1059 {
1060     handleDataReceived(data, length);
1061 }
1062
1063 void CachedResourceStreamingClient::notifyFinished(CachedResource* resource)
1064 {
1065     if (resource->loadFailedOrCanceled()) {
1066         WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1067
1068         if (!resource->wasCanceled()) {
1069             const ResourceError& error = resource->resourceError();
1070             GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
1071             GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
1072         }
1073         gst_app_src_end_of_stream(src->priv->appsrc);
1074         return;
1075     }
1076
1077     handleNotifyFinished();
1078 }
1079
1080 ResourceHandleStreamingClient::ResourceHandleStreamingClient(WebKitWebSrc* src, const ResourceRequest& request)
1081     : StreamingClient(src)
1082 {
1083     m_resource = ResourceHandle::create(0 /*context*/, request, this, false, false);
1084 }
1085
1086 ResourceHandleStreamingClient::~ResourceHandleStreamingClient()
1087 {
1088     if (m_resource) {
1089         m_resource->cancel();
1090         m_resource.release();
1091         m_resource = 0;
1092     }
1093 }
1094
1095 bool ResourceHandleStreamingClient::loadFailed() const
1096 {
1097     return !m_resource;
1098 }
1099
1100 void ResourceHandleStreamingClient::setDefersLoading(bool defers)
1101 {
1102     if (m_resource)
1103         m_resource->setDefersLoading(defers);
1104 }
1105
1106 char* ResourceHandleStreamingClient::getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize)
1107 {
1108     return createReadBuffer(requestedSize, actualSize);
1109 }
1110
1111 void ResourceHandleStreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
1112 {
1113 }
1114
1115 void ResourceHandleStreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
1116 {
1117     handleResponseReceived(response);
1118 }
1119
1120 void ResourceHandleStreamingClient::didReceiveData(ResourceHandle*, const char* data, int length, int)
1121 {
1122     ASSERT_NOT_REACHED();
1123 }
1124
1125 void ResourceHandleStreamingClient::didReceiveBuffer(ResourceHandle*, PassRefPtr<SharedBuffer> buffer, int /* encodedLength */)
1126 {
1127     // This pattern is suggested by SharedBuffer.h.
1128     const char* segment;
1129     unsigned position = 0;
1130     while (unsigned length = buffer->getSomeData(segment, position)) {
1131         handleDataReceived(segment, length);
1132         position += length;
1133     }
1134 }
1135
1136 void ResourceHandleStreamingClient::didFinishLoading(ResourceHandle*, double)
1137 {
1138     handleNotifyFinished();
1139 }
1140
1141 void ResourceHandleStreamingClient::didFail(ResourceHandle*, const ResourceError& error)
1142 {
1143     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1144
1145     GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
1146     GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
1147     gst_app_src_end_of_stream(src->priv->appsrc);
1148 }
1149
1150 void ResourceHandleStreamingClient::wasBlocked(ResourceHandle*)
1151 {
1152     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1153     GOwnPtr<gchar> uri;
1154
1155     GST_ERROR_OBJECT(src, "Request was blocked");
1156
1157     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1158     uri.set(g_strdup(src->priv->uri));
1159     locker.unlock();
1160
1161     GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", uri.get()), (0));
1162 }
1163
1164 void ResourceHandleStreamingClient::cannotShowURL(ResourceHandle*)
1165 {
1166     WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1167     GOwnPtr<gchar> uri;
1168
1169     GST_ERROR_OBJECT(src, "Cannot show URL");
1170
1171     GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
1172     uri.set(g_strdup(src->priv->uri));
1173     locker.unlock();
1174
1175     GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", uri.get()), (0));
1176 }
1177
1178 #endif // USE(GSTREAMER)
1179