[GStreamer] webkitwebsrc: avoid GST_BOILERPLATE_FULL
[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     GstPadTemplate* padTemplate = gst_static_pad_template_get(&srcTemplate);
216     GstPad* targetpad;
217     WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC_GET_PRIVATE(src);
218
219     src->priv = priv;
220
221     priv->client = new StreamingClient(src);
222
223     priv->appsrc = GST_APP_SRC(gst_element_factory_make("appsrc", 0));
224     if (!priv->appsrc) {
225         GST_ERROR_OBJECT(src, "Failed to create appsrc");
226         return;
227     }
228
229     GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(priv->appsrc)->elementfactory);
230     priv->haveAppSrc27 = gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 27);
231
232     gst_bin_add(GST_BIN(src), GST_ELEMENT(priv->appsrc));
233
234
235     targetpad = gst_element_get_static_pad(GST_ELEMENT(priv->appsrc), "src");
236     priv->srcpad = gst_ghost_pad_new_from_template("src", targetpad, padTemplate);
237     gst_object_unref(targetpad);
238
239     gst_element_add_pad(GST_ELEMENT(src), priv->srcpad);
240     gst_pad_set_query_function(priv->srcpad, webKitWebSrcQuery);
241
242     gst_app_src_set_callbacks(priv->appsrc, &appsrcCallbacks, src, 0);
243     gst_app_src_set_emit_signals(priv->appsrc, FALSE);
244     gst_app_src_set_stream_type(priv->appsrc, GST_APP_STREAM_TYPE_SEEKABLE);
245
246     // 512k is a abitrary number but we should choose a value
247     // here to not pause/unpause the SoupMessage too often and
248     // to make sure there's always some data available for
249     // GStreamer to handle.
250     gst_app_src_set_max_bytes(priv->appsrc, 512 * 1024);
251
252     // Emit the need-data signal if the queue contains less
253     // than 20% of data. Without this the need-data signal
254     // is emitted when the queue is empty, we then dispatch
255     // the soup message unpausing to the main loop and from
256     // there unpause the soup message. This already takes
257     // quite some time and libsoup even needs some more time
258     // to actually provide data again. If we do all this
259     // already if the queue is 20% empty, it's much more
260     // likely that libsoup already provides new data before
261     // the queue is really empty.
262     // This might need tweaking for ports not using libsoup.
263     if (priv->haveAppSrc27)
264         g_object_set(priv->appsrc, "min-percent", 20, NULL);
265
266     webKitWebSrcStop(src, false);
267 }
268
269 static void webKitWebSrcFinalize(GObject* object)
270 {
271     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
272     WebKitWebSrcPrivate* priv = src->priv;
273
274     delete priv->client;
275
276     g_free(priv->uri);
277
278     GST_CALL_PARENT(G_OBJECT_CLASS, finalize, ((GObject* )(src)));
279 }
280
281 static void webKitWebSrcSetProperty(GObject* object, guint propID, const GValue* value, GParamSpec* pspec)
282 {
283     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
284     WebKitWebSrcPrivate* priv = src->priv;
285
286     switch (propID) {
287     case PROP_IRADIO_MODE:
288         priv->iradioMode = g_value_get_boolean(value);
289         break;
290     case PROP_LOCATION:
291         webKitWebSrcSetUri(reinterpret_cast<GstURIHandler*>(src), g_value_get_string(value));
292         break;
293     default:
294         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
295         break;
296     }
297 }
298
299 static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value, GParamSpec* pspec)
300 {
301     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
302     WebKitWebSrcPrivate* priv = src->priv;
303
304     switch (propID) {
305     case PROP_IRADIO_MODE:
306         g_value_set_boolean(value, priv->iradioMode);
307         break;
308     case PROP_IRADIO_NAME:
309         g_value_set_string(value, priv->iradioName);
310         break;
311     case PROP_IRADIO_GENRE:
312         g_value_set_string(value, priv->iradioGenre);
313         break;
314     case PROP_IRADIO_URL:
315         g_value_set_string(value, priv->iradioUrl);
316         break;
317     case PROP_IRADIO_TITLE:
318         g_value_set_string(value, priv->iradioTitle);
319         break;
320     case PROP_LOCATION:
321         g_value_set_string(value, webKitWebSrcGetUri(reinterpret_cast<GstURIHandler*>(src)));
322         break;
323     default:
324         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
325         break;
326     }
327 }
328
329
330 static void webKitWebSrcStop(WebKitWebSrc* src, bool seeking)
331 {
332     WebKitWebSrcPrivate* priv = src->priv;
333
334     if (priv->resourceHandle) {
335         priv->resourceHandle->cancel();
336         priv->resourceHandle.release();
337     }
338     priv->resourceHandle = 0;
339
340     if (priv->frame && !seeking)
341         priv->frame.release();
342
343     GST_OBJECT_LOCK(src);
344     if (priv->needDataID)
345         g_source_remove(priv->needDataID);
346     priv->needDataID = 0;
347
348     if (priv->enoughDataID)
349         g_source_remove(priv->enoughDataID);
350     priv->enoughDataID = 0;
351
352     if (priv->seekID)
353         g_source_remove(priv->seekID);
354     priv->seekID = 0;
355
356     priv->paused = FALSE;
357     GST_OBJECT_UNLOCK(src);
358
359     g_free(priv->iradioName);
360     priv->iradioName = 0;
361
362     g_free(priv->iradioGenre);
363     priv->iradioGenre = 0;
364
365     g_free(priv->iradioUrl);
366     priv->iradioUrl = 0;
367
368     g_free(priv->iradioTitle);
369     priv->iradioTitle = 0;
370
371     if (priv->appsrc) {
372         gst_app_src_set_caps(priv->appsrc, 0);
373         if (!seeking)
374             gst_app_src_set_size(priv->appsrc, -1);
375     }
376
377     priv->offset = 0;
378     priv->seekable = FALSE;
379
380     if (!seeking) {
381         priv->size = 0;
382         priv->requestedOffset = 0;
383     }
384
385     GST_DEBUG_OBJECT(src, "Stopped request");
386 }
387
388 static bool webKitWebSrcStart(WebKitWebSrc* src)
389 {
390     WebKitWebSrcPrivate* priv = src->priv;
391
392     if (!priv->uri) {
393         GST_ERROR_OBJECT(src, "No URI provided");
394         return false;
395     }
396     
397     KURL url = KURL(KURL(), priv->uri);
398
399     ResourceRequest request(url);
400     request.setAllowCookies(true);
401
402     NetworkingContext* context = 0;
403     if (priv->frame) {
404         Document* document = priv->frame->document();
405         if (document)
406             request.setHTTPReferrer(document->documentURI());
407
408         FrameLoader* loader = priv->frame->loader();
409         if (loader) {
410             loader->addExtraFieldsToSubresourceRequest(request);
411             context = loader->networkingContext();
412         }
413     }
414
415     // Let Apple web servers know we want to access their nice movie trailers.
416     if (!g_ascii_strcasecmp("movies.apple.com", url.host().utf8().data())
417         || !g_ascii_strcasecmp("trailers.apple.com", url.host().utf8().data()))
418         request.setHTTPUserAgent("Quicktime/7.6.6");
419
420     if (priv->requestedOffset) {
421         GOwnPtr<gchar> val;
422
423         val.set(g_strdup_printf("bytes=%" G_GUINT64_FORMAT "-", priv->requestedOffset));
424         request.setHTTPHeaderField("Range", val.get());
425     }
426
427     if (priv->iradioMode)
428         request.setHTTPHeaderField("icy-metadata", "1");
429
430     // Needed to use DLNA streaming servers
431     request.setHTTPHeaderField("transferMode.dlna", "Streaming");
432
433     priv->resourceHandle = ResourceHandle::create(context, request, priv->client, false, false);
434     if (!priv->resourceHandle) {
435         GST_ERROR_OBJECT(src, "Failed to create ResourceHandle");
436         return false;
437     }
438
439     GST_DEBUG_OBJECT(src, "Started request");
440
441     return true;
442 }
443
444 static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStateChange transition)
445 {
446     GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
447     WebKitWebSrc* src = WEBKIT_WEB_SRC(element);
448     WebKitWebSrcPrivate* priv = src->priv;
449
450     switch (transition) {
451     case GST_STATE_CHANGE_NULL_TO_READY:
452         if (!priv->appsrc) {
453             gst_element_post_message(element,
454                                      gst_missing_element_message_new(element, "appsrc"));
455             GST_ELEMENT_ERROR(src, CORE, MISSING_PLUGIN, (0), ("no appsrc"));
456             return GST_STATE_CHANGE_FAILURE;
457         }
458         break;
459     default:
460         break;
461     }
462
463     ret = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition);
464     if (G_UNLIKELY(ret == GST_STATE_CHANGE_FAILURE)) {
465         GST_DEBUG_OBJECT(src, "State change failed");
466         return ret;
467     }
468
469     switch (transition) {
470     case GST_STATE_CHANGE_READY_TO_PAUSED:
471         GST_DEBUG_OBJECT(src, "READY->PAUSED");
472         if (!webKitWebSrcStart(src))
473             ret = GST_STATE_CHANGE_FAILURE;
474         break;
475     case GST_STATE_CHANGE_PAUSED_TO_READY:
476         GST_DEBUG_OBJECT(src, "PAUSED->READY");
477         webKitWebSrcStop(src, false);
478         break;
479     default:
480         break;
481     }
482
483     return ret;
484 }
485
486 static gboolean webKitWebSrcQuery(GstPad* pad, GstQuery* query)
487 {
488     GRefPtr<GstElement> src = adoptGRef(gst_pad_get_parent_element(pad));
489     WebKitWebSrc* webkitSrc = WEBKIT_WEB_SRC(src.get());
490     gboolean result = FALSE;
491
492     switch (GST_QUERY_TYPE(query)) {
493     case GST_QUERY_DURATION:
494     {
495         GstFormat format;
496
497         gst_query_parse_duration(query, &format, NULL);
498
499         GST_DEBUG_OBJECT(webkitSrc, "duration query in format %s", gst_format_get_name(format));
500         if ((format == GST_FORMAT_BYTES) && (webkitSrc->priv->size > 0)) {
501             gst_query_set_duration(query, format, webkitSrc->priv->size);
502             result = TRUE;
503         }
504         break;
505     }
506     case GST_QUERY_URI:
507     {
508         gst_query_set_uri(query, webkitSrc->priv->uri);
509         result = TRUE;
510         break;
511     }
512     default:
513         break;
514     }
515
516     if (!result)
517         result = gst_pad_query_default(pad, query);
518
519     return result;
520 }
521
522 // uri handler interface
523
524 static GstURIType webKitWebSrcUriGetType(void)
525 {
526     return GST_URI_SRC;
527 }
528
529 static gchar** webKitWebSrcGetProtocols(void)
530 {
531     static gchar* protocols[] = {(gchar*) "http", (gchar*) "https", 0 };
532
533     return protocols;
534 }
535
536 static const gchar* webKitWebSrcGetUri(GstURIHandler* handler)
537 {
538     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
539     WebKitWebSrcPrivate* priv = src->priv;
540
541     return priv->uri;
542 }
543
544 static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri)
545 {
546     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
547     WebKitWebSrcPrivate* priv = src->priv;
548
549     if (GST_STATE(src) >= GST_STATE_PAUSED) {
550         GST_ERROR_OBJECT(src, "URI can only be set in states < PAUSED");
551         return FALSE;
552     }
553
554     g_free(priv->uri);
555     priv->uri = 0;
556
557     if (!uri)
558         return TRUE;
559
560     KURL url(KURL(), uri);
561
562     if (!url.isValid() || !url.protocolInHTTPFamily()) {
563         GST_ERROR_OBJECT(src, "Invalid URI '%s'", uri);
564         return FALSE;
565     }
566
567     priv->uri = g_strdup(url.string().utf8().data());
568     return TRUE;
569 }
570
571 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer ifaceData)
572 {
573     GstURIHandlerInterface* iface = (GstURIHandlerInterface *) gIface;
574
575     iface->get_type = webKitWebSrcUriGetType;
576     iface->get_protocols = webKitWebSrcGetProtocols;
577     iface->get_uri = webKitWebSrcGetUri;
578     iface->set_uri = webKitWebSrcSetUri;
579 }
580
581 // appsrc callbacks
582
583 static gboolean webKitWebSrcNeedDataMainCb(WebKitWebSrc* src)
584 {
585     WebKitWebSrcPrivate* priv = src->priv;
586
587     priv->resourceHandle->setDefersLoading(false);
588
589     GST_OBJECT_LOCK(src);
590     priv->paused = FALSE;
591     priv->needDataID = 0;
592     GST_OBJECT_UNLOCK(src);
593     return FALSE;
594 }
595
596 static void webKitWebSrcNeedDataCb(GstAppSrc* appsrc, guint length, gpointer userData)
597 {
598     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
599     WebKitWebSrcPrivate* priv = src->priv;
600
601     GST_DEBUG_OBJECT(src, "Need more data: %u", length);
602
603     GST_OBJECT_LOCK(src);
604     if (priv->needDataID || !priv->paused) {
605         GST_OBJECT_UNLOCK(src);
606         return;
607     }
608
609     priv->needDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcNeedDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
610     GST_OBJECT_UNLOCK(src);
611 }
612
613 static gboolean webKitWebSrcEnoughDataMainCb(WebKitWebSrc* src)
614 {
615     WebKitWebSrcPrivate* priv = src->priv;
616
617     priv->resourceHandle->setDefersLoading(true);
618
619     GST_OBJECT_LOCK(src);
620     priv->paused = TRUE;
621     priv->enoughDataID = 0;
622     GST_OBJECT_UNLOCK(src);
623
624     return FALSE;
625 }
626
627 static void webKitWebSrcEnoughDataCb(GstAppSrc* appsrc, gpointer userData)
628 {
629     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
630     WebKitWebSrcPrivate* priv = src->priv;
631
632     GST_DEBUG_OBJECT(src, "Have enough data");
633
634     GST_OBJECT_LOCK(src);
635     if (priv->enoughDataID || priv->paused) {
636         GST_OBJECT_UNLOCK(src);
637         return;
638     }
639
640     priv->enoughDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcEnoughDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
641     GST_OBJECT_UNLOCK(src);
642 }
643
644 static gboolean webKitWebSrcSeekMainCb(WebKitWebSrc* src)
645 {
646     webKitWebSrcStop(src, true);
647     webKitWebSrcStart(src);
648
649     return FALSE;
650 }
651
652 static gboolean webKitWebSrcSeekDataCb(GstAppSrc* appsrc, guint64 offset, gpointer userData)
653 {
654     WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
655     WebKitWebSrcPrivate* priv = src->priv;
656
657     GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, offset);
658     if (offset == priv->offset)
659         return TRUE;
660
661     if (!priv->seekable)
662         return FALSE;
663     if (offset > priv->size)
664         return FALSE;
665
666     GST_DEBUG_OBJECT(src, "Doing range-request seek");
667     priv->requestedOffset = offset;
668
669     GST_OBJECT_LOCK(src);
670     if (priv->seekID)
671         g_source_remove(priv->seekID);
672     priv->seekID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcSeekMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
673     GST_OBJECT_UNLOCK(src);
674     
675     return TRUE;
676 }
677
678 void webKitWebSrcSetFrame(WebKitWebSrc* src, WebCore::Frame* frame)
679 {
680     WebKitWebSrcPrivate* priv = src->priv;
681
682     priv->frame = frame;
683 }
684
685 StreamingClient::StreamingClient(WebKitWebSrc* src) : m_src(src)
686 {
687
688 }
689
690 StreamingClient::~StreamingClient()
691 {
692
693 }
694
695 void StreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
696 {
697 }
698
699 void StreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
700 {
701     WebKitWebSrcPrivate* priv = m_src->priv;
702
703     GST_DEBUG_OBJECT(m_src, "Received response: %d", response.httpStatusCode());
704
705     // If we seeked we need 206 == PARTIAL_CONTENT
706     if (priv->requestedOffset && response.httpStatusCode() != 206) {
707         GST_ELEMENT_ERROR(m_src, RESOURCE, READ, (0), (0));
708         gst_app_src_end_of_stream(priv->appsrc);
709         webKitWebSrcStop(m_src, false);
710         return;
711     }
712
713     long long length = response.expectedContentLength();
714     if (length > 0) {
715         length += priv->requestedOffset;
716         gst_app_src_set_size(priv->appsrc, length);
717         if (!priv->haveAppSrc27) {
718             gst_segment_set_duration(&GST_BASE_SRC(priv->appsrc)->segment, GST_FORMAT_BYTES, length);
719             gst_element_post_message(GST_ELEMENT(priv->appsrc),
720                                      gst_message_new_duration(GST_OBJECT(priv->appsrc),
721                                                               GST_FORMAT_BYTES, length));
722         }
723     }
724
725     priv->size = length >= 0 ? length : 0;
726     priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField("Accept-Ranges").utf8().data());
727
728     // icecast stuff
729     String value = response.httpHeaderField("icy-metaint");
730     if (!value.isEmpty()) {
731         gchar* endptr = 0;
732         gint64 icyMetaInt = g_ascii_strtoll(value.utf8().data(), &endptr, 10);
733             
734         if (endptr && *endptr == '\0' && icyMetaInt > 0) {
735             GstCaps* caps = gst_caps_new_simple("application/x-icy", "metadata-interval", G_TYPE_INT, (gint) icyMetaInt, NULL);
736
737             gst_app_src_set_caps(priv->appsrc, caps);
738             gst_caps_unref(caps);
739         }
740     }
741
742     GstTagList* tags = gst_tag_list_new();
743     value = response.httpHeaderField("icy-name");
744     if (!value.isEmpty()) {
745         g_free(priv->iradioName);
746         priv->iradioName = g_strdup(value.utf8().data());
747         g_object_notify(G_OBJECT(m_src), "iradio-name");
748         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
749     }
750     value = response.httpHeaderField("icy-genre");
751     if (!value.isEmpty()) {
752         g_free(priv->iradioGenre);
753         priv->iradioGenre = g_strdup(value.utf8().data());
754         g_object_notify(G_OBJECT(m_src), "iradio-genre");
755         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
756     }
757     value = response.httpHeaderField("icy-url");
758     if (!value.isEmpty()) {
759         g_free(priv->iradioUrl);
760         priv->iradioUrl = g_strdup(value.utf8().data());
761         g_object_notify(G_OBJECT(m_src), "iradio-url");
762         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
763     }
764     value = response.httpHeaderField("icy-title");
765     if (!value.isEmpty()) {
766         g_free(priv->iradioTitle);
767         priv->iradioTitle = g_strdup(value.utf8().data());
768         g_object_notify(G_OBJECT(m_src), "iradio-title");
769         gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
770     }
771
772     if (gst_tag_list_is_empty(tags))
773         gst_tag_list_free(tags);
774     else
775         gst_element_found_tags_for_pad(GST_ELEMENT(m_src), m_src->priv->srcpad, tags);
776 }
777
778 void StreamingClient::didReceiveData(ResourceHandle* handle, const char* data, int length, int encodedDataLength)
779 {
780     WebKitWebSrcPrivate* priv = m_src->priv;
781
782     GST_LOG_OBJECT(m_src, "Have %d bytes of data", length);
783
784     if (priv->seekID || handle != priv->resourceHandle) {
785         GST_DEBUG_OBJECT(m_src, "Seek in progress, ignoring data");
786         return;
787     }
788
789     GstBuffer* buffer = gst_buffer_new_and_alloc(length);
790
791     memcpy(GST_BUFFER_DATA(buffer), data, length);
792     GST_BUFFER_OFFSET(buffer) = priv->offset;
793     priv->offset += length;
794     GST_BUFFER_OFFSET_END(buffer) = priv->offset;
795
796     GstFlowReturn ret = gst_app_src_push_buffer(priv->appsrc, buffer);
797     if (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED)
798         GST_ELEMENT_ERROR(m_src, CORE, FAILED, (0), (0));
799 }
800
801 void StreamingClient::didFinishLoading(ResourceHandle*, double)
802 {
803     WebKitWebSrcPrivate* priv = m_src->priv;
804
805     GST_DEBUG_OBJECT(m_src, "Have EOS");
806
807     if (!priv->seekID)
808         gst_app_src_end_of_stream(m_src->priv->appsrc);
809 }
810
811 void StreamingClient::didFail(ResourceHandle*, const ResourceError& error)
812 {
813     GST_ERROR_OBJECT(m_src, "Have failure: %s", error.localizedDescription().utf8().data());
814     GST_ELEMENT_ERROR(m_src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
815     gst_app_src_end_of_stream(m_src->priv->appsrc);
816 }
817
818 void StreamingClient::wasBlocked(ResourceHandle*)
819 {
820     GST_ERROR_OBJECT(m_src, "Request was blocked");
821     GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", m_src->priv->uri), (0));
822 }
823
824 void StreamingClient::cannotShowURL(ResourceHandle*)
825 {
826     GST_ERROR_OBJECT(m_src, "Cannot show URL");
827     GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", m_src->priv->uri), (0));
828 }
829
830 #endif // USE(GSTREAMER)
831