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