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