e8a601eafdfaff79c72a3a2b73059df9e32b80a2
[framework/web/webkit-efl.git] / Source / WebCore / platform / graphics / gstreamer / MediaPlayerPrivateGStreamer.cpp
1 /*
2  * Copyright (C) 2007, 2009 Apple Inc.  All rights reserved.
3  * Copyright (C) 2007 Collabora Ltd.  All rights reserved.
4  * Copyright (C) 2007 Alp Toker <alp@atoker.com>
5  * Copyright (C) 2009 Gustavo Noronha Silva <gns@gnome.org>
6  * Copyright (C) 2009, 2010 Igalia S.L
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * aint with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #include "config.h"
25 #include "MediaPlayerPrivateGStreamer.h"
26
27 #if ENABLE(VIDEO) && USE(GSTREAMER)
28
29 #include "ColorSpace.h"
30 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
31 #include "CookieJar.h"
32 #include <power.h>
33 #endif
34 #include "Document.h"
35 #include "Frame.h"
36 #include "FrameView.h"
37 #include "GStreamerGWorld.h"
38 #include "GStreamerUtilities.h"
39 #include "GStreamerVersioning.h"
40 #include "GraphicsContext.h"
41 #include "GraphicsTypes.h"
42 #if ENABLE(TIZEN_MEDIA_STREAM)
43 #include "HTMLMediaElement.h"
44 #endif
45 #include "ImageGStreamer.h"
46 #include "ImageOrientation.h"
47 #include "IntRect.h"
48 #include "KURL.h"
49 #include "MIMETypeRegistry.h"
50 #include "MediaPlayer.h"
51 #include "NotImplemented.h"
52 #include "SecurityOrigin.h"
53 #include "TimeRanges.h"
54 #include "VideoSinkGStreamer.h"
55 #include "WebKitWebSourceGStreamer.h"
56 #include <gst/gst.h>
57 #include <gst/video/video.h>
58 #include <limits>
59 #include <math.h>
60 #include <wtf/gobject/GOwnPtr.h>
61 #include <wtf/text/CString.h>
62
63 #ifdef GST_API_VERSION_1
64 #include <gst/audio/streamvolume.h>
65 #else
66 #include <gst/interfaces/streamvolume.h>
67 #endif
68
69 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
70 #include "Page.h"
71 #include "Settings.h"
72 #include "VideoLayerTizen.h"
73 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
74
75 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
76 #include "URIUtils.h"
77 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
78
79 #if ENABLE(TIZEN_MEDIA_STREAM)
80 #include "WebKitCameraSourceGStreamerTizen.h"
81 #endif // ENABLE(TIZEN_MEDIA_STREAM)
82
83 // GstPlayFlags flags from playbin2. It is the policy of GStreamer to
84 // not publicly expose element-specific enums. That's why this
85 // GstPlayFlags enum has been copied here.
86 typedef enum {
87     GST_PLAY_FLAG_VIDEO         = 0x00000001,
88     GST_PLAY_FLAG_AUDIO         = 0x00000002,
89     GST_PLAY_FLAG_TEXT          = 0x00000004,
90     GST_PLAY_FLAG_VIS           = 0x00000008,
91     GST_PLAY_FLAG_SOFT_VOLUME   = 0x00000010,
92     GST_PLAY_FLAG_NATIVE_AUDIO  = 0x00000020,
93     GST_PLAY_FLAG_NATIVE_VIDEO  = 0x00000040,
94     GST_PLAY_FLAG_DOWNLOAD      = 0x00000080,
95     GST_PLAY_FLAG_BUFFERING     = 0x000000100
96 } GstPlayFlags;
97
98 #ifdef GST_API_VERSION_1
99 static const char* gPlaybinName = "playbin";
100 #else
101 static const char* gPlaybinName = "playbin2";
102 #endif
103
104 GST_DEBUG_CATEGORY_STATIC(webkit_media_player_debug);
105 #define GST_CAT_DEFAULT webkit_media_player_debug
106
107 using namespace std;
108
109 namespace WebCore {
110
111 static int greatestCommonDivisor(int a, int b)
112 {
113     while (b) {
114         int temp = a;
115         a = b;
116         b = temp % b;
117     }
118
119     return ABS(a);
120 }
121
122 static gboolean mediaPlayerPrivateMessageCallback(GstBus*, GstMessage* message, MediaPlayerPrivateGStreamer* player)
123 {
124     return player->handleMessage(message);
125 }
126
127 static void mediaPlayerPrivateSourceChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
128 {
129     player->sourceChanged();
130 }
131
132 static void mediaPlayerPrivateVolumeChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
133 {
134     // This is called when playbin receives the notify::volume signal.
135     player->volumeChanged();
136 }
137
138 static gboolean mediaPlayerPrivateVolumeChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
139 {
140     // This is the callback of the timeout source created in ::volumeChanged.
141     player->notifyPlayerOfVolumeChange();
142     return FALSE;
143 }
144
145 static void mediaPlayerPrivateMuteChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
146 {
147     // This is called when playbin receives the notify::mute signal.
148     player->muteChanged();
149 }
150
151 static gboolean mediaPlayerPrivateMuteChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
152 {
153     // This is the callback of the timeout source created in ::muteChanged.
154     player->notifyPlayerOfMute();
155     return FALSE;
156 }
157
158 static void mediaPlayerPrivateVideoSinkCapsChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
159 {
160     player->videoChanged();
161 }
162
163 static void mediaPlayerPrivateVideoChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
164 {
165     player->videoChanged();
166 }
167
168 static void mediaPlayerPrivateAudioChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
169 {
170     player->audioChanged();
171 }
172
173 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
174 static void mediaPlayerPrivateSourceSetupCallback(GObject*, GstElement* source, MediaPlayerPrivateGStreamer* player)
175 {
176     HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->player()->mediaPlayerClient());
177
178     // Grab the current document
179     Document* document = element->document();
180     if (!document)
181         document = element->ownerDocument();
182
183     // Grab the frame and network manager
184     Frame* frame = document ? document->frame() : 0;
185     FrameLoader* frameLoader = frame ? frame->loader() : 0;
186
187     String cookie = cookies(document, player->url());
188     if (!cookie.length())
189         cookie = cookieRequestHeaderFieldValue(document, player->url());
190
191     GstStructure* headers = gst_structure_new("extra-headers", "Cookie", G_TYPE_STRING, cookie.utf8().data(), NULL);
192     g_object_set(source, "extra-headers", headers, NULL);
193     gst_structure_free(headers);
194
195 #if ENABLE(TIZEN_WEBKIT2_PROXY)
196     player->setProxy(source);
197 #endif
198
199     if (frameLoader)
200         g_object_set(source, "user-agent", frameLoader->userAgent(player->url()).utf8().data(), NULL);
201 }
202 #endif
203
204 static gboolean mediaPlayerPrivateAudioChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
205 {
206     // This is the callback of the timeout source created in ::audioChanged.
207     player->notifyPlayerOfAudio();
208     return FALSE;
209 }
210
211 static gboolean mediaPlayerPrivateVideoChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
212 {
213     // This is the callback of the timeout source created in ::videoChanged.
214     player->notifyPlayerOfVideo();
215     return FALSE;
216 }
217
218 #if ENABLE(TIZEN_GSTREAMER_VIDEO) && (!ENABLE(TIZEN_ACCELERATED_COMPOSITING) || !USE(TIZEN_TEXTURE_MAPPER) || !ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE) || CPU(X86) || CPU(X86_64))
219 static void mediaPlayerPrivateRepaintCallback(WebKitVideoSink*, GstBuffer *buffer, MediaPlayerPrivateGStreamer* playerPrivate)
220 {
221     playerPrivate->triggerRepaint(buffer);
222 }
223 #endif
224
225 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
226 static GstBusSyncReply mediaPlayerPrivateSyncHandler(GstBus* bus, GstMessage* message, MediaPlayerPrivateGStreamer* playerPrivate)
227 {
228     // ignore anything but 'prepare-xid' message
229     if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_ELEMENT)
230         return GST_BUS_PASS;
231     if (!gst_structure_has_name (message->structure, "prepare-xid"))
232         return GST_BUS_PASS;
233
234     playerPrivate->xWindowIdPrepared(message);
235     return GST_BUS_DROP;
236 }
237 #endif
238
239 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
240 static ASM_cb_result_t MediaPlayerAudioSessionEventSourcePause(ASM_event_sources_t eventSource, void* callbackData)
241 {
242     MediaPlayer* player = static_cast<MediaPlayer*>(callbackData);
243     HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->mediaPlayerClient());
244
245     if (!player)
246         return ASM_CB_RES_IGNORE;
247
248     switch (eventSource) {
249     case ASM_EVENT_SOURCE_CALL_START:
250     case ASM_EVENT_SOURCE_ALARM_START:
251     case ASM_EVENT_SOURCE_MEDIA:
252     case ASM_EVENT_SOURCE_EMERGENCY_START:
253     case ASM_EVENT_SOURCE_OTHER_PLAYER_APP:
254     case ASM_EVENT_SOURCE_RESOURCE_CONFLICT:
255     case ASM_EVENT_SOURCE_EARJACK_UNPLUG:
256         if (!player->url().string().contains("camera://")) {
257             element->pause();
258             return ASM_CB_RES_PAUSE;
259         }
260     default:
261         return ASM_CB_RES_NONE;
262     }
263 }
264
265 static ASM_cb_result_t MediaPlayerAudioSessionEventSourcePlay(ASM_event_sources_t eventSource, void* callbackData)
266 {
267     MediaPlayer* player = static_cast<MediaPlayer*>(callbackData);
268     HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->mediaPlayerClient());
269
270     if (!player)
271         return ASM_CB_RES_IGNORE;
272
273     switch (eventSource) {
274     case ASM_EVENT_SOURCE_ALARM_END:
275         if (!element->isVideo() && !player->url().string().contains("camera://")) {
276             element->play();
277             return ASM_CB_RES_PLAYING;
278         }
279         return ASM_CB_RES_NONE;
280     default:
281         return ASM_CB_RES_NONE;
282     }
283 }
284
285 static ASM_cb_result_t mediaPlayerPrivateAudioSessionNotifyCallback(int, ASM_event_sources_t eventSource, ASM_sound_commands_t command, unsigned int, void* callbackData)
286 {
287     if (command == ASM_COMMAND_STOP || command == ASM_COMMAND_PAUSE)
288         return MediaPlayerAudioSessionEventSourcePause(eventSource, callbackData);
289     if (command == ASM_COMMAND_PLAY || command == ASM_COMMAND_RESUME)
290         return MediaPlayerAudioSessionEventSourcePlay(eventSource, callbackData);
291
292     return ASM_CB_RES_NONE;
293 }
294 #endif
295
296 PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivateGStreamer::create(MediaPlayer* player)
297 {
298     return adoptPtr(new MediaPlayerPrivateGStreamer(player));
299 }
300
301 void MediaPlayerPrivateGStreamer::registerMediaEngine(MediaEngineRegistrar registrar)
302 {
303     if (isAvailable())
304         registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
305 }
306
307 bool initializeGStreamerAndRegisterWebKitElements()
308 {
309     if (!initializeGStreamer())
310         return false;
311
312     GRefPtr<GstElementFactory> srcFactory = gst_element_factory_find("webkitwebsrc");
313     if (!srcFactory)
314 #if ENABLE(TIZEN_MEDIA_STREAM)
315         return gst_element_register(0, "webkitcamerasrc", GST_RANK_PRIMARY + 200, WEBKIT_TYPE_CAMERA_SRC);
316 #else
317         GST_DEBUG_CATEGORY_INIT(webkit_media_player_debug, "webkitmediaplayer", 0, "WebKit media player");
318         return gst_element_register(0, "webkitwebsrc", GST_RANK_PRIMARY + 100, WEBKIT_TYPE_WEB_SRC);
319 #endif // ENABLE(TIZEN_MEDIA_STREAM)
320
321     return true;
322 }
323
324 bool MediaPlayerPrivateGStreamer::isAvailable()
325 {
326     if (!initializeGStreamerAndRegisterWebKitElements())
327         return false;
328
329     GRefPtr<GstElementFactory> factory = gst_element_factory_find(gPlaybinName);
330     return factory;
331 }
332
333 MediaPlayerPrivateGStreamer::MediaPlayerPrivateGStreamer(MediaPlayer* player)
334     : m_player(player)
335     , m_webkitVideoSink(0)
336 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
337     , m_videoSinkBin(0)
338 #endif
339     , m_fpsSink(0)
340     , m_source(0)
341     , m_seekTime(0)
342     , m_changingRate(false)
343     , m_endTime(numeric_limits<float>::infinity())
344     , m_isEndReached(false)
345     , m_networkState(MediaPlayer::Empty)
346     , m_readyState(MediaPlayer::HaveNothing)
347     , m_isStreaming(false)
348     , m_size(IntSize())
349     , m_buffer(0)
350     , m_mediaLocations(0)
351     , m_mediaLocationCurrentIndex(0)
352     , m_resetPipeline(false)
353     , m_paused(true)
354     , m_seeking(false)
355     , m_buffering(false)
356     , m_playbackRate(1)
357     , m_errorOccured(false)
358     , m_mediaDuration(0)
359     , m_startedBuffering(false)
360     , m_fillTimer(this, &MediaPlayerPrivateGStreamer::fillTimerFired)
361     , m_maxTimeLoaded(0)
362     , m_bufferingPercentage(0)
363     , m_preload(MediaPlayer::Auto)
364     , m_delayingLoad(false)
365     , m_mediaDurationKnown(true)
366     , m_maxTimeLoadedAtLastDidLoadingProgress(0)
367     , m_volumeTimerHandler(0)
368     , m_muteTimerHandler(0)
369     , m_hasVideo(false)
370     , m_hasAudio(false)
371     , m_audioTimerHandler(0)
372     , m_videoTimerHandler(0)
373     , m_webkitAudioSink(0)
374     , m_totalBytes(-1)
375 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
376     , m_videoLayer(VideoLayerTizen::create(static_cast<HTMLMediaElement*>(player->mediaPlayerClient())))
377 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
378 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
379     , m_audioSessionManager(AudioSessionManagerGStreamerTizen::createAudioSessionManager())
380 #endif
381     , m_originalPreloadWasAutoAndWasOverridden(false)
382     , m_preservesPitch(false)
383 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
384     , m_suspendTime(0)
385 #endif
386 {
387 }
388
389 MediaPlayerPrivateGStreamer::~MediaPlayerPrivateGStreamer()
390 {
391     if (m_fillTimer.isActive())
392         m_fillTimer.stop();
393
394     if (m_buffer)
395         gst_buffer_unref(m_buffer);
396     m_buffer = 0;
397
398     if (m_mediaLocations) {
399         gst_structure_free(m_mediaLocations);
400         m_mediaLocations = 0;
401     }
402
403 #ifndef GST_API_VERSION_1
404     if (m_videoSinkBin) {
405         gst_object_unref(m_videoSinkBin);
406         m_videoSinkBin = 0;
407     }
408 #endif
409
410     if (m_playBin) {
411         GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
412         ASSERT(bus);
413         g_signal_handlers_disconnect_by_func(bus.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateMessageCallback), this);
414         gst_bus_remove_signal_watch(bus.get());
415
416         gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
417         m_playBin = 0;
418     }
419
420     m_player = 0;
421
422 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
423     if (m_audioSessionManager)
424         m_audioSessionManager->setSoundState(ASM_STATE_STOP);
425 #endif
426
427     if (m_muteTimerHandler)
428         g_source_remove(m_muteTimerHandler);
429
430     if (m_volumeTimerHandler)
431         g_source_remove(m_volumeTimerHandler);
432
433     if (m_videoTimerHandler)
434         g_source_remove(m_videoTimerHandler);
435
436     if (m_audioTimerHandler)
437         g_source_remove(m_audioTimerHandler);
438 }
439
440 void MediaPlayerPrivateGStreamer::load(const String& url)
441 {
442     if (!initializeGStreamerAndRegisterWebKitElements())
443         return;
444
445 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
446     crackURI(url);
447 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
448     KURL kurl(KURL(), url);
449     String cleanUrl(url);
450
451     // Clean out everything after file:// url path.
452     if (kurl.isLocalFile())
453         cleanUrl = cleanUrl.substring(0, kurl.pathEnd());
454
455     if (!m_playBin) {
456         createGSTPlayBin();
457         setDownloadBuffering();
458     }
459
460     ASSERT(m_playBin);
461
462     m_url = KURL(KURL(), cleanUrl);
463     g_object_set(m_playBin.get(), "uri", cleanUrl.utf8().data(), NULL);
464
465     LOG_MEDIA_MESSAGE("Load %s", cleanUrl.utf8().data());
466
467 #if ENABLE(TIZEN_MEDIA_STREAM)
468     // Workaround modification for getUserMedia.
469     // When 'playing' event is fired videoWidth and videoHeight are not available.
470     // Set m_videoSize as frame size which comes from webkitCameraSource.
471     // This size is fixed.
472     if (isLocalMediaStream())
473         if (gst_element_factory_find("camerasrc"))
474             m_videoSize = IntSize(480, 640);
475         else
476             m_videoSize = IntSize(640, 480);
477 #endif
478
479     if (m_preload == MediaPlayer::None) {
480         LOG_MEDIA_MESSAGE("Delaying load.");
481         m_delayingLoad = true;
482     }
483
484     // Reset network and ready states. Those will be set properly once
485     // the pipeline pre-rolled.
486 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
487     if (!m_delayingLoad)
488         m_networkState = MediaPlayer::Loading;
489     else
490         m_networkState = MediaPlayer::Idle;
491 #else
492     m_networkState = MediaPlayer::Loading;
493 #endif
494     m_player->networkStateChanged();
495     m_readyState = MediaPlayer::HaveNothing;
496     m_player->readyStateChanged();
497     m_volumeAndMuteInitialized = false;
498
499     // GStreamer needs to have the pipeline set to a paused state to
500     // start providing anything useful.
501 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
502     if (!m_delayingLoad)
503 #endif
504     gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
505
506 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
507     if (m_audioSessionManager && !m_delayingLoad)
508         m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
509 #endif
510
511     if (!m_delayingLoad)
512         commitLoad();
513 }
514
515 void MediaPlayerPrivateGStreamer::commitLoad()
516 {
517     ASSERT(!m_delayingLoad);
518     LOG_MEDIA_MESSAGE("Committing load.");
519     updateStates();
520 }
521
522 float MediaPlayerPrivateGStreamer::playbackPosition() const
523 {
524     if (m_isEndReached) {
525         // Position queries on a null pipeline return 0. If we're at
526         // the end of the stream the pipeline is null but we want to
527         // report either the seek time or the duration because this is
528         // what the Media element spec expects us to do.
529         if (m_seeking)
530             return m_seekTime;
531         if (m_mediaDuration)
532             return m_mediaDuration;
533     }
534
535     float ret = 0.0f;
536
537     GstQuery* query = gst_query_new_position(GST_FORMAT_TIME);
538     if (!gst_element_query(m_playBin.get(), query)) {
539         LOG_MEDIA_MESSAGE("Position query failed...");
540         gst_query_unref(query);
541         return ret;
542     }
543
544     gint64 position;
545     gst_query_parse_position(query, 0, &position);
546
547     // Position is available only if the pipeline is not in GST_STATE_NULL or
548     // GST_STATE_READY state.
549     if (position != static_cast<gint64>(GST_CLOCK_TIME_NONE))
550         ret = static_cast<double>(position) / GST_SECOND;
551
552     LOG_MEDIA_MESSAGE("Position %" GST_TIME_FORMAT, GST_TIME_ARGS(position));
553
554     gst_query_unref(query);
555
556     return ret;
557 }
558
559 bool MediaPlayerPrivateGStreamer::changePipelineState(GstState newState)
560 {
561     ASSERT(newState == GST_STATE_PLAYING || newState == GST_STATE_PAUSED);
562
563     GstState currentState;
564     GstState pending;
565
566     gst_element_get_state(m_playBin.get(), &currentState, &pending, 0);
567     LOG_MEDIA_MESSAGE("Current state: %s, pending: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
568 #if ENABLE(TIZEN_DLOG_SUPPORT)
569     TIZEN_LOGI("Current state: %s, New state: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(newState));
570 #endif
571     if (currentState == newState || pending == newState)
572         return true;
573
574     GstStateChangeReturn setStateResult = gst_element_set_state(m_playBin.get(), newState);
575     GstState pausedOrPlaying = newState == GST_STATE_PLAYING ? GST_STATE_PAUSED : GST_STATE_PLAYING;
576     if (currentState != pausedOrPlaying && setStateResult == GST_STATE_CHANGE_FAILURE) {
577         loadingFailed(MediaPlayer::Empty);
578         return false;
579     }
580     return true;
581 }
582
583 void MediaPlayerPrivateGStreamer::prepareToPlay()
584 {
585     m_isEndReached = false;
586     m_seeking = false;
587
588     if (m_delayingLoad) {
589         m_delayingLoad = false;
590         commitLoad();
591     }
592 }
593
594 void MediaPlayerPrivateGStreamer::play()
595 {
596 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
597     if (!m_audioSessionManager->setSoundState(ASM_STATE_PLAYING) && !isLocalMediaStream())
598         return;
599 #endif
600     if (changePipelineState(GST_STATE_PLAYING)) {
601         m_isEndReached = false;
602         LOG_MEDIA_MESSAGE("Play");
603     }
604 }
605
606 void MediaPlayerPrivateGStreamer::pause()
607 {
608 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
609     if (!m_audioSessionManager->setSoundState(ASM_STATE_PAUSE) && !isLocalMediaStream())
610         return;
611 #endif
612     if (m_isEndReached)
613         return;
614
615     if (changePipelineState(GST_STATE_PAUSED))
616         LOG_MEDIA_MESSAGE("Pause");
617 }
618
619 float MediaPlayerPrivateGStreamer::duration() const
620 {
621     if (!m_playBin)
622         return 0.0f;
623
624     if (m_errorOccured)
625         return 0.0f;
626
627     // Media duration query failed already, don't attempt new useless queries.
628     if (!m_mediaDurationKnown)
629         return numeric_limits<float>::infinity();
630
631     if (m_mediaDuration)
632         return m_mediaDuration;
633
634     GstFormat timeFormat = GST_FORMAT_TIME;
635     gint64 timeLength = 0;
636
637 #ifdef GST_API_VERSION_1
638     bool failure = !gst_element_query_duration(m_playBin.get(), timeFormat, &timeLength) || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
639 #else
640     bool failure = !gst_element_query_duration(m_playBin.get(), &timeFormat, &timeLength) || timeFormat != GST_FORMAT_TIME || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
641 #endif
642     if (failure) {
643         LOG_MEDIA_MESSAGE("Time duration query failed for %s", m_url.string().utf8().data());
644         return numeric_limits<float>::infinity();
645     }
646
647     LOG_MEDIA_MESSAGE("Duration: %" GST_TIME_FORMAT, GST_TIME_ARGS(timeLength));
648
649     return static_cast<double>(timeLength) / GST_SECOND;
650     // FIXME: handle 3.14.9.5 properly
651 }
652
653 float MediaPlayerPrivateGStreamer::currentTime() const
654 {
655     if (!m_playBin)
656         return 0.0f;
657
658     if (m_errorOccured)
659         return 0.0f;
660
661     if (m_seeking)
662         return m_seekTime;
663
664     // Workaround for
665     // https://bugzilla.gnome.org/show_bug.cgi?id=639941 In GStreamer
666     // 0.10.35 basesink reports wrong duration in case of EOS and
667     // negative playback rate. There's no upstream accepted patch for
668     // this bug yet, hence this temporary workaround.
669     if (m_isEndReached && m_playbackRate < 0)
670         return 0.0f;
671
672     return playbackPosition();
673
674 }
675
676 void MediaPlayerPrivateGStreamer::seek(float time)
677 {
678     if (!m_playBin)
679         return;
680
681     if (m_errorOccured)
682         return;
683
684     LOG_MEDIA_MESSAGE("Seek attempt to %f secs", time);
685 #if ENABLE(TIZEN_DLOG_SUPPORT)
686     TIZEN_LOGI("Seek attempt to %f secs", time);
687 #endif
688
689     // Avoid useless seeking.
690     if (time == currentTime())
691         return;
692
693     // Extract the integer part of the time (seconds) and the
694     // fractional part (microseconds). Attempt to round the
695     // microseconds so no floating point precision is lost and we can
696     // perform an accurate seek.
697     float seconds;
698     float microSeconds = modf(time, &seconds) * 1000000;
699     GTimeVal timeValue;
700     timeValue.tv_sec = static_cast<glong>(seconds);
701     timeValue.tv_usec = static_cast<glong>(roundf(microSeconds / 10000) * 10000);
702
703     GstClockTime clockTime = GST_TIMEVAL_TO_TIME(timeValue);
704     LOG_MEDIA_MESSAGE("Seek: %" GST_TIME_FORMAT, GST_TIME_ARGS(clockTime));
705
706     if (!gst_element_seek(m_playBin.get(), m_player->rate(),
707             GST_FORMAT_TIME,
708             (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE),
709             GST_SEEK_TYPE_SET, clockTime,
710             GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) {
711         LOG_MEDIA_MESSAGE("Seek to %f failed", time);
712 #if ENABLE(TIZEN_DLOG_SUPPORT)
713         TIZEN_LOGE("Seek to %f failed", time);
714 #endif
715     } else {
716         m_seeking = true;
717         m_seekTime = time;
718 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
719         if (m_seekTime != m_mediaDuration)
720             m_isEndReached = false;
721 #endif
722     }
723 }
724
725 bool MediaPlayerPrivateGStreamer::paused() const
726 {
727     if (m_isEndReached) {
728         LOG_MEDIA_MESSAGE("Ignoring pause at EOS");
729         return true;
730     }
731
732     GstState state;
733     gst_element_get_state(m_playBin.get(), &state, 0, 0);
734     return state == GST_STATE_PAUSED;
735 }
736
737 bool MediaPlayerPrivateGStreamer::seeking() const
738 {
739     return m_seeking;
740 }
741
742 // Returns the size of the video
743 IntSize MediaPlayerPrivateGStreamer::naturalSize() const
744 {
745     if (!hasVideo())
746         return IntSize();
747
748     if (!m_videoSize.isEmpty())
749         return m_videoSize;
750
751     GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
752     if (!caps)
753         return IntSize();
754
755
756     // TODO: handle possible clean aperture data. See
757     // https://bugzilla.gnome.org/show_bug.cgi?id=596571
758     // TODO: handle possible transformation matrix. See
759     // https://bugzilla.gnome.org/show_bug.cgi?id=596326
760
761     // Get the video PAR and original size, if this fails the
762     // video-sink has likely not yet negotiated its caps.
763     int pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride;
764     IntSize originalSize;
765     GstVideoFormat format;
766     if (!getVideoSizeAndFormatFromCaps(caps.get(), originalSize, format, pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride))
767         return IntSize();
768
769     LOG_MEDIA_MESSAGE("Original video size: %dx%d", originalSize.width(), originalSize.height());
770     LOG_MEDIA_MESSAGE("Pixel aspect ratio: %d/%d", pixelAspectRatioNumerator, pixelAspectRatioDenominator);
771
772     // Calculate DAR based on PAR and video size.
773     int displayWidth = originalSize.width() * pixelAspectRatioNumerator;
774     int displayHeight = originalSize.height() * pixelAspectRatioDenominator;
775
776     // Divide display width and height by their GCD to avoid possible overflows.
777     int displayAspectRatioGCD = greatestCommonDivisor(displayWidth, displayHeight);
778     displayWidth /= displayAspectRatioGCD;
779     displayHeight /= displayAspectRatioGCD;
780
781     // Apply DAR to original video size. This is the same behavior as in xvimagesink's setcaps function.
782     guint64 width = 0, height = 0;
783     if (!(originalSize.height() % displayHeight)) {
784         LOG_MEDIA_MESSAGE("Keeping video original height");
785         width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
786         height = static_cast<guint64>(originalSize.height());
787     } else if (!(originalSize.width() % displayWidth)) {
788         LOG_MEDIA_MESSAGE("Keeping video original width");
789         height = gst_util_uint64_scale_int(originalSize.width(), displayHeight, displayWidth);
790         width = static_cast<guint64>(originalSize.width());
791     } else {
792         LOG_MEDIA_MESSAGE("Approximating while keeping original video height");
793         width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
794         height = static_cast<guint64>(originalSize.height());
795     }
796
797     LOG_MEDIA_MESSAGE("Natural size: %" G_GUINT64_FORMAT "x%" G_GUINT64_FORMAT, width, height);
798 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE) && USE(ACCELERATED_VIDEO_VAAPI)
799     if (!m_displaySize.isEmpty())
800         m_videoSize = scaleHDVideoToDisplaySize(static_cast<int>(width), static_cast<int>(height), m_displaySize.width(), m_displaySize.height());
801     else
802 #endif
803         m_videoSize = IntSize(static_cast<int>(width), static_cast<int>(height));
804     return m_videoSize;
805 }
806
807 void MediaPlayerPrivateGStreamer::videoChanged()
808 {
809     if (m_videoTimerHandler)
810         g_source_remove(m_videoTimerHandler);
811     m_videoTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVideoChangeTimeoutCallback), this);
812 }
813
814 void MediaPlayerPrivateGStreamer::notifyPlayerOfVideo()
815 {
816     m_videoTimerHandler = 0;
817
818     gint videoTracks = 0;
819     if (m_playBin)
820         g_object_get(m_playBin.get(), "n-video", &videoTracks, NULL);
821
822     m_hasVideo = videoTracks > 0;
823
824 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
825     int width, height;
826     if (gst_video_get_size(m_videoSinkPad.get(), &width, &height)) {
827         IntSize size(width, height);
828         if (m_videoSize != size) {
829             m_videoSize = IntSize();
830 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
831             m_videoLayer->setOverlay(naturalSize());
832 #endif
833         }
834     }
835
836     m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
837 #else // ENABLE(TIZEN_GSTREAMER_VIDEO)
838     m_videoSize = IntSize();
839
840     m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
841 #endif
842 }
843
844 void MediaPlayerPrivateGStreamer::audioChanged()
845 {
846     if (m_audioTimerHandler)
847         g_source_remove(m_audioTimerHandler);
848     m_audioTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateAudioChangeTimeoutCallback), this);
849 }
850
851 void MediaPlayerPrivateGStreamer::notifyPlayerOfAudio()
852 {
853     m_audioTimerHandler = 0;
854
855     gint audioTracks = 0;
856     if (m_playBin)
857         g_object_get(m_playBin.get(), "n-audio", &audioTracks, NULL);
858     m_hasAudio = audioTracks > 0;
859     m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
860 }
861
862 void MediaPlayerPrivateGStreamer::setVolume(float volume)
863 {
864     if (!m_playBin)
865         return;
866
867     gst_stream_volume_set_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC,
868                                  static_cast<double>(volume));
869 }
870
871 void MediaPlayerPrivateGStreamer::notifyPlayerOfVolumeChange()
872 {
873     m_volumeTimerHandler = 0;
874
875     if (!m_player || !m_playBin)
876         return;
877     double volume;
878     volume = gst_stream_volume_get_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC);
879     // get_volume() can return values superior to 1.0 if the user
880     // applies software user gain via third party application (GNOME
881     // volume control for instance).
882     volume = CLAMP(volume, 0.0, 1.0);
883     m_player->volumeChanged(static_cast<float>(volume));
884 }
885
886 void MediaPlayerPrivateGStreamer::volumeChanged()
887 {
888     if (m_volumeTimerHandler)
889         g_source_remove(m_volumeTimerHandler);
890     m_volumeTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVolumeChangeTimeoutCallback), this);
891 }
892
893 void MediaPlayerPrivateGStreamer::setRate(float rate)
894 {
895     // Avoid useless playback rate update.
896     if (m_playbackRate == rate)
897         return;
898
899     GstState state;
900     GstState pending;
901
902     gst_element_get_state(m_playBin.get(), &state, &pending, 0);
903     if ((state != GST_STATE_PLAYING && state != GST_STATE_PAUSED)
904         || (pending == GST_STATE_PAUSED))
905         return;
906
907     if (isLiveStream())
908         return;
909
910     m_playbackRate = rate;
911     m_changingRate = true;
912
913     if (!rate) {
914         gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
915 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
916         if (m_audioSessionManager)
917             m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
918 #endif
919         return;
920     }
921
922     float currentPosition = static_cast<float>(playbackPosition() * GST_SECOND);
923     GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH);
924     gint64 start, end;
925     bool mute = false;
926
927     LOG_MEDIA_MESSAGE("Set Rate to %f", rate);
928     if (rate > 0) {
929         // Mute the sound if the playback rate is too extreme and
930         // audio pitch is not adjusted.
931         mute = (!m_preservesPitch && (rate < 0.8 || rate > 2));
932         start = currentPosition;
933         end = GST_CLOCK_TIME_NONE;
934     } else {
935         start = 0;
936         mute = true;
937
938         // If we are at beginning of media, start from the end to
939         // avoid immediate EOS.
940         if (currentPosition <= 0)
941             end = static_cast<gint64>(duration() * GST_SECOND);
942         else
943             end = currentPosition;
944     }
945
946     LOG_MEDIA_MESSAGE("Need to mute audio: %d", (int) mute);
947
948     if (!gst_element_seek(m_playBin.get(), rate, GST_FORMAT_TIME, flags,
949                           GST_SEEK_TYPE_SET, start,
950                           GST_SEEK_TYPE_SET, end))
951         LOG_MEDIA_MESSAGE("Set rate to %f failed", rate);
952     else
953         g_object_set(m_playBin.get(), "mute", mute, NULL);
954 }
955
956 void MediaPlayerPrivateGStreamer::setPreservesPitch(bool preservesPitch)
957 {
958     m_preservesPitch = preservesPitch;
959 }
960
961 MediaPlayer::NetworkState MediaPlayerPrivateGStreamer::networkState() const
962 {
963     return m_networkState;
964 }
965
966 MediaPlayer::ReadyState MediaPlayerPrivateGStreamer::readyState() const
967 {
968     return m_readyState;
969 }
970
971 PassRefPtr<TimeRanges> MediaPlayerPrivateGStreamer::buffered() const
972 {
973     RefPtr<TimeRanges> timeRanges = TimeRanges::create();
974     if (m_errorOccured || isLiveStream())
975         return timeRanges.release();
976
977 #if GST_CHECK_VERSION(0, 10, 31)
978     float mediaDuration(duration());
979     if (!mediaDuration || isinf(mediaDuration))
980         return timeRanges.release();
981
982     GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
983
984     if (!gst_element_query(m_playBin.get(), query)) {
985         gst_query_unref(query);
986         return timeRanges.release();
987     }
988
989     gint64 rangeStart = 0, rangeStop = 0;
990     for (guint index = 0; index < gst_query_get_n_buffering_ranges(query); index++) {
991         if (gst_query_parse_nth_buffering_range(query, index, &rangeStart, &rangeStop))
992             timeRanges->add(static_cast<float>((rangeStart * mediaDuration) / 100),
993                             static_cast<float>((rangeStop * mediaDuration) / 100));
994     }
995
996     // Fallback to the more general maxTimeLoaded() if no range has
997     // been found.
998     if (!timeRanges->length())
999         if (float loaded = maxTimeLoaded())
1000             timeRanges->add(0, loaded);
1001
1002     gst_query_unref(query);
1003 #else
1004     float loaded = maxTimeLoaded();
1005     if (!m_errorOccured && !isLiveStream() && loaded > 0)
1006         timeRanges->add(0, loaded);
1007 #endif
1008     return timeRanges.release();
1009 }
1010
1011 gboolean MediaPlayerPrivateGStreamer::handleMessage(GstMessage* message)
1012 {
1013     GOwnPtr<GError> err;
1014     GOwnPtr<gchar> debug;
1015     MediaPlayer::NetworkState error;
1016     bool issueError = true;
1017     bool attemptNextLocation = false;
1018     const GstStructure* structure = gst_message_get_structure(message);
1019
1020     if (structure) {
1021         const gchar* messageTypeName = gst_structure_get_name(structure);
1022
1023         // Redirect messages are sent from elements, like qtdemux, to
1024         // notify of the new location(s) of the media.
1025         if (!g_strcmp0(messageTypeName, "redirect")) {
1026             mediaLocationChanged(message);
1027             return TRUE;
1028         }
1029     }
1030
1031     LOG_MEDIA_MESSAGE("Message received from element %s", GST_MESSAGE_SRC_NAME(message));
1032     switch (GST_MESSAGE_TYPE(message)) {
1033     case GST_MESSAGE_ERROR:
1034         if (m_resetPipeline)
1035             break;
1036         gst_message_parse_error(message, &err.outPtr(), &debug.outPtr());
1037         LOG_MEDIA_MESSAGE("Error %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1038
1039 #if ENABLE(TIZEN_DLOG_SUPPORT)
1040         TIZEN_LOGE("GST_MESSAGE_ERROR %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1041 #endif
1042
1043         GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, "webkit-video.error");
1044
1045         error = MediaPlayer::Empty;
1046         if (err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND
1047             || err->code == GST_STREAM_ERROR_WRONG_TYPE
1048             || err->code == GST_STREAM_ERROR_FAILED
1049             || err->code == GST_CORE_ERROR_MISSING_PLUGIN
1050             || err->code == GST_RESOURCE_ERROR_NOT_FOUND)
1051             error = MediaPlayer::FormatError;
1052         else if (err->domain == GST_STREAM_ERROR) {
1053             // Let the mediaPlayerClient handle the stream error, in
1054             // this case the HTMLMediaElement will emit a stalled
1055             // event.
1056 #if !ENABLE(TIZEN_MEDIA_STREAM)
1057             if (err->code == GST_STREAM_ERROR_TYPE_NOT_FOUND) {
1058                 LOG_MEDIA_MESSAGE("Decode error, let the Media element emit a stalled event.");
1059                 break;
1060             }
1061 #endif
1062             error = MediaPlayer::DecodeError;
1063             attemptNextLocation = true;
1064         } else if (err->domain == GST_RESOURCE_ERROR)
1065             error = MediaPlayer::NetworkError;
1066
1067         if (attemptNextLocation)
1068             issueError = !loadNextLocation();
1069         if (issueError)
1070             loadingFailed(error);
1071         break;
1072     case GST_MESSAGE_EOS:
1073         LOG_MEDIA_MESSAGE("End of Stream");
1074         didEnd();
1075         break;
1076     case GST_MESSAGE_STATE_CHANGED:
1077         // Ignore state changes if load is delayed (preload=none). The
1078         // player state will be updated once commitLoad() is called.
1079         if (m_delayingLoad) {
1080             LOG_MEDIA_MESSAGE("Media load has been delayed. Ignoring state changes for now");
1081             break;
1082         }
1083
1084         // Ignore state changes from internal elements. They are
1085         // forwarded to playbin2 anyway.
1086         if (GST_MESSAGE_SRC(message) == reinterpret_cast<GstObject*>(m_playBin.get())) {
1087             updateStates();
1088
1089             // Construct a filename for the graphviz dot file output.
1090             GstState oldState, newState;
1091             gst_message_parse_state_changed(message, &oldState, &newState, 0);
1092
1093             CString dotFileName = String::format("webkit-video.%s_%s",
1094                                                  gst_element_state_get_name(oldState),
1095                                                  gst_element_state_get_name(newState)).utf8();
1096
1097             GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, dotFileName.data());
1098
1099 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1100             if (m_suspendTime > 0 && newState == GST_STATE_PAUSED) {
1101                 if (!isLocalMediaStream())
1102                     seek(m_suspendTime);
1103                 m_suspendTime = 0;
1104                 m_player->mediaPlayerClient()->setSuspended(false);
1105             }
1106 #endif
1107         }
1108         break;
1109     case GST_MESSAGE_BUFFERING:
1110         processBufferingStats(message);
1111         break;
1112     case GST_MESSAGE_DURATION:
1113         LOG_MEDIA_MESSAGE("Duration changed");
1114         durationChanged();
1115         break;
1116     default:
1117         LOG_MEDIA_MESSAGE("Unhandled GStreamer message type: %s",
1118                     GST_MESSAGE_TYPE_NAME(message));
1119         break;
1120     }
1121     return TRUE;
1122 }
1123
1124 void MediaPlayerPrivateGStreamer::processBufferingStats(GstMessage* message)
1125 {
1126     // This is the immediate buffering that needs to happen so we have
1127     // enough to play right now.
1128     m_buffering = true;
1129     const GstStructure *structure = gst_message_get_structure(message);
1130     gst_structure_get_int(structure, "buffer-percent", &m_bufferingPercentage);
1131
1132     LOG_MEDIA_MESSAGE("[Buffering] Buffering: %d%%.", m_bufferingPercentage);
1133
1134     GstBufferingMode mode;
1135     gst_message_parse_buffering_stats(message, &mode, 0, 0, 0);
1136     if (mode != GST_BUFFERING_DOWNLOAD) {
1137         updateStates();
1138         return;
1139     }
1140
1141     // This is on-disk buffering, that allows us to download much more
1142     // than needed for right now.
1143     if (!m_startedBuffering) {
1144         LOG_MEDIA_MESSAGE("[Buffering] Starting on-disk buffering.");
1145
1146         m_startedBuffering = true;
1147
1148         if (m_fillTimer.isActive())
1149             m_fillTimer.stop();
1150
1151         m_fillTimer.startRepeating(0.2);
1152     }
1153 }
1154
1155 void MediaPlayerPrivateGStreamer::fillTimerFired(Timer<MediaPlayerPrivateGStreamer>*)
1156 {
1157     GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
1158
1159     if (!gst_element_query(m_playBin.get(), query)) {
1160         gst_query_unref(query);
1161         return;
1162     }
1163
1164     gint64 start, stop;
1165     gdouble fillStatus = 100.0;
1166
1167     gst_query_parse_buffering_range(query, 0, &start, &stop, 0);
1168     gst_query_unref(query);
1169
1170     if (stop != -1)
1171         fillStatus = 100.0 * stop / GST_FORMAT_PERCENT_MAX;
1172
1173     LOG_MEDIA_MESSAGE("[Buffering] Download buffer filled up to %f%%", fillStatus);
1174
1175     if (!m_mediaDuration)
1176         durationChanged();
1177
1178     // Update maxTimeLoaded only if the media duration is
1179     // available. Otherwise we can't compute it.
1180     if (m_mediaDuration) {
1181         if (fillStatus == 100.0)
1182             m_maxTimeLoaded = m_mediaDuration;
1183         else
1184             m_maxTimeLoaded = static_cast<float>((fillStatus * m_mediaDuration) / 100.0);
1185         LOG_MEDIA_MESSAGE("[Buffering] Updated maxTimeLoaded: %f", m_maxTimeLoaded);
1186     }
1187
1188     if (fillStatus != 100.0) {
1189         updateStates();
1190         return;
1191     }
1192
1193     // Media is now fully loaded. It will play even if network
1194     // connection is cut. Buffering is done, remove the fill source
1195     // from the main loop.
1196     m_fillTimer.stop();
1197     m_startedBuffering = false;
1198     updateStates();
1199 }
1200
1201 float MediaPlayerPrivateGStreamer::maxTimeSeekable() const
1202 {
1203     if (m_errorOccured)
1204         return 0.0f;
1205
1206     LOG_MEDIA_MESSAGE("maxTimeSeekable");
1207     // infinite duration means live stream
1208     if (isinf(duration()))
1209         return 0.0f;
1210
1211     return duration();
1212 }
1213
1214 float MediaPlayerPrivateGStreamer::maxTimeLoaded() const
1215 {
1216     if (m_errorOccured)
1217         return 0.0f;
1218
1219     float loaded = m_maxTimeLoaded;
1220     if (!loaded && !m_fillTimer.isActive())
1221         loaded = duration();
1222     LOG_MEDIA_MESSAGE("maxTimeLoaded: %f", loaded);
1223     return loaded;
1224 }
1225
1226 bool MediaPlayerPrivateGStreamer::didLoadingProgress() const
1227 {
1228     if (!m_playBin || !m_mediaDuration || !totalBytes())
1229         return false;
1230     float currentMaxTimeLoaded = maxTimeLoaded();
1231     bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
1232     m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
1233     LOG_MEDIA_MESSAGE("didLoadingProgress: %d", didLoadingProgress);
1234     return didLoadingProgress;
1235 }
1236
1237 unsigned MediaPlayerPrivateGStreamer::totalBytes() const
1238 {
1239     if (m_errorOccured)
1240         return 0;
1241
1242     if (m_totalBytes != -1)
1243         return m_totalBytes;
1244
1245     if (!m_source)
1246         return 0;
1247
1248     GstFormat fmt = GST_FORMAT_BYTES;
1249     gint64 length = 0;
1250 #ifdef GST_API_VERSION_1
1251     if (gst_element_query_duration(m_source.get(), fmt, &length)) {
1252 #else
1253     if (gst_element_query_duration(m_source.get(), &fmt, &length)) {
1254 #endif
1255         LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1256         m_totalBytes = static_cast<unsigned>(length);
1257         m_isStreaming = !length;
1258         return m_totalBytes;
1259     }
1260
1261     // Fall back to querying the source pads manually.
1262     // See also https://bugzilla.gnome.org/show_bug.cgi?id=638749
1263     GstIterator* iter = gst_element_iterate_src_pads(m_source.get());
1264     bool done = false;
1265     while (!done) {
1266 #ifdef GST_API_VERSION_1
1267         GValue item = G_VALUE_INIT;
1268         switch (gst_iterator_next(iter, &item)) {
1269         case GST_ITERATOR_OK: {
1270             GstPad* pad = static_cast<GstPad*>(g_value_get_object(&item));
1271             gint64 padLength = 0;
1272             if (gst_pad_query_duration(pad, fmt, &padLength) && padLength > length)
1273                 length = padLength;
1274             break;
1275         }
1276 #else
1277         gpointer data;
1278
1279         switch (gst_iterator_next(iter, &data)) {
1280         case GST_ITERATOR_OK: {
1281             GRefPtr<GstPad> pad = adoptGRef(GST_PAD_CAST(data));
1282             gint64 padLength = 0;
1283             if (gst_pad_query_duration(pad.get(), &fmt, &padLength) && padLength > length)
1284                 length = padLength;
1285             break;
1286         }
1287 #endif
1288         case GST_ITERATOR_RESYNC:
1289             gst_iterator_resync(iter);
1290             break;
1291         case GST_ITERATOR_ERROR:
1292             // Fall through.
1293         case GST_ITERATOR_DONE:
1294             done = true;
1295             break;
1296         }
1297
1298 #ifdef GST_API_VERSION_1
1299         g_value_unset(&item);
1300 #endif
1301     }
1302
1303     gst_iterator_free(iter);
1304
1305     LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1306     m_totalBytes = static_cast<unsigned>(length);
1307     m_isStreaming = !length;
1308     return m_totalBytes;
1309 }
1310
1311 unsigned MediaPlayerPrivateGStreamer::decodedFrameCount() const
1312 {
1313     guint64 decodedFrames = 0;
1314     if (m_fpsSink)
1315         g_object_get(m_fpsSink, "frames-rendered", &decodedFrames, NULL);
1316     return static_cast<unsigned>(decodedFrames);
1317 }
1318
1319 unsigned MediaPlayerPrivateGStreamer::droppedFrameCount() const
1320 {
1321     guint64 framesDropped = 0;
1322     if (m_fpsSink)
1323         g_object_get(m_fpsSink, "frames-dropped", &framesDropped, NULL);
1324     return static_cast<unsigned>(framesDropped);
1325 }
1326
1327 unsigned MediaPlayerPrivateGStreamer::audioDecodedByteCount() const
1328 {
1329     GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1330     gint64 position = 0;
1331
1332     if (m_webkitAudioSink && gst_element_query(m_webkitAudioSink.get(), query))
1333         gst_query_parse_position(query, 0, &position);
1334
1335     gst_query_unref(query);
1336     return static_cast<unsigned>(position);
1337 }
1338
1339 unsigned MediaPlayerPrivateGStreamer::videoDecodedByteCount() const
1340 {
1341     GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1342     gint64 position = 0;
1343
1344     if (gst_element_query(m_webkitVideoSink, query))
1345         gst_query_parse_position(query, 0, &position);
1346
1347     gst_query_unref(query);
1348     return static_cast<unsigned>(position);
1349 }
1350
1351 void MediaPlayerPrivateGStreamer::updateAudioSink()
1352 {
1353     if (!m_playBin)
1354         return;
1355
1356     GstElement* sinkPtr = 0;
1357
1358     g_object_get(m_playBin.get(), "audio-sink", &sinkPtr, NULL);
1359     m_webkitAudioSink = adoptGRef(sinkPtr);
1360
1361 }
1362
1363
1364 void MediaPlayerPrivateGStreamer::sourceChanged()
1365 {
1366     GstElement* srcPtr = 0;
1367
1368     g_object_get(m_playBin.get(), "source", &srcPtr, NULL);
1369     m_source = adoptGRef(srcPtr);
1370
1371     if (WEBKIT_IS_WEB_SRC(m_source.get()))
1372         webKitWebSrcSetMediaPlayer(WEBKIT_WEB_SRC(m_source.get()), m_player);
1373 }
1374
1375 void MediaPlayerPrivateGStreamer::cancelLoad()
1376 {
1377     if (m_networkState < MediaPlayer::Loading || m_networkState == MediaPlayer::Loaded)
1378         return;
1379
1380     if (m_playBin)
1381         gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1382 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1383     if (m_audioSessionManager)
1384         m_audioSessionManager->setSoundState(ASM_STATE_STOP);
1385 #endif
1386 }
1387
1388 void MediaPlayerPrivateGStreamer::updateStates()
1389 {
1390     if (!m_playBin)
1391         return;
1392
1393     if (m_errorOccured)
1394         return;
1395
1396     MediaPlayer::NetworkState oldNetworkState = m_networkState;
1397     MediaPlayer::ReadyState oldReadyState = m_readyState;
1398     GstState state;
1399     GstState pending;
1400
1401     GstStateChangeReturn ret = gst_element_get_state(m_playBin.get(),
1402         &state, &pending, 250 * GST_NSECOND);
1403
1404     bool shouldUpdateAfterSeek = false;
1405     switch (ret) {
1406     case GST_STATE_CHANGE_SUCCESS:
1407         LOG_MEDIA_MESSAGE("State: %s, pending: %s",
1408             gst_element_state_get_name(state),
1409             gst_element_state_get_name(pending));
1410
1411         m_resetPipeline = state <= GST_STATE_READY;
1412
1413         // Try to figure out ready and network states.
1414         if (state == GST_STATE_READY) {
1415             m_readyState = MediaPlayer::HaveMetadata;
1416             m_networkState = MediaPlayer::Empty;
1417             // Cache the duration without emiting the durationchange
1418             // event because it's taken care of by the media element
1419             // in this precise case.
1420             if (!m_isEndReached)
1421                 cacheDuration();
1422         } else if ((state == GST_STATE_NULL) || (maxTimeLoaded() == duration())) {
1423             m_networkState = MediaPlayer::Loaded;
1424             m_readyState = MediaPlayer::HaveEnoughData;
1425         } else {
1426             m_readyState = currentTime() < maxTimeLoaded() ? MediaPlayer::HaveFutureData : MediaPlayer::HaveCurrentData;
1427             m_networkState = MediaPlayer::Loading;
1428         }
1429
1430         if (m_buffering && state != GST_STATE_READY) {
1431             m_readyState = MediaPlayer::HaveCurrentData;
1432             m_networkState = MediaPlayer::Loading;
1433         }
1434
1435         // Now let's try to get the states in more detail using
1436         // information from GStreamer, while we sync states where
1437         // needed.
1438         if (state == GST_STATE_PAUSED) {
1439             if (!m_webkitAudioSink)
1440                 updateAudioSink();
1441
1442             if (!m_volumeAndMuteInitialized) {
1443                 notifyPlayerOfVolumeChange();
1444                 notifyPlayerOfMute();
1445                 m_volumeAndMuteInitialized = true;
1446             }
1447
1448             if (m_buffering && m_bufferingPercentage == 100) {
1449                 m_buffering = false;
1450                 m_bufferingPercentage = 0;
1451                 m_readyState = MediaPlayer::HaveEnoughData;
1452
1453                 LOG_MEDIA_MESSAGE("[Buffering] Complete.");
1454
1455                 if (!m_paused) {
1456                     LOG_MEDIA_MESSAGE("[Buffering] Restarting playback.");
1457                     gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1458 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1459                     if (m_audioSessionManager)
1460                         m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1461 #endif
1462                 }
1463             } else if (!m_buffering && (currentTime() < duration())) {
1464                 m_paused = true;
1465             }
1466         } else if (state == GST_STATE_PLAYING) {
1467             m_readyState = MediaPlayer::HaveEnoughData;
1468             m_paused = false;
1469
1470             if (m_buffering && !isLiveStream()) {
1471                 m_readyState = MediaPlayer::HaveCurrentData;
1472                 m_networkState = MediaPlayer::Loading;
1473
1474                 LOG_MEDIA_MESSAGE("[Buffering] Pausing stream for buffering.");
1475
1476                 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1477 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1478                 if (m_audioSessionManager)
1479                     m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1480 #endif
1481             }
1482         } else
1483             m_paused = true;
1484
1485         // Is on-disk buffering in progress?
1486         if (m_fillTimer.isActive())
1487             m_networkState = MediaPlayer::Loading;
1488
1489         if (m_changingRate) {
1490             m_player->rateChanged();
1491             m_changingRate = false;
1492         }
1493
1494         if (m_seeking) {
1495             shouldUpdateAfterSeek = true;
1496             m_seeking = false;
1497         }
1498
1499         break;
1500     case GST_STATE_CHANGE_ASYNC:
1501         LOG_MEDIA_MESSAGE("Async: State: %s, pending: %s",
1502             gst_element_state_get_name(state),
1503             gst_element_state_get_name(pending));
1504         // Change in progress
1505
1506         // On-disk buffering was attempted but the media is live. This
1507         // can't work so disable on-disk buffering and reset the
1508         // pipeline.
1509
1510 #if ENABLE(TIZEN_MEDIA_STREAM)
1511         if (state == GST_STATE_READY && isLiveStream() && m_preload == MediaPlayer::Auto && !isLocalMediaStream()) {
1512 #else
1513         if (state == GST_STATE_READY && isLiveStream() && m_preload == MediaPlayer::Auto) {
1514 #endif
1515             setPreload(MediaPlayer::None);
1516             gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1517             gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1518 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1519             if (m_audioSessionManager)
1520                 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1521 #endif
1522         }
1523
1524         // A live stream was paused, reset the pipeline.
1525 #if ENABLE(TIZEN_MEDIA_STREAM)
1526         if (state == GST_STATE_PAUSED && pending == GST_STATE_PLAYING && isLiveStream() && !isLocalMediaStream()) {
1527 #else
1528         if (state == GST_STATE_PAUSED && pending == GST_STATE_PLAYING && isLiveStream()) {
1529 #endif
1530             gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1531             gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1532 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1533             if (m_audioSessionManager)
1534                 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1535 #endif
1536         }
1537
1538         if (!isLiveStream() && !m_buffering)
1539             return;
1540
1541         if (m_seeking) {
1542             shouldUpdateAfterSeek = true;
1543             m_seeking = false;
1544         }
1545         break;
1546     case GST_STATE_CHANGE_FAILURE:
1547         LOG_MEDIA_MESSAGE("Failure: State: %s, pending: %s",
1548             gst_element_state_get_name(state),
1549             gst_element_state_get_name(pending));
1550         // Change failed
1551         return;
1552     case GST_STATE_CHANGE_NO_PREROLL:
1553         LOG_MEDIA_MESSAGE("No preroll: State: %s, pending: %s",
1554             gst_element_state_get_name(state),
1555             gst_element_state_get_name(pending));
1556
1557         if (state == GST_STATE_READY)
1558             m_readyState = MediaPlayer::HaveNothing;
1559         else if (state == GST_STATE_PAUSED) {
1560             m_readyState = MediaPlayer::HaveEnoughData;
1561             m_paused = true;
1562             // Live pipelines go in PAUSED without prerolling.
1563             m_isStreaming = true;
1564         } else if (state == GST_STATE_PLAYING)
1565             m_paused = false;
1566
1567         if (m_seeking) {
1568             shouldUpdateAfterSeek = true;
1569             m_seeking = false;
1570             if (!m_paused) {
1571                 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1572 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1573                 if (m_audioSessionManager)
1574                     m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1575 #endif
1576             }
1577         } else if (!m_paused) {
1578             gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1579 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1580             if (m_audioSessionManager)
1581                 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1582 #endif
1583         }
1584
1585         m_networkState = MediaPlayer::Loading;
1586         break;
1587     default:
1588         LOG_MEDIA_MESSAGE("Else : %d", ret);
1589         break;
1590     }
1591
1592     if (seeking())
1593         m_readyState = MediaPlayer::HaveNothing;
1594
1595     if (shouldUpdateAfterSeek)
1596         timeChanged();
1597
1598     if (m_networkState != oldNetworkState) {
1599         LOG_MEDIA_MESSAGE("Network State Changed from %u to %u",
1600             oldNetworkState, m_networkState);
1601         m_player->networkStateChanged();
1602     }
1603     if (m_readyState != oldReadyState) {
1604         LOG_MEDIA_MESSAGE("Ready State Changed from %u to %u",
1605             oldReadyState, m_readyState);
1606         m_player->readyStateChanged();
1607 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1608         if (state == GST_STATE_PLAYING)
1609             m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
1610 #endif
1611     }
1612 }
1613
1614 void MediaPlayerPrivateGStreamer::mediaLocationChanged(GstMessage* message)
1615 {
1616     if (m_mediaLocations)
1617         gst_structure_free(m_mediaLocations);
1618
1619     const GstStructure* structure = gst_message_get_structure(message);
1620     if (structure) {
1621         // This structure can contain:
1622         // - both a new-location string and embedded locations structure
1623         // - or only a new-location string.
1624         m_mediaLocations = gst_structure_copy(structure);
1625         const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1626
1627         if (locations)
1628             m_mediaLocationCurrentIndex = static_cast<int>(gst_value_list_get_size(locations)) -1;
1629
1630         loadNextLocation();
1631     }
1632 }
1633
1634 bool MediaPlayerPrivateGStreamer::loadNextLocation()
1635 {
1636     if (!m_mediaLocations)
1637         return false;
1638
1639     const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1640     const gchar* newLocation = 0;
1641
1642     if (!locations) {
1643         // Fallback on new-location string.
1644         newLocation = gst_structure_get_string(m_mediaLocations, "new-location");
1645         if (!newLocation)
1646             return false;
1647     }
1648
1649     if (!newLocation) {
1650         if (m_mediaLocationCurrentIndex < 0) {
1651             m_mediaLocations = 0;
1652             return false;
1653         }
1654
1655         const GValue* location = gst_value_list_get_value(locations,
1656                                                           m_mediaLocationCurrentIndex);
1657         const GstStructure* structure = gst_value_get_structure(location);
1658
1659         if (!structure) {
1660             m_mediaLocationCurrentIndex--;
1661             return false;
1662         }
1663
1664         newLocation = gst_structure_get_string(structure, "new-location");
1665     }
1666
1667     if (newLocation) {
1668         // Found a candidate. new-location is not always an absolute url
1669         // though. We need to take the base of the current url and
1670         // append the value of new-location to it.
1671
1672         gchar* currentLocation = 0;
1673         g_object_get(m_playBin.get(), "uri", &currentLocation, NULL);
1674
1675         KURL currentUrl(KURL(), currentLocation);
1676         g_free(currentLocation);
1677
1678         KURL newUrl;
1679
1680         if (gst_uri_is_valid(newLocation))
1681             newUrl = KURL(KURL(), newLocation);
1682         else
1683             newUrl = KURL(KURL(), currentUrl.baseAsString() + newLocation);
1684
1685         RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(currentUrl);
1686         if (securityOrigin->canRequest(newUrl)) {
1687             LOG_MEDIA_MESSAGE("New media url: %s", newUrl.string().utf8().data());
1688
1689             // Reset player states.
1690             m_networkState = MediaPlayer::Loading;
1691             m_player->networkStateChanged();
1692             m_readyState = MediaPlayer::HaveNothing;
1693             m_player->readyStateChanged();
1694
1695             // Reset pipeline state.
1696             m_resetPipeline = true;
1697             gst_element_set_state(m_playBin.get(), GST_STATE_READY);
1698 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1699             if (m_audioSessionManager)
1700                 m_audioSessionManager->setSoundState(ASM_STATE_NONE);
1701 #endif
1702             GstState state;
1703             gst_element_get_state(m_playBin.get(), &state, 0, 0);
1704             if (state <= GST_STATE_READY) {
1705                 // Set the new uri and start playing.
1706                 g_object_set(m_playBin.get(), "uri", newUrl.string().utf8().data(), NULL);
1707                 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1708 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1709                 if (m_audioSessionManager)
1710                     m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1711 #endif
1712                 return true;
1713             }
1714         }
1715     }
1716     m_mediaLocationCurrentIndex--;
1717     return false;
1718
1719 }
1720
1721 void MediaPlayerPrivateGStreamer::loadStateChanged()
1722 {
1723     updateStates();
1724 }
1725
1726 void MediaPlayerPrivateGStreamer::sizeChanged()
1727 {
1728     notImplemented();
1729 }
1730
1731 void MediaPlayerPrivateGStreamer::timeChanged()
1732 {
1733     updateStates();
1734     m_player->timeChanged();
1735 }
1736
1737 void MediaPlayerPrivateGStreamer::didEnd()
1738 {
1739     // Synchronize position and duration values to not confuse the
1740     // HTMLMediaElement. In some cases like reverse playback the
1741     // position is not always reported as 0 for instance.
1742     float now = currentTime();
1743 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1744     if (now > 0 && now != duration()) {
1745 #else
1746     if (now > 0 && now <= duration() && m_mediaDuration != now) {
1747 #endif
1748         m_mediaDurationKnown = true;
1749         m_mediaDuration = now;
1750         m_player->durationChanged();
1751     }
1752
1753     m_isEndReached = true;
1754     timeChanged();
1755
1756     if (!m_player->mediaPlayerClient()->mediaPlayerIsLooping()) {
1757         m_paused = true;
1758 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1759         gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1760         if (m_audioSessionManager)
1761             m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1762 #else
1763         gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1764 #endif
1765
1766 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1767         HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
1768         if (element->isVideo())
1769             power_unlock_state(POWER_STATE_NORMAL);
1770 #endif
1771     }
1772 }
1773
1774 void MediaPlayerPrivateGStreamer::cacheDuration()
1775 {
1776 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1777     float previousDuration = m_mediaDuration;
1778 #endif
1779     // Reset cached media duration
1780     m_mediaDuration = 0;
1781
1782     // And re-cache it if possible.
1783     GstState state;
1784     gst_element_get_state(m_playBin.get(), &state, 0, 0);
1785     float newDuration = duration();
1786
1787 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1788     if (state > GST_STATE_READY) {
1789         // Don't set m_mediaDurationKnown yet if the pipeline is not
1790         // paused. This allows duration() query to fail at least once
1791         // before playback starts and duration becomes known.
1792         m_mediaDurationKnown = !isinf(newDuration);
1793     }
1794
1795     if (!isinf(newDuration))
1796         m_mediaDuration = newDuration;
1797     else
1798         m_mediaDuration = previousDuration;
1799 #else
1800     if (state <= GST_STATE_READY) {
1801         // Don't set m_mediaDurationKnown yet if the pipeline is not
1802         // paused. This allows duration() query to fail at least once
1803         // before playback starts and duration becomes known.
1804         if (!isinf(newDuration))
1805             m_mediaDuration = newDuration;
1806     } else {
1807         m_mediaDurationKnown = !isinf(newDuration);
1808         if (m_mediaDurationKnown)
1809             m_mediaDuration = newDuration;
1810     }
1811
1812     if (!isinf(newDuration))
1813         m_mediaDuration = newDuration;
1814 #endif
1815 }
1816
1817 void MediaPlayerPrivateGStreamer::durationChanged()
1818 {
1819     float previousDuration = m_mediaDuration;
1820
1821     cacheDuration();
1822     // Avoid emiting durationchanged in the case where the previous
1823     // duration was 0 because that case is already handled by the
1824     // HTMLMediaElement.
1825     if (previousDuration && m_mediaDuration != previousDuration)
1826         m_player->durationChanged();
1827
1828     if (m_preload == MediaPlayer::None && m_originalPreloadWasAutoAndWasOverridden) {
1829         m_totalBytes = -1;
1830         if (totalBytes() && !isLiveStream()) {
1831             setPreload(MediaPlayer::Auto);
1832             gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1833             gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1834 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1835             if (m_audioSessionManager)
1836                 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1837 #endif
1838         }
1839     }
1840 }
1841
1842 bool MediaPlayerPrivateGStreamer::supportsMuting() const
1843 {
1844     return true;
1845 }
1846
1847 void MediaPlayerPrivateGStreamer::setMuted(bool muted)
1848 {
1849     if (!m_playBin)
1850         return;
1851
1852     g_object_set(m_playBin.get(), "mute", muted, NULL);
1853 }
1854
1855 void MediaPlayerPrivateGStreamer::notifyPlayerOfMute()
1856 {
1857     m_muteTimerHandler = 0;
1858
1859     if (!m_player || !m_playBin)
1860         return;
1861
1862     gboolean muted;
1863     g_object_get(m_playBin.get(), "mute", &muted, NULL);
1864     m_player->muteChanged(static_cast<bool>(muted));
1865 }
1866
1867 void MediaPlayerPrivateGStreamer::muteChanged()
1868 {
1869     if (m_muteTimerHandler)
1870         g_source_remove(m_muteTimerHandler);
1871     m_muteTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateMuteChangeTimeoutCallback), this);
1872 }
1873
1874 void MediaPlayerPrivateGStreamer::loadingFailed(MediaPlayer::NetworkState error)
1875 {
1876 #if ENABLE(TIZEN_DLOG_SUPPORT)
1877     TIZEN_LOGE("NetworkState : %d", error);
1878 #endif
1879
1880     m_errorOccured = true;
1881     if (m_networkState != error) {
1882         m_networkState = error;
1883         m_player->networkStateChanged();
1884     }
1885     if (m_readyState != MediaPlayer::HaveNothing) {
1886         m_readyState = MediaPlayer::HaveNothing;
1887         m_player->readyStateChanged();
1888     }
1889 }
1890
1891 void MediaPlayerPrivateGStreamer::setSize(const IntSize& size)
1892 {
1893     m_size = size;
1894 }
1895
1896 void MediaPlayerPrivateGStreamer::setVisible(bool visible)
1897 {
1898 }
1899
1900 void MediaPlayerPrivateGStreamer::triggerRepaint(GstBuffer* buffer)
1901 {
1902     g_return_if_fail(GST_IS_BUFFER(buffer));
1903     gst_buffer_replace(&m_buffer, buffer);
1904 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1905 #if !ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1906     if (m_videoSize.isEmpty())
1907         m_videoSize =  naturalSize();
1908     m_videoLayer->paintVideoLayer(m_videoSize);
1909     return;
1910 #endif
1911 #endif
1912     m_player->repaint();
1913 }
1914
1915 void MediaPlayerPrivateGStreamer::paint(GraphicsContext* context, const IntRect& rect)
1916 {
1917     if (context->paintingDisabled())
1918         return;
1919
1920     if (!m_player->visible())
1921         return;
1922
1923     if (!m_buffer)
1924         return;
1925
1926     GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
1927     if (!caps)
1928         return;
1929
1930     RefPtr<ImageGStreamer> gstImage = ImageGStreamer::createImage(m_buffer, caps.get());
1931     if (!gstImage)
1932         return;
1933
1934     context->drawImage(reinterpret_cast<Image*>(gstImage->image().get()), ColorSpaceSRGB,
1935                        rect, gstImage->rect(), CompositeCopy, DoNotRespectImageOrientation, false);
1936 }
1937
1938 static HashSet<String> mimeTypeCache()
1939 {
1940     initializeGStreamerAndRegisterWebKitElements();
1941
1942     DEFINE_STATIC_LOCAL(HashSet<String>, cache, ());
1943     static bool typeListInitialized = false;
1944
1945     if (typeListInitialized)
1946         return cache;
1947     const char* mimeTypes[] = {
1948         "application/ogg",
1949         "application/vnd.apple.mpegurl",
1950         "application/vnd.rn-realmedia",
1951         "application/x-3gp",
1952 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1953         "application/x-mpegurl",
1954         "application/x-mpegURL",
1955 #endif
1956         "application/x-pn-realaudio",
1957         "audio/3gpp",
1958         "audio/aac",
1959         "audio/flac",
1960         "audio/iLBC-sh",
1961         "audio/midi",
1962         "audio/mobile-xmf",
1963         "audio/mp1",
1964         "audio/mp2",
1965         "audio/mp3",
1966         "audio/mp4",
1967         "audio/mpeg",
1968         "audio/ogg",
1969         "audio/opus",
1970         "audio/qcelp",
1971         "audio/riff-midi",
1972         "audio/wav",
1973         "audio/webm",
1974         "audio/x-ac3",
1975         "audio/x-aiff",
1976         "audio/x-amr-nb-sh",
1977         "audio/x-amr-wb-sh",
1978         "audio/x-au",
1979         "audio/x-ay",
1980         "audio/x-celt",
1981         "audio/x-dts",
1982         "audio/x-flac",
1983         "audio/x-gbs",
1984         "audio/x-gsm",
1985         "audio/x-gym",
1986         "audio/x-imelody",
1987         "audio/x-ircam",
1988         "audio/x-kss",
1989         "audio/x-m4a",
1990         "audio/x-mod",
1991         "audio/x-mp3",
1992         "audio/x-mpeg",
1993         "audio/x-musepack",
1994         "audio/x-nist",
1995         "audio/x-nsf",
1996         "audio/x-paris",
1997         "audio/x-sap",
1998         "audio/x-sbc",
1999         "audio/x-sds",
2000         "audio/x-shorten",
2001         "audio/x-sid",
2002         "audio/x-spc",
2003         "audio/x-speex",
2004         "audio/x-svx",
2005         "audio/x-ttafile",
2006         "audio/x-vgm",
2007         "audio/x-voc",
2008         "audio/x-vorbis+ogg",
2009         "audio/x-w64",
2010         "audio/x-wav",
2011         "audio/x-wavpack",
2012         "audio/x-wavpack-correction",
2013         "video/3gpp",
2014         "video/mj2",
2015         "video/mp4",
2016         "video/mpeg",
2017         "video/mpegts",
2018         "video/ogg",
2019         "video/quicktime",
2020         "video/vivo",
2021 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2022         "video/webm",
2023 #endif
2024         "video/x-cdxa",
2025         "video/x-dirac",
2026         "video/x-dv",
2027         "video/x-fli",
2028         "video/x-flv",
2029         "video/x-h263",
2030         "video/x-ivf",
2031         "video/x-m4v",
2032         "video/x-matroska",
2033         "video/x-mng",
2034         "video/x-ms-asf",
2035         "video/x-msvideo",
2036         "video/x-mve",
2037         "video/x-nuv",
2038         "video/x-vcd"
2039     };
2040
2041     for (unsigned i = 0; i < (sizeof(mimeTypes) / sizeof(*mimeTypes)); ++i)
2042         cache.add(String(mimeTypes[i]));
2043
2044     typeListInitialized = true;
2045     return cache;
2046 }
2047
2048 void MediaPlayerPrivateGStreamer::getSupportedTypes(HashSet<String>& types)
2049 {
2050     types = mimeTypeCache();
2051 }
2052
2053 MediaPlayer::SupportsType MediaPlayerPrivateGStreamer::supportsType(const String& type, const String& codecs, const KURL&)
2054 {
2055     if (type.isNull() || type.isEmpty())
2056         return MediaPlayer::IsNotSupported;
2057
2058     // spec says we should not return "probably" if the codecs string is empty
2059     if (mimeTypeCache().contains(type))
2060         return codecs.isEmpty() ? MediaPlayer::MayBeSupported : MediaPlayer::IsSupported;
2061     return MediaPlayer::IsNotSupported;
2062 }
2063
2064 bool MediaPlayerPrivateGStreamer::hasSingleSecurityOrigin() const
2065 {
2066     return true;
2067 }
2068
2069 bool MediaPlayerPrivateGStreamer::supportsFullscreen() const
2070 {
2071 #if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
2072     // See <rdar://problem/7389945>
2073     return false;
2074 #else
2075     return true;
2076 #endif
2077 }
2078
2079 PlatformMedia MediaPlayerPrivateGStreamer::platformMedia() const
2080 {
2081     PlatformMedia p;
2082 #ifndef GST_API_VERSION_1
2083     p.type = PlatformMedia::GStreamerGWorldType;
2084     p.media.gstreamerGWorld = m_gstGWorld.get();
2085 #endif
2086     return p;
2087 }
2088
2089 MediaPlayer::MovieLoadType MediaPlayerPrivateGStreamer::movieLoadType() const
2090 {
2091     if (m_readyState == MediaPlayer::HaveNothing)
2092         return MediaPlayer::Unknown;
2093
2094     if (isLiveStream())
2095         return MediaPlayer::LiveStream;
2096
2097     return MediaPlayer::Download;
2098 }
2099
2100 void MediaPlayerPrivateGStreamer::setDownloadBuffering()
2101 {
2102     if (!m_playBin)
2103         return;
2104
2105     GstPlayFlags flags;
2106
2107     g_object_get(m_playBin.get(), "flags", &flags, NULL);
2108 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2109     flags = (GstPlayFlags)(flags | GST_PLAY_FLAG_NATIVE_VIDEO);
2110 #endif
2111     if (m_preload == MediaPlayer::Auto) {
2112         LOG_MEDIA_MESSAGE("Enabling on-disk buffering");
2113         g_object_set(m_playBin.get(), "flags", flags | GST_PLAY_FLAG_DOWNLOAD, NULL);
2114     } else {
2115         LOG_MEDIA_MESSAGE("Disabling on-disk buffering");
2116         g_object_set(m_playBin.get(), "flags", flags & ~GST_PLAY_FLAG_DOWNLOAD, NULL);
2117     }
2118 }
2119
2120 void MediaPlayerPrivateGStreamer::setPreload(MediaPlayer::Preload preload)
2121 {
2122     m_originalPreloadWasAutoAndWasOverridden = m_preload != preload && m_preload == MediaPlayer::Auto;
2123
2124     m_preload = preload;
2125
2126     setDownloadBuffering();
2127
2128     if (m_delayingLoad && m_preload != MediaPlayer::None) {
2129         m_delayingLoad = false;
2130         commitLoad();
2131     }
2132 }
2133
2134 void MediaPlayerPrivateGStreamer::createAudioSink()
2135 {
2136     // Construct audio sink if pitch preserving is enabled.
2137     if (!m_preservesPitch)
2138         return;
2139
2140     if (!m_playBin)
2141         return;
2142
2143     GstElement* scale = gst_element_factory_make("scaletempo", 0);
2144     if (!scale) {
2145         GST_WARNING("Failed to create scaletempo");
2146         return;
2147     }
2148
2149     GstElement* convert = gst_element_factory_make("audioconvert", 0);
2150     GstElement* resample = gst_element_factory_make("audioresample", 0);
2151     GstElement* sink = gst_element_factory_make("autoaudiosink", 0);
2152
2153     GstElement* audioSink = gst_bin_new("audio-sink");
2154     gst_bin_add_many(GST_BIN(audioSink), scale, convert, resample, sink, NULL);
2155
2156     if (!gst_element_link_many(scale, convert, resample, sink, NULL)) {
2157         GST_WARNING("Failed to link audio sink elements");
2158         gst_object_unref(audioSink);
2159         return;
2160     }
2161
2162     GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(scale, "sink"));
2163     gst_element_add_pad(audioSink, gst_ghost_pad_new("sink", pad.get()));
2164
2165     g_object_set(m_playBin.get(), "audio-sink", audioSink, NULL);
2166 }
2167
2168 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2169 GstElement* MediaPlayerPrivateGStreamer::createVideoSink()
2170 {
2171 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2172     m_webkitVideoSink = m_videoLayer->createVideoSink();
2173     m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2174
2175     // Primary video should be OFF and Secondary video should be FULL SCREEN mode
2176     g_object_set(m_webkitVideoSink, "display-mode", 2, NULL);
2177 #else // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2178 #ifndef GST_API_VERSION_1
2179     m_webkitVideoSink = webkitVideoSinkNew(m_gstGWorld.get());
2180 #else
2181     m_webkitVideoSink = webkitVideoSinkNew();
2182 #endif
2183     m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2184     g_signal_connect(m_webkitVideoSink, "repaint-requested", G_CALLBACK(mediaPlayerPrivateRepaintCallback), this);
2185 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2186
2187 #ifndef GST_API_VERSION_1
2188     m_videoSinkBin = gst_bin_new("video-sink");
2189     GstElement* videoTee = gst_element_factory_make("tee", "videoTee");
2190 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2191     GstElement* queue = gst_element_factory_make("queue", 0);
2192 #endif
2193     // Take ownership.
2194     gst_object_ref_sink(m_videoSinkBin);
2195
2196     // Build a new video sink consisting of a bin containing a tee
2197     // (meant to distribute data to multiple video sinks) and our
2198     // internal video sink. For fullscreen we create an autovideosink
2199     // and initially block the data flow towards it and configure it
2200 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2201     gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, queue, NULL);
2202 #else
2203     gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, NULL);
2204 #endif
2205
2206 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2207     // Link a new src pad from tee to queue1.
2208     gst_element_link_pads_full(videoTee, 0, queue, "sink", GST_PAD_LINK_CHECK_NOTHING);
2209 #endif
2210 #endif
2211
2212     GstElement* actualVideoSink = 0;
2213     m_fpsSink = gst_element_factory_make("fpsdisplaysink", "sink");
2214     if (m_fpsSink) {
2215         // The verbose property has been added in -bad 0.10.22. Making
2216         // this whole code depend on it because we don't want
2217         // fpsdiplaysink to spit data on stdout.
2218         GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(m_fpsSink)->elementfactory);
2219         if (gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 22)) {
2220             g_object_set(m_fpsSink, "silent", TRUE , NULL);
2221
2222             // Turn off text overlay unless logging is enabled.
2223 #if LOG_DISABLED
2224             g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2225 #else
2226             WTFLogChannel* channel = getChannelFromName("Media");
2227             if (channel->state != WTFLogChannelOn)
2228                 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2229 #endif // LOG_DISABLED
2230
2231             if (g_object_class_find_property(G_OBJECT_GET_CLASS(m_fpsSink), "video-sink")) {
2232                 g_object_set(m_fpsSink, "video-sink", m_webkitVideoSink, NULL);
2233 #ifndef GST_API_VERSION_1
2234                 gst_bin_add(GST_BIN(m_videoSinkBin), m_fpsSink);
2235 #endif
2236                 actualVideoSink = m_fpsSink;
2237             } else
2238                 m_fpsSink = 0;
2239         } else
2240             m_fpsSink = 0;
2241     }
2242
2243     if (!m_fpsSink) {
2244 #ifndef GST_API_VERSION_1
2245         gst_bin_add(GST_BIN(m_videoSinkBin), m_webkitVideoSink);
2246 #endif
2247         actualVideoSink = m_webkitVideoSink;
2248     }
2249
2250     ASSERT(actualVideoSink);
2251
2252 #ifndef GST_API_VERSION_1
2253 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2254     // Link a new src pad from tee to queue1.
2255     GRefPtr<GstPad> srcPad = adoptGRef(gst_element_get_request_pad(videoTee, "src%d"));
2256     GRefPtr<GstPad> sinkPad = adoptGRef(gst_element_get_static_pad(actualVideoSink, "sink"));
2257     gst_pad_link(srcPad.get(), sinkPad.get());
2258 #else
2259     // Faster elements linking.
2260     gst_element_link_pads_full(queue, "src", actualVideoSink, "sink", GST_PAD_LINK_CHECK_NOTHING);
2261 #endif
2262     // Add a ghostpad to the bin so it can proxy to tee.
2263     GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(videoTee, "sink"));
2264     gst_element_add_pad(m_videoSinkBin, gst_ghost_pad_new("sink", pad.get()));
2265
2266     // Set the bin as video sink of playbin.
2267     return m_videoSinkBin;
2268 #else
2269     return actualVideoSink;
2270 #endif
2271 }
2272 #endif
2273
2274 void MediaPlayerPrivateGStreamer::createGSTPlayBin()
2275 {
2276     ASSERT(!m_playBin);
2277
2278     // gst_element_factory_make() returns a floating reference so
2279     // we should not adopt.
2280     m_playBin = gst_element_factory_make(gPlaybinName, "play");
2281
2282 #ifndef GST_API_VERSION_1
2283     m_gstGWorld = GStreamerGWorld::createGWorld(m_playBin.get());
2284 #endif
2285
2286     GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
2287     gst_bus_add_signal_watch(bus.get());
2288     g_signal_connect(bus.get(), "message", G_CALLBACK(mediaPlayerPrivateMessageCallback), this);
2289 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2290     gst_bus_set_sync_handler(bus.get(), GstBusSyncHandler(mediaPlayerPrivateSyncHandler), this);
2291 #endif
2292     gst_object_unref(bus.get());
2293
2294     g_object_set(m_playBin.get(), "mute", m_player->muted(), NULL);
2295
2296     g_signal_connect(m_playBin.get(), "notify::volume", G_CALLBACK(mediaPlayerPrivateVolumeChangedCallback), this);
2297     g_signal_connect(m_playBin.get(), "notify::source", G_CALLBACK(mediaPlayerPrivateSourceChangedCallback), this);
2298     g_signal_connect(m_playBin.get(), "notify::mute", G_CALLBACK(mediaPlayerPrivateMuteChangedCallback), this);
2299     g_signal_connect(m_playBin.get(), "video-changed", G_CALLBACK(mediaPlayerPrivateVideoChangedCallback), this);
2300     g_signal_connect(m_playBin.get(), "audio-changed", G_CALLBACK(mediaPlayerPrivateAudioChangedCallback), this);
2301 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2302     g_signal_connect(m_playBin.get(), "source-setup", G_CALLBACK(mediaPlayerPrivateSourceSetupCallback), this);
2303 #endif
2304
2305 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2306     HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
2307     if (element->isVideo()) {
2308         GstElement* videoElement = createVideoSink();
2309         g_object_set(m_playBin.get(), "video-sink", videoElement, NULL);
2310
2311         GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2312         if (videoSinkPad)
2313             g_signal_connect(videoSinkPad.get(), "notify::caps", G_CALLBACK(mediaPlayerPrivateVideoSinkCapsChangedCallback), this);
2314     } else {
2315         GstElement* fakeSink = gst_element_factory_make("fakesink", 0);
2316         g_object_set(fakeSink, "sync", true, NULL);
2317         g_object_set(m_playBin.get(), "video-sink", fakeSink, NULL);
2318     }
2319 #endif
2320 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2321     GstElement* realSink = gst_element_factory_make("avsysaudiosink", 0);
2322     g_object_set(realSink, "close-handle-on-prepare", 1, NULL);
2323     g_object_set(m_playBin.get(), "audio-sink", realSink, NULL);
2324
2325     if (m_audioSessionManager)
2326         m_audioSessionManager->registerAudioSessionManager(MM_SESSION_TYPE_SHARE, mediaPlayerPrivateAudioSessionNotifyCallback, player());
2327 #else
2328     createAudioSink();
2329 #endif
2330 }
2331
2332 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2333 bool MediaPlayerPrivateGStreamer::supportsAcceleratedRendering() const
2334 {
2335     bool isEmbedVideo = false;
2336     if (m_player->mediaPlayerClient()) {
2337         Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
2338         if (document && document->settings()) {
2339             isEmbedVideo = document->settings()->acceleratedCompositingForVideoEnabled()
2340                                 && document->settings()->acceleratedCompositingEnabled();
2341             LOG_MEDIA_MESSAGE("isEmbedVideo: %d", isEmbedVideo);
2342         }
2343     }
2344
2345     return isEmbedVideo;
2346 }
2347
2348 PlatformLayer* MediaPlayerPrivateGStreamer::platformLayer() const
2349 {
2350     return m_videoLayer->platformLayer();
2351 }
2352
2353 #if ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2354 void MediaPlayerPrivateGStreamer::paintCurrentFrameInContext(GraphicsContext* context, const IntRect& rect)
2355 {
2356     m_videoLayer->paintCurrentFrameInContext(context, rect);
2357 }
2358
2359 #if USE(ACCELERATED_VIDEO_VAAPI)
2360 // Other device doesn't prefer such optimization, so enclose it in USE(ACCELERATED_VIDEO_VAAPI) macro
2361 IntSize MediaPlayerPrivateGStreamer::scaleHDVideoToDisplaySize(int videoWidth, int videoHeight, int displayWidth, int displayHeight) const
2362 {
2363     int fitWidth, fitHeight;
2364
2365 #if ENABLE(TIZEN_DLOG_SUPPORT)
2366     TIZEN_LOGI("videoWidth: %d, videoHeight: %d, displayWidth: %d, displayHeight: %d ", videoWidth, videoHeight, displayWidth, displayHeight);
2367 #endif
2368     fitWidth = videoWidth;
2369     fitHeight = videoHeight;
2370     if (displayWidth > 0 && displayHeight > 0) {
2371         // In case video is rotated, we always use a 'better'
2372         // orientation (landscape or portrait) to calculate fitWidth/fitHeight.
2373         // It means we use a bigger size which doesn't lose quality
2374         // in either landscape or portrait orientation
2375         if ((videoWidth > videoHeight && displayWidth < displayHeight)
2376             || (videoWidth < videoHeight && displayWidth > displayHeight)) {
2377             int tmp;
2378             tmp = displayWidth;
2379             displayWidth = displayHeight;
2380             displayHeight = tmp;
2381         }
2382
2383         if (videoWidth > displayWidth || videoHeight > displayHeight) {
2384             if (videoWidth * displayHeight > videoHeight * displayWidth) {
2385                 fitWidth = displayWidth;
2386                 fitHeight = videoHeight * displayWidth / videoWidth;
2387                 ASSERT(fitHeight <= displayHeight);
2388             } else {
2389                 fitWidth = videoWidth * displayHeight / videoHeight;
2390                 fitHeight = displayHeight;
2391                 ASSERT(fitWidth <= displayWidth);
2392             }
2393         }
2394     }
2395
2396     return IntSize(fitWidth, fitHeight);
2397 }
2398 #endif
2399 void MediaPlayerPrivateGStreamer::xWindowIdPrepared(GstMessage* message)
2400 {
2401     // It is called in streaming thread.
2402     // It should be used only to set window handle to video sink.
2403
2404     int videoWidth, videoHeight;
2405     gst_structure_get_int(message->structure, "video-width", &videoWidth);
2406     gst_structure_get_int(message->structure, "video-height", &videoHeight);
2407
2408 #if ENABLE(TIZEN_DLOG_SUPPORT)
2409     TIZEN_LOGI("videoWidth: %d, videoHeight: %d", videoWidth, videoHeight);
2410 #endif
2411
2412 #if USE(ACCELERATED_VIDEO_VAAPI)
2413     int displayWidth, displayHeight;
2414     gst_structure_get_int(message->structure, "display-width", &displayWidth);
2415     gst_structure_get_int(message->structure, "display-height", &displayHeight);
2416
2417     m_displaySize = IntSize(displayWidth, displayHeight);
2418     m_videoSize = scaleHDVideoToDisplaySize(videoWidth, videoHeight, displayWidth, displayHeight);
2419 #else
2420     m_videoSize = IntSize(videoWidth, videoHeight);
2421 #endif
2422     m_videoLayer->setOverlay(m_videoSize);
2423 }
2424
2425 #endif // ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2426 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2427
2428 #if ENABLE(TIZEN_WEBKIT2_PROXY)
2429 void MediaPlayerPrivateGStreamer::setProxy(GstElement* source)
2430 {
2431     SoupSession* session = WebCore::ResourceHandle::defaultSession();
2432     if (!session)
2433         return;
2434
2435     SoupURI* proxyUri = 0;
2436     g_object_get(session, SOUP_SESSION_PROXY_URI, &proxyUri, NULL);
2437     if (!proxyUri)
2438         return;
2439
2440     char* proxy = soup_uri_to_string(proxyUri, false);
2441     g_object_set(source, "proxy", proxy, NULL);
2442
2443     soup_uri_free(proxyUri);
2444     g_free(proxy);
2445 }
2446 #endif
2447
2448 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2449 void MediaPlayerPrivateGStreamer::suspend()
2450 {
2451     m_suspendTime = currentTime();
2452     gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
2453 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2454     if (m_audioSessionManager)
2455         m_audioSessionManager->setSoundState(ASM_STATE_STOP);
2456 #endif
2457 }
2458
2459 void MediaPlayerPrivateGStreamer::resume()
2460 {
2461     if (isLocalMediaStream()) {
2462         gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
2463 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2464         if (m_audioSessionManager)
2465             m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
2466 #endif
2467     } else {
2468         gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
2469 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2470         if (m_audioSessionManager)
2471             m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
2472 #endif
2473     }
2474 }
2475
2476 bool MediaPlayerPrivateGStreamer::isLocalMediaStream()
2477 {
2478     if (m_url.string().contains("camera://"))
2479         return true;
2480     else
2481         return false;
2482 }
2483 #endif // ENABLE(TIZEN_GSTREAMER_VIDEO)
2484
2485 }
2486
2487 #endif // USE(GSTREAMER)