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
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.
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.
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.
25 #include "MediaPlayerPrivateGStreamer.h"
27 #if ENABLE(VIDEO) && USE(GSTREAMER)
29 #include "ColorSpace.h"
30 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
31 #include "CookieJar.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"
45 #include "ImageGStreamer.h"
46 #include "ImageOrientation.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"
57 #include <gst/video/video.h>
60 #include <wtf/gobject/GOwnPtr.h>
61 #include <wtf/text/CString.h>
63 #ifdef GST_API_VERSION_1
64 #include <gst/audio/streamvolume.h>
66 #include <gst/interfaces/streamvolume.h>
69 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
72 #include "VideoLayerTizen.h"
73 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
75 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
77 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
79 #if ENABLE(TIZEN_MEDIA_STREAM)
80 #include "WebKitCameraSourceGStreamerTizen.h"
81 #endif // ENABLE(TIZEN_MEDIA_STREAM)
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.
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
98 #ifdef GST_API_VERSION_1
99 static const char* gPlaybinName = "playbin";
101 static const char* gPlaybinName = "playbin2";
104 GST_DEBUG_CATEGORY_STATIC(webkit_media_player_debug);
105 #define GST_CAT_DEFAULT webkit_media_player_debug
111 static int greatestCommonDivisor(int a, int b)
122 static gboolean mediaPlayerPrivateMessageCallback(GstBus*, GstMessage* message, MediaPlayerPrivateGStreamer* player)
124 return player->handleMessage(message);
127 static void mediaPlayerPrivateSourceChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
129 player->sourceChanged();
132 static void mediaPlayerPrivateVolumeChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
134 // This is called when playbin receives the notify::volume signal.
135 player->volumeChanged();
138 static gboolean mediaPlayerPrivateVolumeChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
140 // This is the callback of the timeout source created in ::volumeChanged.
141 player->notifyPlayerOfVolumeChange();
145 static void mediaPlayerPrivateMuteChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
147 // This is called when playbin receives the notify::mute signal.
148 player->muteChanged();
151 static gboolean mediaPlayerPrivateMuteChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
153 // This is the callback of the timeout source created in ::muteChanged.
154 player->notifyPlayerOfMute();
158 static void mediaPlayerPrivateVideoSinkCapsChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
160 player->videoChanged();
163 static void mediaPlayerPrivateVideoChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
165 player->videoChanged();
168 static void mediaPlayerPrivateAudioChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
170 player->audioChanged();
173 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
174 static void mediaPlayerPrivateSourceSetupCallback(GObject*, GstElement* source, MediaPlayerPrivateGStreamer* player)
176 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->player()->mediaPlayerClient());
178 // Grab the current document
179 Document* document = element->document();
181 document = element->ownerDocument();
183 // Grab the frame and network manager
184 Frame* frame = document ? document->frame() : 0;
185 FrameLoader* frameLoader = frame ? frame->loader() : 0;
187 String cookie = cookies(document, player->url());
188 if (!cookie.length())
189 cookie = cookieRequestHeaderFieldValue(document, player->url());
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);
195 #if ENABLE(TIZEN_WEBKIT2_PROXY)
196 player->setProxy(source);
200 g_object_set(source, "user-agent", frameLoader->userAgent(player->url()).utf8().data(), NULL);
204 static gboolean mediaPlayerPrivateAudioChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
206 // This is the callback of the timeout source created in ::audioChanged.
207 player->notifyPlayerOfAudio();
211 static gboolean mediaPlayerPrivateVideoChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
213 // This is the callback of the timeout source created in ::videoChanged.
214 player->notifyPlayerOfVideo();
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)
221 playerPrivate->triggerRepaint(buffer);
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)
228 // ignore anything but 'prepare-xid' message
229 if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_ELEMENT)
231 if (!gst_structure_has_name (message->structure, "prepare-xid"))
234 playerPrivate->xWindowIdPrepared(message);
239 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
240 static ASM_cb_result_t MediaPlayerAudioSessionEventSourcePause(ASM_event_sources_t eventSource, void* callbackData)
242 MediaPlayer* player = static_cast<MediaPlayer*>(callbackData);
244 return ASM_CB_RES_IGNORE;
246 switch (eventSource) {
247 case ASM_EVENT_SOURCE_CALL_START:
248 case ASM_EVENT_SOURCE_ALARM_START:
249 case ASM_EVENT_SOURCE_MEDIA:
250 case ASM_EVENT_SOURCE_EMERGENCY_START:
251 case ASM_EVENT_SOURCE_OTHER_PLAYER_APP:
252 case ASM_EVENT_SOURCE_RESOURCE_CONFLICT:
253 case ASM_EVENT_SOURCE_EARJACK_UNPLUG:
254 if (!player->url().string().contains("camera://")) {
256 return ASM_CB_RES_PAUSE;
259 return ASM_CB_RES_NONE;
263 static ASM_cb_result_t MediaPlayerAudioSessionEventSourcePlay(ASM_event_sources_t eventSource, void* callbackData)
265 MediaPlayer* player = static_cast<MediaPlayer*>(callbackData);
266 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->mediaPlayerClient());
268 return ASM_CB_RES_IGNORE;
270 switch (eventSource) {
271 case ASM_EVENT_SOURCE_ALARM_END:
272 if (!element->isVideo() && !player->url().string().contains("camera://")) {
274 return ASM_CB_RES_PLAYING;
276 return ASM_CB_RES_NONE;
278 return ASM_CB_RES_NONE;
282 static ASM_cb_result_t mediaPlayerPrivateAudioSessionNotifyCallback(int, ASM_event_sources_t eventSource, ASM_sound_commands_t command, unsigned int, void* callbackData)
284 if (command == ASM_COMMAND_STOP || command == ASM_COMMAND_PAUSE)
285 return MediaPlayerAudioSessionEventSourcePause(eventSource, callbackData);
286 if (command == ASM_COMMAND_PLAY || command == ASM_COMMAND_RESUME)
287 return MediaPlayerAudioSessionEventSourcePlay(eventSource, callbackData);
289 return ASM_CB_RES_NONE;
293 PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivateGStreamer::create(MediaPlayer* player)
295 return adoptPtr(new MediaPlayerPrivateGStreamer(player));
298 void MediaPlayerPrivateGStreamer::registerMediaEngine(MediaEngineRegistrar registrar)
301 registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
304 bool initializeGStreamerAndRegisterWebKitElements()
306 if (!initializeGStreamer())
309 GRefPtr<GstElementFactory> srcFactory = gst_element_factory_find("webkitwebsrc");
311 #if ENABLE(TIZEN_MEDIA_STREAM)
312 return gst_element_register(0, "webkitcamerasrc", GST_RANK_PRIMARY + 200, WEBKIT_TYPE_CAMERA_SRC);
314 GST_DEBUG_CATEGORY_INIT(webkit_media_player_debug, "webkitmediaplayer", 0, "WebKit media player");
315 return gst_element_register(0, "webkitwebsrc", GST_RANK_PRIMARY + 100, WEBKIT_TYPE_WEB_SRC);
316 #endif // ENABLE(TIZEN_MEDIA_STREAM)
321 bool MediaPlayerPrivateGStreamer::isAvailable()
323 if (!initializeGStreamerAndRegisterWebKitElements())
326 GRefPtr<GstElementFactory> factory = gst_element_factory_find(gPlaybinName);
330 MediaPlayerPrivateGStreamer::MediaPlayerPrivateGStreamer(MediaPlayer* player)
332 , m_webkitVideoSink(0)
333 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
339 , m_changingRate(false)
340 , m_endTime(numeric_limits<float>::infinity())
341 , m_isEndReached(false)
342 , m_networkState(MediaPlayer::Empty)
343 , m_readyState(MediaPlayer::HaveNothing)
344 , m_isStreaming(false)
347 , m_mediaLocations(0)
348 , m_mediaLocationCurrentIndex(0)
349 , m_resetPipeline(false)
354 , m_errorOccured(false)
356 , m_startedBuffering(false)
357 , m_fillTimer(this, &MediaPlayerPrivateGStreamer::fillTimerFired)
359 , m_bufferingPercentage(0)
360 , m_preload(MediaPlayer::Auto)
361 , m_delayingLoad(false)
362 , m_mediaDurationKnown(true)
363 , m_maxTimeLoadedAtLastDidLoadingProgress(0)
364 , m_volumeTimerHandler(0)
365 , m_muteTimerHandler(0)
368 , m_audioTimerHandler(0)
369 , m_videoTimerHandler(0)
370 , m_webkitAudioSink(0)
372 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
373 , m_videoLayer(VideoLayerTizen::create(static_cast<HTMLMediaElement*>(player->mediaPlayerClient())))
374 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
375 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
376 , m_audioSessionManager(AudioSessionManagerGStreamerTizen::createAudioSessionManager())
378 , m_originalPreloadWasAutoAndWasOverridden(false)
379 , m_preservesPitch(false)
380 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
386 MediaPlayerPrivateGStreamer::~MediaPlayerPrivateGStreamer()
388 if (m_fillTimer.isActive())
392 gst_buffer_unref(m_buffer);
395 if (m_mediaLocations) {
396 gst_structure_free(m_mediaLocations);
397 m_mediaLocations = 0;
400 #ifndef GST_API_VERSION_1
401 if (m_videoSinkBin) {
402 gst_object_unref(m_videoSinkBin);
408 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
410 g_signal_handlers_disconnect_by_func(bus.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateMessageCallback), this);
411 gst_bus_remove_signal_watch(bus.get());
413 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
419 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
420 if (m_audioSessionManager)
421 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
424 if (m_muteTimerHandler)
425 g_source_remove(m_muteTimerHandler);
427 if (m_volumeTimerHandler)
428 g_source_remove(m_volumeTimerHandler);
430 if (m_videoTimerHandler)
431 g_source_remove(m_videoTimerHandler);
433 if (m_audioTimerHandler)
434 g_source_remove(m_audioTimerHandler);
437 void MediaPlayerPrivateGStreamer::load(const String& url)
439 if (!initializeGStreamerAndRegisterWebKitElements())
442 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
444 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
445 KURL kurl(KURL(), url);
446 String cleanUrl(url);
448 // Clean out everything after file:// url path.
449 if (kurl.isLocalFile())
450 cleanUrl = cleanUrl.substring(0, kurl.pathEnd());
454 setDownloadBuffering();
459 m_url = KURL(KURL(), cleanUrl);
460 g_object_set(m_playBin.get(), "uri", cleanUrl.utf8().data(), NULL);
462 LOG_MEDIA_MESSAGE("Load %s", cleanUrl.utf8().data());
464 if (m_preload == MediaPlayer::None) {
465 LOG_MEDIA_MESSAGE("Delaying load.");
466 m_delayingLoad = true;
469 // Reset network and ready states. Those will be set properly once
470 // the pipeline pre-rolled.
471 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
473 m_networkState = MediaPlayer::Loading;
475 m_networkState = MediaPlayer::Idle;
477 m_networkState = MediaPlayer::Loading;
479 m_player->networkStateChanged();
480 m_readyState = MediaPlayer::HaveNothing;
481 m_player->readyStateChanged();
482 m_volumeAndMuteInitialized = false;
484 // GStreamer needs to have the pipeline set to a paused state to
485 // start providing anything useful.
486 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
489 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
491 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
492 if (m_audioSessionManager && !m_delayingLoad)
493 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
500 void MediaPlayerPrivateGStreamer::commitLoad()
502 ASSERT(!m_delayingLoad);
503 LOG_MEDIA_MESSAGE("Committing load.");
507 float MediaPlayerPrivateGStreamer::playbackPosition() const
509 if (m_isEndReached) {
510 // Position queries on a null pipeline return 0. If we're at
511 // the end of the stream the pipeline is null but we want to
512 // report either the seek time or the duration because this is
513 // what the Media element spec expects us to do.
517 return m_mediaDuration;
522 GstQuery* query = gst_query_new_position(GST_FORMAT_TIME);
523 if (!gst_element_query(m_playBin.get(), query)) {
524 LOG_MEDIA_MESSAGE("Position query failed...");
525 gst_query_unref(query);
530 gst_query_parse_position(query, 0, &position);
532 // Position is available only if the pipeline is not in GST_STATE_NULL or
533 // GST_STATE_READY state.
534 if (position != static_cast<gint64>(GST_CLOCK_TIME_NONE))
535 ret = static_cast<double>(position) / GST_SECOND;
537 LOG_MEDIA_MESSAGE("Position %" GST_TIME_FORMAT, GST_TIME_ARGS(position));
539 gst_query_unref(query);
544 bool MediaPlayerPrivateGStreamer::changePipelineState(GstState newState)
546 ASSERT(newState == GST_STATE_PLAYING || newState == GST_STATE_PAUSED);
548 GstState currentState;
551 gst_element_get_state(m_playBin.get(), ¤tState, &pending, 0);
552 LOG_MEDIA_MESSAGE("Current state: %s, pending: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
553 #if ENABLE(TIZEN_DLOG_SUPPORT)
554 TIZEN_LOGI("Current state: %s, New state: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(newState));
556 if (currentState == newState || pending == newState)
559 GstStateChangeReturn setStateResult = gst_element_set_state(m_playBin.get(), newState);
560 GstState pausedOrPlaying = newState == GST_STATE_PLAYING ? GST_STATE_PAUSED : GST_STATE_PLAYING;
561 if (currentState != pausedOrPlaying && setStateResult == GST_STATE_CHANGE_FAILURE) {
562 loadingFailed(MediaPlayer::Empty);
568 void MediaPlayerPrivateGStreamer::prepareToPlay()
570 m_isEndReached = false;
573 if (m_delayingLoad) {
574 m_delayingLoad = false;
579 void MediaPlayerPrivateGStreamer::play()
581 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
582 if (!m_audioSessionManager->setSoundState(ASM_STATE_PLAYING) && !isLocalMediaStream())
585 if (changePipelineState(GST_STATE_PLAYING)) {
586 m_isEndReached = false;
587 LOG_MEDIA_MESSAGE("Play");
591 void MediaPlayerPrivateGStreamer::pause()
593 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
594 if (!m_audioSessionManager->setSoundState(ASM_STATE_PAUSE) && !isLocalMediaStream())
600 if (changePipelineState(GST_STATE_PAUSED))
601 LOG_MEDIA_MESSAGE("Pause");
604 float MediaPlayerPrivateGStreamer::duration() const
612 // Media duration query failed already, don't attempt new useless queries.
613 if (!m_mediaDurationKnown)
614 return numeric_limits<float>::infinity();
617 return m_mediaDuration;
619 GstFormat timeFormat = GST_FORMAT_TIME;
620 gint64 timeLength = 0;
622 #ifdef GST_API_VERSION_1
623 bool failure = !gst_element_query_duration(m_playBin.get(), timeFormat, &timeLength) || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
625 bool failure = !gst_element_query_duration(m_playBin.get(), &timeFormat, &timeLength) || timeFormat != GST_FORMAT_TIME || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
628 LOG_MEDIA_MESSAGE("Time duration query failed for %s", m_url.string().utf8().data());
629 return numeric_limits<float>::infinity();
632 LOG_MEDIA_MESSAGE("Duration: %" GST_TIME_FORMAT, GST_TIME_ARGS(timeLength));
634 return static_cast<double>(timeLength) / GST_SECOND;
635 // FIXME: handle 3.14.9.5 properly
638 float MediaPlayerPrivateGStreamer::currentTime() const
650 // https://bugzilla.gnome.org/show_bug.cgi?id=639941 In GStreamer
651 // 0.10.35 basesink reports wrong duration in case of EOS and
652 // negative playback rate. There's no upstream accepted patch for
653 // this bug yet, hence this temporary workaround.
654 if (m_isEndReached && m_playbackRate < 0)
657 return playbackPosition();
661 void MediaPlayerPrivateGStreamer::seek(float time)
669 LOG_MEDIA_MESSAGE("Seek attempt to %f secs", time);
670 #if ENABLE(TIZEN_DLOG_SUPPORT)
671 TIZEN_LOGI("Seek attempt to %f secs", time);
674 // Avoid useless seeking.
675 if (time == currentTime())
678 // Extract the integer part of the time (seconds) and the
679 // fractional part (microseconds). Attempt to round the
680 // microseconds so no floating point precision is lost and we can
681 // perform an accurate seek.
683 float microSeconds = modf(time, &seconds) * 1000000;
685 timeValue.tv_sec = static_cast<glong>(seconds);
686 timeValue.tv_usec = static_cast<glong>(roundf(microSeconds / 10000) * 10000);
688 GstClockTime clockTime = GST_TIMEVAL_TO_TIME(timeValue);
689 LOG_MEDIA_MESSAGE("Seek: %" GST_TIME_FORMAT, GST_TIME_ARGS(clockTime));
691 if (!gst_element_seek(m_playBin.get(), m_player->rate(),
693 (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE),
694 GST_SEEK_TYPE_SET, clockTime,
695 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) {
696 LOG_MEDIA_MESSAGE("Seek to %f failed", time);
697 #if ENABLE(TIZEN_DLOG_SUPPORT)
698 TIZEN_LOGE("Seek to %f failed", time);
703 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
704 m_isEndReached = false;
709 bool MediaPlayerPrivateGStreamer::paused() const
711 if (m_isEndReached) {
712 LOG_MEDIA_MESSAGE("Ignoring pause at EOS");
717 gst_element_get_state(m_playBin.get(), &state, 0, 0);
718 return state == GST_STATE_PAUSED;
721 bool MediaPlayerPrivateGStreamer::seeking() const
726 // Returns the size of the video
727 IntSize MediaPlayerPrivateGStreamer::naturalSize() const
732 if (!m_videoSize.isEmpty())
735 GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
740 // TODO: handle possible clean aperture data. See
741 // https://bugzilla.gnome.org/show_bug.cgi?id=596571
742 // TODO: handle possible transformation matrix. See
743 // https://bugzilla.gnome.org/show_bug.cgi?id=596326
745 // Get the video PAR and original size, if this fails the
746 // video-sink has likely not yet negotiated its caps.
747 int pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride;
748 IntSize originalSize;
749 GstVideoFormat format;
750 if (!getVideoSizeAndFormatFromCaps(caps.get(), originalSize, format, pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride))
753 LOG_MEDIA_MESSAGE("Original video size: %dx%d", originalSize.width(), originalSize.height());
754 LOG_MEDIA_MESSAGE("Pixel aspect ratio: %d/%d", pixelAspectRatioNumerator, pixelAspectRatioDenominator);
756 // Calculate DAR based on PAR and video size.
757 int displayWidth = originalSize.width() * pixelAspectRatioNumerator;
758 int displayHeight = originalSize.height() * pixelAspectRatioDenominator;
760 // Divide display width and height by their GCD to avoid possible overflows.
761 int displayAspectRatioGCD = greatestCommonDivisor(displayWidth, displayHeight);
762 displayWidth /= displayAspectRatioGCD;
763 displayHeight /= displayAspectRatioGCD;
765 // Apply DAR to original video size. This is the same behavior as in xvimagesink's setcaps function.
766 guint64 width = 0, height = 0;
767 if (!(originalSize.height() % displayHeight)) {
768 LOG_MEDIA_MESSAGE("Keeping video original height");
769 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
770 height = static_cast<guint64>(originalSize.height());
771 } else if (!(originalSize.width() % displayWidth)) {
772 LOG_MEDIA_MESSAGE("Keeping video original width");
773 height = gst_util_uint64_scale_int(originalSize.width(), displayHeight, displayWidth);
774 width = static_cast<guint64>(originalSize.width());
776 LOG_MEDIA_MESSAGE("Approximating while keeping original video height");
777 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
778 height = static_cast<guint64>(originalSize.height());
781 LOG_MEDIA_MESSAGE("Natural size: %" G_GUINT64_FORMAT "x%" G_GUINT64_FORMAT, width, height);
782 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE) && USE(ACCELERATED_VIDEO_VAAPI)
783 if (!m_displaySize.isEmpty())
784 m_videoSize = scaleHDVideoToDisplaySize(static_cast<int>(width), static_cast<int>(height), m_displaySize.width(), m_displaySize.height());
787 m_videoSize = IntSize(static_cast<int>(width), static_cast<int>(height));
791 void MediaPlayerPrivateGStreamer::videoChanged()
793 if (m_videoTimerHandler)
794 g_source_remove(m_videoTimerHandler);
795 m_videoTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVideoChangeTimeoutCallback), this);
798 void MediaPlayerPrivateGStreamer::notifyPlayerOfVideo()
800 m_videoTimerHandler = 0;
802 gint videoTracks = 0;
804 g_object_get(m_playBin.get(), "n-video", &videoTracks, NULL);
806 m_hasVideo = videoTracks > 0;
808 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
810 if (gst_video_get_size(m_videoSinkPad.get(), &width, &height)) {
811 IntSize size(width, height);
812 if (m_videoSize != size) {
813 m_videoSize = IntSize();
814 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
815 m_videoLayer->setOverlay(naturalSize());
820 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
821 #else // ENABLE(TIZEN_GSTREAMER_VIDEO)
822 m_videoSize = IntSize();
824 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
828 void MediaPlayerPrivateGStreamer::audioChanged()
830 if (m_audioTimerHandler)
831 g_source_remove(m_audioTimerHandler);
832 m_audioTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateAudioChangeTimeoutCallback), this);
835 void MediaPlayerPrivateGStreamer::notifyPlayerOfAudio()
837 m_audioTimerHandler = 0;
839 gint audioTracks = 0;
841 g_object_get(m_playBin.get(), "n-audio", &audioTracks, NULL);
842 m_hasAudio = audioTracks > 0;
843 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
846 void MediaPlayerPrivateGStreamer::setVolume(float volume)
851 gst_stream_volume_set_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC,
852 static_cast<double>(volume));
855 void MediaPlayerPrivateGStreamer::notifyPlayerOfVolumeChange()
857 m_volumeTimerHandler = 0;
859 if (!m_player || !m_playBin)
862 volume = gst_stream_volume_get_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC);
863 // get_volume() can return values superior to 1.0 if the user
864 // applies software user gain via third party application (GNOME
865 // volume control for instance).
866 volume = CLAMP(volume, 0.0, 1.0);
867 m_player->volumeChanged(static_cast<float>(volume));
870 void MediaPlayerPrivateGStreamer::volumeChanged()
872 if (m_volumeTimerHandler)
873 g_source_remove(m_volumeTimerHandler);
874 m_volumeTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVolumeChangeTimeoutCallback), this);
877 void MediaPlayerPrivateGStreamer::setRate(float rate)
879 // Avoid useless playback rate update.
880 if (m_playbackRate == rate)
886 gst_element_get_state(m_playBin.get(), &state, &pending, 0);
887 if ((state != GST_STATE_PLAYING && state != GST_STATE_PAUSED)
888 || (pending == GST_STATE_PAUSED))
894 m_playbackRate = rate;
895 m_changingRate = true;
898 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
899 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
900 if (m_audioSessionManager)
901 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
906 float currentPosition = static_cast<float>(playbackPosition() * GST_SECOND);
907 GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH);
911 LOG_MEDIA_MESSAGE("Set Rate to %f", rate);
913 // Mute the sound if the playback rate is too extreme and
914 // audio pitch is not adjusted.
915 mute = (!m_preservesPitch && (rate < 0.8 || rate > 2));
916 start = currentPosition;
917 end = GST_CLOCK_TIME_NONE;
922 // If we are at beginning of media, start from the end to
923 // avoid immediate EOS.
924 if (currentPosition <= 0)
925 end = static_cast<gint64>(duration() * GST_SECOND);
927 end = currentPosition;
930 LOG_MEDIA_MESSAGE("Need to mute audio: %d", (int) mute);
932 if (!gst_element_seek(m_playBin.get(), rate, GST_FORMAT_TIME, flags,
933 GST_SEEK_TYPE_SET, start,
934 GST_SEEK_TYPE_SET, end))
935 LOG_MEDIA_MESSAGE("Set rate to %f failed", rate);
937 g_object_set(m_playBin.get(), "mute", mute, NULL);
940 void MediaPlayerPrivateGStreamer::setPreservesPitch(bool preservesPitch)
942 m_preservesPitch = preservesPitch;
945 MediaPlayer::NetworkState MediaPlayerPrivateGStreamer::networkState() const
947 return m_networkState;
950 MediaPlayer::ReadyState MediaPlayerPrivateGStreamer::readyState() const
955 PassRefPtr<TimeRanges> MediaPlayerPrivateGStreamer::buffered() const
957 RefPtr<TimeRanges> timeRanges = TimeRanges::create();
958 if (m_errorOccured || isLiveStream())
959 return timeRanges.release();
961 #if GST_CHECK_VERSION(0, 10, 31)
962 float mediaDuration(duration());
963 if (!mediaDuration || isinf(mediaDuration))
964 return timeRanges.release();
966 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
968 if (!gst_element_query(m_playBin.get(), query)) {
969 gst_query_unref(query);
970 return timeRanges.release();
973 gint64 rangeStart = 0, rangeStop = 0;
974 for (guint index = 0; index < gst_query_get_n_buffering_ranges(query); index++) {
975 if (gst_query_parse_nth_buffering_range(query, index, &rangeStart, &rangeStop))
976 timeRanges->add(static_cast<float>((rangeStart * mediaDuration) / 100),
977 static_cast<float>((rangeStop * mediaDuration) / 100));
980 // Fallback to the more general maxTimeLoaded() if no range has
982 if (!timeRanges->length())
983 if (float loaded = maxTimeLoaded())
984 timeRanges->add(0, loaded);
986 gst_query_unref(query);
988 float loaded = maxTimeLoaded();
989 if (!m_errorOccured && !isLiveStream() && loaded > 0)
990 timeRanges->add(0, loaded);
992 return timeRanges.release();
995 gboolean MediaPlayerPrivateGStreamer::handleMessage(GstMessage* message)
998 GOwnPtr<gchar> debug;
999 MediaPlayer::NetworkState error;
1000 bool issueError = true;
1001 bool attemptNextLocation = false;
1002 const GstStructure* structure = gst_message_get_structure(message);
1005 const gchar* messageTypeName = gst_structure_get_name(structure);
1007 // Redirect messages are sent from elements, like qtdemux, to
1008 // notify of the new location(s) of the media.
1009 if (!g_strcmp0(messageTypeName, "redirect")) {
1010 mediaLocationChanged(message);
1015 LOG_MEDIA_MESSAGE("Message received from element %s", GST_MESSAGE_SRC_NAME(message));
1016 switch (GST_MESSAGE_TYPE(message)) {
1017 case GST_MESSAGE_ERROR:
1018 if (m_resetPipeline)
1020 gst_message_parse_error(message, &err.outPtr(), &debug.outPtr());
1021 LOG_MEDIA_MESSAGE("Error %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1023 #if ENABLE(TIZEN_DLOG_SUPPORT)
1024 TIZEN_LOGE("GST_MESSAGE_ERROR %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1027 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, "webkit-video.error");
1029 error = MediaPlayer::Empty;
1030 if (err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND
1031 || err->code == GST_STREAM_ERROR_WRONG_TYPE
1032 || err->code == GST_STREAM_ERROR_FAILED
1033 || err->code == GST_CORE_ERROR_MISSING_PLUGIN
1034 || err->code == GST_RESOURCE_ERROR_NOT_FOUND)
1035 error = MediaPlayer::FormatError;
1036 else if (err->domain == GST_STREAM_ERROR) {
1037 // Let the mediaPlayerClient handle the stream error, in
1038 // this case the HTMLMediaElement will emit a stalled
1040 #if !ENABLE(TIZEN_MEDIA_STREAM)
1041 if (err->code == GST_STREAM_ERROR_TYPE_NOT_FOUND) {
1042 LOG_MEDIA_MESSAGE("Decode error, let the Media element emit a stalled event.");
1046 error = MediaPlayer::DecodeError;
1047 attemptNextLocation = true;
1048 } else if (err->domain == GST_RESOURCE_ERROR)
1049 error = MediaPlayer::NetworkError;
1051 if (attemptNextLocation)
1052 issueError = !loadNextLocation();
1054 loadingFailed(error);
1056 case GST_MESSAGE_EOS:
1057 LOG_MEDIA_MESSAGE("End of Stream");
1060 case GST_MESSAGE_STATE_CHANGED:
1061 // Ignore state changes if load is delayed (preload=none). The
1062 // player state will be updated once commitLoad() is called.
1063 if (m_delayingLoad) {
1064 LOG_MEDIA_MESSAGE("Media load has been delayed. Ignoring state changes for now");
1068 // Ignore state changes from internal elements. They are
1069 // forwarded to playbin2 anyway.
1070 if (GST_MESSAGE_SRC(message) == reinterpret_cast<GstObject*>(m_playBin.get())) {
1073 // Construct a filename for the graphviz dot file output.
1074 GstState oldState, newState;
1075 gst_message_parse_state_changed(message, &oldState, &newState, 0);
1077 CString dotFileName = String::format("webkit-video.%s_%s",
1078 gst_element_state_get_name(oldState),
1079 gst_element_state_get_name(newState)).utf8();
1081 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, dotFileName.data());
1083 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1084 if (m_suspendTime > 0 && newState == GST_STATE_PAUSED) {
1085 if (!isLocalMediaStream())
1086 seek(m_suspendTime);
1088 m_player->mediaPlayerClient()->setSuspended(false);
1093 case GST_MESSAGE_BUFFERING:
1094 processBufferingStats(message);
1096 case GST_MESSAGE_DURATION:
1097 LOG_MEDIA_MESSAGE("Duration changed");
1101 LOG_MEDIA_MESSAGE("Unhandled GStreamer message type: %s",
1102 GST_MESSAGE_TYPE_NAME(message));
1108 void MediaPlayerPrivateGStreamer::processBufferingStats(GstMessage* message)
1110 // This is the immediate buffering that needs to happen so we have
1111 // enough to play right now.
1113 const GstStructure *structure = gst_message_get_structure(message);
1114 gst_structure_get_int(structure, "buffer-percent", &m_bufferingPercentage);
1116 LOG_MEDIA_MESSAGE("[Buffering] Buffering: %d%%.", m_bufferingPercentage);
1118 GstBufferingMode mode;
1119 gst_message_parse_buffering_stats(message, &mode, 0, 0, 0);
1120 if (mode != GST_BUFFERING_DOWNLOAD) {
1125 // This is on-disk buffering, that allows us to download much more
1126 // than needed for right now.
1127 if (!m_startedBuffering) {
1128 LOG_MEDIA_MESSAGE("[Buffering] Starting on-disk buffering.");
1130 m_startedBuffering = true;
1132 if (m_fillTimer.isActive())
1135 m_fillTimer.startRepeating(0.2);
1139 void MediaPlayerPrivateGStreamer::fillTimerFired(Timer<MediaPlayerPrivateGStreamer>*)
1141 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
1143 if (!gst_element_query(m_playBin.get(), query)) {
1144 gst_query_unref(query);
1149 gdouble fillStatus = 100.0;
1151 gst_query_parse_buffering_range(query, 0, &start, &stop, 0);
1152 gst_query_unref(query);
1155 fillStatus = 100.0 * stop / GST_FORMAT_PERCENT_MAX;
1157 LOG_MEDIA_MESSAGE("[Buffering] Download buffer filled up to %f%%", fillStatus);
1159 if (!m_mediaDuration)
1162 // Update maxTimeLoaded only if the media duration is
1163 // available. Otherwise we can't compute it.
1164 if (m_mediaDuration) {
1165 if (fillStatus == 100.0)
1166 m_maxTimeLoaded = m_mediaDuration;
1168 m_maxTimeLoaded = static_cast<float>((fillStatus * m_mediaDuration) / 100.0);
1169 LOG_MEDIA_MESSAGE("[Buffering] Updated maxTimeLoaded: %f", m_maxTimeLoaded);
1172 if (fillStatus != 100.0) {
1177 // Media is now fully loaded. It will play even if network
1178 // connection is cut. Buffering is done, remove the fill source
1179 // from the main loop.
1181 m_startedBuffering = false;
1185 float MediaPlayerPrivateGStreamer::maxTimeSeekable() const
1190 LOG_MEDIA_MESSAGE("maxTimeSeekable");
1191 // infinite duration means live stream
1192 if (isinf(duration()))
1198 float MediaPlayerPrivateGStreamer::maxTimeLoaded() const
1203 float loaded = m_maxTimeLoaded;
1204 if (!loaded && !m_fillTimer.isActive())
1205 loaded = duration();
1206 LOG_MEDIA_MESSAGE("maxTimeLoaded: %f", loaded);
1210 bool MediaPlayerPrivateGStreamer::didLoadingProgress() const
1212 if (!m_playBin || !m_mediaDuration || !totalBytes())
1214 float currentMaxTimeLoaded = maxTimeLoaded();
1215 bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
1216 m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
1217 LOG_MEDIA_MESSAGE("didLoadingProgress: %d", didLoadingProgress);
1218 return didLoadingProgress;
1221 unsigned MediaPlayerPrivateGStreamer::totalBytes() const
1226 if (m_totalBytes != -1)
1227 return m_totalBytes;
1232 GstFormat fmt = GST_FORMAT_BYTES;
1234 #ifdef GST_API_VERSION_1
1235 if (gst_element_query_duration(m_source.get(), fmt, &length)) {
1237 if (gst_element_query_duration(m_source.get(), &fmt, &length)) {
1239 LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1240 m_totalBytes = static_cast<unsigned>(length);
1241 m_isStreaming = !length;
1242 return m_totalBytes;
1245 // Fall back to querying the source pads manually.
1246 // See also https://bugzilla.gnome.org/show_bug.cgi?id=638749
1247 GstIterator* iter = gst_element_iterate_src_pads(m_source.get());
1250 #ifdef GST_API_VERSION_1
1251 GValue item = G_VALUE_INIT;
1252 switch (gst_iterator_next(iter, &item)) {
1253 case GST_ITERATOR_OK: {
1254 GstPad* pad = static_cast<GstPad*>(g_value_get_object(&item));
1255 gint64 padLength = 0;
1256 if (gst_pad_query_duration(pad, fmt, &padLength) && padLength > length)
1263 switch (gst_iterator_next(iter, &data)) {
1264 case GST_ITERATOR_OK: {
1265 GRefPtr<GstPad> pad = adoptGRef(GST_PAD_CAST(data));
1266 gint64 padLength = 0;
1267 if (gst_pad_query_duration(pad.get(), &fmt, &padLength) && padLength > length)
1272 case GST_ITERATOR_RESYNC:
1273 gst_iterator_resync(iter);
1275 case GST_ITERATOR_ERROR:
1277 case GST_ITERATOR_DONE:
1282 #ifdef GST_API_VERSION_1
1283 g_value_unset(&item);
1287 gst_iterator_free(iter);
1289 LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1290 m_totalBytes = static_cast<unsigned>(length);
1291 m_isStreaming = !length;
1292 return m_totalBytes;
1295 unsigned MediaPlayerPrivateGStreamer::decodedFrameCount() const
1297 guint64 decodedFrames = 0;
1299 g_object_get(m_fpsSink, "frames-rendered", &decodedFrames, NULL);
1300 return static_cast<unsigned>(decodedFrames);
1303 unsigned MediaPlayerPrivateGStreamer::droppedFrameCount() const
1305 guint64 framesDropped = 0;
1307 g_object_get(m_fpsSink, "frames-dropped", &framesDropped, NULL);
1308 return static_cast<unsigned>(framesDropped);
1311 unsigned MediaPlayerPrivateGStreamer::audioDecodedByteCount() const
1313 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1314 gint64 position = 0;
1316 if (m_webkitAudioSink && gst_element_query(m_webkitAudioSink.get(), query))
1317 gst_query_parse_position(query, 0, &position);
1319 gst_query_unref(query);
1320 return static_cast<unsigned>(position);
1323 unsigned MediaPlayerPrivateGStreamer::videoDecodedByteCount() const
1325 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1326 gint64 position = 0;
1328 if (gst_element_query(m_webkitVideoSink, query))
1329 gst_query_parse_position(query, 0, &position);
1331 gst_query_unref(query);
1332 return static_cast<unsigned>(position);
1335 void MediaPlayerPrivateGStreamer::updateAudioSink()
1340 GstElement* sinkPtr = 0;
1342 g_object_get(m_playBin.get(), "audio-sink", &sinkPtr, NULL);
1343 m_webkitAudioSink = adoptGRef(sinkPtr);
1348 void MediaPlayerPrivateGStreamer::sourceChanged()
1350 GstElement* srcPtr = 0;
1352 g_object_get(m_playBin.get(), "source", &srcPtr, NULL);
1353 m_source = adoptGRef(srcPtr);
1355 if (WEBKIT_IS_WEB_SRC(m_source.get()))
1356 webKitWebSrcSetMediaPlayer(WEBKIT_WEB_SRC(m_source.get()), m_player);
1359 void MediaPlayerPrivateGStreamer::cancelLoad()
1361 if (m_networkState < MediaPlayer::Loading || m_networkState == MediaPlayer::Loaded)
1365 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1366 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1367 if (m_audioSessionManager)
1368 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
1372 void MediaPlayerPrivateGStreamer::updateStates()
1380 MediaPlayer::NetworkState oldNetworkState = m_networkState;
1381 MediaPlayer::ReadyState oldReadyState = m_readyState;
1385 GstStateChangeReturn ret = gst_element_get_state(m_playBin.get(),
1386 &state, &pending, 250 * GST_NSECOND);
1388 bool shouldUpdateAfterSeek = false;
1390 case GST_STATE_CHANGE_SUCCESS:
1391 LOG_MEDIA_MESSAGE("State: %s, pending: %s",
1392 gst_element_state_get_name(state),
1393 gst_element_state_get_name(pending));
1395 m_resetPipeline = state <= GST_STATE_READY;
1397 // Try to figure out ready and network states.
1398 if (state == GST_STATE_READY) {
1399 m_readyState = MediaPlayer::HaveMetadata;
1400 m_networkState = MediaPlayer::Empty;
1401 // Cache the duration without emiting the durationchange
1402 // event because it's taken care of by the media element
1403 // in this precise case.
1404 if (!m_isEndReached)
1406 } else if ((state == GST_STATE_NULL) || (maxTimeLoaded() == duration())) {
1407 m_networkState = MediaPlayer::Loaded;
1408 m_readyState = MediaPlayer::HaveEnoughData;
1410 m_readyState = currentTime() < maxTimeLoaded() ? MediaPlayer::HaveFutureData : MediaPlayer::HaveCurrentData;
1411 m_networkState = MediaPlayer::Loading;
1414 if (m_buffering && state != GST_STATE_READY) {
1415 m_readyState = MediaPlayer::HaveCurrentData;
1416 m_networkState = MediaPlayer::Loading;
1419 // Now let's try to get the states in more detail using
1420 // information from GStreamer, while we sync states where
1422 if (state == GST_STATE_PAUSED) {
1423 if (!m_webkitAudioSink)
1426 if (!m_volumeAndMuteInitialized) {
1427 notifyPlayerOfVolumeChange();
1428 notifyPlayerOfMute();
1429 m_volumeAndMuteInitialized = true;
1432 if (m_buffering && m_bufferingPercentage == 100) {
1433 m_buffering = false;
1434 m_bufferingPercentage = 0;
1435 m_readyState = MediaPlayer::HaveEnoughData;
1437 LOG_MEDIA_MESSAGE("[Buffering] Complete.");
1440 LOG_MEDIA_MESSAGE("[Buffering] Restarting playback.");
1441 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1442 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1443 if (m_audioSessionManager)
1444 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1447 } else if (!m_buffering && (currentTime() < duration())) {
1450 } else if (state == GST_STATE_PLAYING) {
1451 m_readyState = MediaPlayer::HaveEnoughData;
1454 if (m_buffering && !isLiveStream()) {
1455 m_readyState = MediaPlayer::HaveCurrentData;
1456 m_networkState = MediaPlayer::Loading;
1458 LOG_MEDIA_MESSAGE("[Buffering] Pausing stream for buffering.");
1460 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1461 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1462 if (m_audioSessionManager)
1463 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1469 // Is on-disk buffering in progress?
1470 if (m_fillTimer.isActive())
1471 m_networkState = MediaPlayer::Loading;
1473 if (m_changingRate) {
1474 m_player->rateChanged();
1475 m_changingRate = false;
1479 shouldUpdateAfterSeek = true;
1484 case GST_STATE_CHANGE_ASYNC:
1485 LOG_MEDIA_MESSAGE("Async: State: %s, pending: %s",
1486 gst_element_state_get_name(state),
1487 gst_element_state_get_name(pending));
1488 // Change in progress
1490 // On-disk buffering was attempted but the media is live. This
1491 // can't work so disable on-disk buffering and reset the
1493 if (state == GST_STATE_READY && isLiveStream() && m_preload == MediaPlayer::Auto) {
1494 setPreload(MediaPlayer::None);
1495 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1496 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1497 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1498 if (m_audioSessionManager)
1499 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1503 // A live stream was paused, reset the pipeline.
1504 if (state == GST_STATE_PAUSED && pending == GST_STATE_PLAYING && isLiveStream()) {
1505 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1506 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1507 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1508 if (m_audioSessionManager)
1509 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1513 if (!isLiveStream() && !m_buffering)
1517 shouldUpdateAfterSeek = true;
1521 case GST_STATE_CHANGE_FAILURE:
1522 LOG_MEDIA_MESSAGE("Failure: State: %s, pending: %s",
1523 gst_element_state_get_name(state),
1524 gst_element_state_get_name(pending));
1527 case GST_STATE_CHANGE_NO_PREROLL:
1528 LOG_MEDIA_MESSAGE("No preroll: State: %s, pending: %s",
1529 gst_element_state_get_name(state),
1530 gst_element_state_get_name(pending));
1532 if (state == GST_STATE_READY)
1533 m_readyState = MediaPlayer::HaveNothing;
1534 else if (state == GST_STATE_PAUSED) {
1535 m_readyState = MediaPlayer::HaveEnoughData;
1537 // Live pipelines go in PAUSED without prerolling.
1538 m_isStreaming = true;
1539 } else if (state == GST_STATE_PLAYING)
1543 shouldUpdateAfterSeek = true;
1546 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1547 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1548 if (m_audioSessionManager)
1549 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1552 } else if (!m_paused) {
1553 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1554 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1555 if (m_audioSessionManager)
1556 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1560 m_networkState = MediaPlayer::Loading;
1563 LOG_MEDIA_MESSAGE("Else : %d", ret);
1568 m_readyState = MediaPlayer::HaveNothing;
1570 if (shouldUpdateAfterSeek)
1573 if (m_networkState != oldNetworkState) {
1574 LOG_MEDIA_MESSAGE("Network State Changed from %u to %u",
1575 oldNetworkState, m_networkState);
1576 m_player->networkStateChanged();
1578 if (m_readyState != oldReadyState) {
1579 LOG_MEDIA_MESSAGE("Ready State Changed from %u to %u",
1580 oldReadyState, m_readyState);
1581 m_player->readyStateChanged();
1582 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1583 if (state == GST_STATE_PLAYING)
1584 m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
1589 void MediaPlayerPrivateGStreamer::mediaLocationChanged(GstMessage* message)
1591 if (m_mediaLocations)
1592 gst_structure_free(m_mediaLocations);
1594 const GstStructure* structure = gst_message_get_structure(message);
1596 // This structure can contain:
1597 // - both a new-location string and embedded locations structure
1598 // - or only a new-location string.
1599 m_mediaLocations = gst_structure_copy(structure);
1600 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1603 m_mediaLocationCurrentIndex = static_cast<int>(gst_value_list_get_size(locations)) -1;
1609 bool MediaPlayerPrivateGStreamer::loadNextLocation()
1611 if (!m_mediaLocations)
1614 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1615 const gchar* newLocation = 0;
1618 // Fallback on new-location string.
1619 newLocation = gst_structure_get_string(m_mediaLocations, "new-location");
1625 if (m_mediaLocationCurrentIndex < 0) {
1626 m_mediaLocations = 0;
1630 const GValue* location = gst_value_list_get_value(locations,
1631 m_mediaLocationCurrentIndex);
1632 const GstStructure* structure = gst_value_get_structure(location);
1635 m_mediaLocationCurrentIndex--;
1639 newLocation = gst_structure_get_string(structure, "new-location");
1643 // Found a candidate. new-location is not always an absolute url
1644 // though. We need to take the base of the current url and
1645 // append the value of new-location to it.
1647 gchar* currentLocation = 0;
1648 g_object_get(m_playBin.get(), "uri", ¤tLocation, NULL);
1650 KURL currentUrl(KURL(), currentLocation);
1651 g_free(currentLocation);
1655 if (gst_uri_is_valid(newLocation))
1656 newUrl = KURL(KURL(), newLocation);
1658 newUrl = KURL(KURL(), currentUrl.baseAsString() + newLocation);
1660 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(currentUrl);
1661 if (securityOrigin->canRequest(newUrl)) {
1662 LOG_MEDIA_MESSAGE("New media url: %s", newUrl.string().utf8().data());
1664 // Reset player states.
1665 m_networkState = MediaPlayer::Loading;
1666 m_player->networkStateChanged();
1667 m_readyState = MediaPlayer::HaveNothing;
1668 m_player->readyStateChanged();
1670 // Reset pipeline state.
1671 m_resetPipeline = true;
1672 gst_element_set_state(m_playBin.get(), GST_STATE_READY);
1673 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1674 if (m_audioSessionManager)
1675 m_audioSessionManager->setSoundState(ASM_STATE_NONE);
1678 gst_element_get_state(m_playBin.get(), &state, 0, 0);
1679 if (state <= GST_STATE_READY) {
1680 // Set the new uri and start playing.
1681 g_object_set(m_playBin.get(), "uri", newUrl.string().utf8().data(), NULL);
1682 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1683 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1684 if (m_audioSessionManager)
1685 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1691 m_mediaLocationCurrentIndex--;
1696 void MediaPlayerPrivateGStreamer::loadStateChanged()
1701 void MediaPlayerPrivateGStreamer::sizeChanged()
1706 void MediaPlayerPrivateGStreamer::timeChanged()
1709 m_player->timeChanged();
1712 void MediaPlayerPrivateGStreamer::didEnd()
1714 // Synchronize position and duration values to not confuse the
1715 // HTMLMediaElement. In some cases like reverse playback the
1716 // position is not always reported as 0 for instance.
1717 float now = currentTime();
1718 if (now > 0 && now <= duration() && m_mediaDuration != now) {
1719 m_mediaDurationKnown = true;
1720 m_mediaDuration = now;
1721 m_player->durationChanged();
1724 m_isEndReached = true;
1727 if (!m_player->mediaPlayerClient()->mediaPlayerIsLooping()) {
1729 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1730 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1731 if (m_audioSessionManager)
1732 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1734 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1737 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1738 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
1739 if (element->isVideo())
1740 power_unlock_state(POWER_STATE_NORMAL);
1745 void MediaPlayerPrivateGStreamer::cacheDuration()
1747 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1748 float previousDuration = m_mediaDuration;
1750 // Reset cached media duration
1751 m_mediaDuration = 0;
1753 // And re-cache it if possible.
1755 gst_element_get_state(m_playBin.get(), &state, 0, 0);
1756 float newDuration = duration();
1758 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1759 if (state > GST_STATE_READY) {
1760 // Don't set m_mediaDurationKnown yet if the pipeline is not
1761 // paused. This allows duration() query to fail at least once
1762 // before playback starts and duration becomes known.
1763 m_mediaDurationKnown = !isinf(newDuration);
1766 if (!isinf(newDuration))
1767 m_mediaDuration = newDuration;
1769 m_mediaDuration = previousDuration;
1771 if (state <= GST_STATE_READY) {
1772 // Don't set m_mediaDurationKnown yet if the pipeline is not
1773 // paused. This allows duration() query to fail at least once
1774 // before playback starts and duration becomes known.
1775 if (!isinf(newDuration))
1776 m_mediaDuration = newDuration;
1778 m_mediaDurationKnown = !isinf(newDuration);
1779 if (m_mediaDurationKnown)
1780 m_mediaDuration = newDuration;
1783 if (!isinf(newDuration))
1784 m_mediaDuration = newDuration;
1788 void MediaPlayerPrivateGStreamer::durationChanged()
1790 float previousDuration = m_mediaDuration;
1793 // Avoid emiting durationchanged in the case where the previous
1794 // duration was 0 because that case is already handled by the
1795 // HTMLMediaElement.
1796 if (previousDuration && m_mediaDuration != previousDuration)
1797 m_player->durationChanged();
1799 if (m_preload == MediaPlayer::None && m_originalPreloadWasAutoAndWasOverridden) {
1801 if (totalBytes() && !isLiveStream()) {
1802 setPreload(MediaPlayer::Auto);
1803 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1804 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1805 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1806 if (m_audioSessionManager)
1807 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1813 bool MediaPlayerPrivateGStreamer::supportsMuting() const
1818 void MediaPlayerPrivateGStreamer::setMuted(bool muted)
1823 g_object_set(m_playBin.get(), "mute", muted, NULL);
1826 void MediaPlayerPrivateGStreamer::notifyPlayerOfMute()
1828 m_muteTimerHandler = 0;
1830 if (!m_player || !m_playBin)
1834 g_object_get(m_playBin.get(), "mute", &muted, NULL);
1835 m_player->muteChanged(static_cast<bool>(muted));
1838 void MediaPlayerPrivateGStreamer::muteChanged()
1840 if (m_muteTimerHandler)
1841 g_source_remove(m_muteTimerHandler);
1842 m_muteTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateMuteChangeTimeoutCallback), this);
1845 void MediaPlayerPrivateGStreamer::loadingFailed(MediaPlayer::NetworkState error)
1847 #if ENABLE(TIZEN_DLOG_SUPPORT)
1848 TIZEN_LOGE("NetworkState : %d", error);
1851 m_errorOccured = true;
1852 if (m_networkState != error) {
1853 m_networkState = error;
1854 m_player->networkStateChanged();
1856 if (m_readyState != MediaPlayer::HaveNothing) {
1857 m_readyState = MediaPlayer::HaveNothing;
1858 m_player->readyStateChanged();
1862 void MediaPlayerPrivateGStreamer::setSize(const IntSize& size)
1867 void MediaPlayerPrivateGStreamer::setVisible(bool visible)
1871 void MediaPlayerPrivateGStreamer::triggerRepaint(GstBuffer* buffer)
1873 g_return_if_fail(GST_IS_BUFFER(buffer));
1874 gst_buffer_replace(&m_buffer, buffer);
1875 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1876 #if !ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1877 if (m_videoSize.isEmpty())
1878 m_videoSize = naturalSize();
1879 m_videoLayer->paintVideoLayer(m_videoSize);
1883 m_player->repaint();
1886 void MediaPlayerPrivateGStreamer::paint(GraphicsContext* context, const IntRect& rect)
1888 if (context->paintingDisabled())
1891 if (!m_player->visible())
1897 GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
1901 RefPtr<ImageGStreamer> gstImage = ImageGStreamer::createImage(m_buffer, caps.get());
1905 context->drawImage(reinterpret_cast<Image*>(gstImage->image().get()), ColorSpaceSRGB,
1906 rect, gstImage->rect(), CompositeCopy, DoNotRespectImageOrientation, false);
1909 static HashSet<String> mimeTypeCache()
1911 initializeGStreamerAndRegisterWebKitElements();
1913 DEFINE_STATIC_LOCAL(HashSet<String>, cache, ());
1914 static bool typeListInitialized = false;
1916 if (typeListInitialized)
1918 const char* mimeTypes[] = {
1920 "application/vnd.apple.mpegurl",
1921 "application/vnd.rn-realmedia",
1922 "application/x-3gp",
1923 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1924 "application/x-mpegurl",
1925 "application/x-mpegURL",
1927 "application/x-pn-realaudio",
1947 "audio/x-amr-nb-sh",
1948 "audio/x-amr-wb-sh",
1979 "audio/x-vorbis+ogg",
1983 "audio/x-wavpack-correction",
2010 for (unsigned i = 0; i < (sizeof(mimeTypes) / sizeof(*mimeTypes)); ++i)
2011 cache.add(String(mimeTypes[i]));
2013 typeListInitialized = true;
2017 void MediaPlayerPrivateGStreamer::getSupportedTypes(HashSet<String>& types)
2019 types = mimeTypeCache();
2022 MediaPlayer::SupportsType MediaPlayerPrivateGStreamer::supportsType(const String& type, const String& codecs, const KURL&)
2024 if (type.isNull() || type.isEmpty())
2025 return MediaPlayer::IsNotSupported;
2027 // spec says we should not return "probably" if the codecs string is empty
2028 if (mimeTypeCache().contains(type))
2029 return codecs.isEmpty() ? MediaPlayer::MayBeSupported : MediaPlayer::IsSupported;
2030 return MediaPlayer::IsNotSupported;
2033 bool MediaPlayerPrivateGStreamer::hasSingleSecurityOrigin() const
2038 bool MediaPlayerPrivateGStreamer::supportsFullscreen() const
2040 #if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
2041 // See <rdar://problem/7389945>
2048 PlatformMedia MediaPlayerPrivateGStreamer::platformMedia() const
2051 #ifndef GST_API_VERSION_1
2052 p.type = PlatformMedia::GStreamerGWorldType;
2053 p.media.gstreamerGWorld = m_gstGWorld.get();
2058 MediaPlayer::MovieLoadType MediaPlayerPrivateGStreamer::movieLoadType() const
2060 if (m_readyState == MediaPlayer::HaveNothing)
2061 return MediaPlayer::Unknown;
2064 return MediaPlayer::LiveStream;
2066 return MediaPlayer::Download;
2069 void MediaPlayerPrivateGStreamer::setDownloadBuffering()
2076 g_object_get(m_playBin.get(), "flags", &flags, NULL);
2077 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2078 flags = (GstPlayFlags)(flags | GST_PLAY_FLAG_NATIVE_VIDEO);
2080 if (m_preload == MediaPlayer::Auto) {
2081 LOG_MEDIA_MESSAGE("Enabling on-disk buffering");
2082 g_object_set(m_playBin.get(), "flags", flags | GST_PLAY_FLAG_DOWNLOAD, NULL);
2084 LOG_MEDIA_MESSAGE("Disabling on-disk buffering");
2085 g_object_set(m_playBin.get(), "flags", flags & ~GST_PLAY_FLAG_DOWNLOAD, NULL);
2089 void MediaPlayerPrivateGStreamer::setPreload(MediaPlayer::Preload preload)
2091 m_originalPreloadWasAutoAndWasOverridden = m_preload != preload && m_preload == MediaPlayer::Auto;
2093 m_preload = preload;
2095 setDownloadBuffering();
2097 if (m_delayingLoad && m_preload != MediaPlayer::None) {
2098 m_delayingLoad = false;
2103 void MediaPlayerPrivateGStreamer::createAudioSink()
2105 // Construct audio sink if pitch preserving is enabled.
2106 if (!m_preservesPitch)
2112 GstElement* scale = gst_element_factory_make("scaletempo", 0);
2114 GST_WARNING("Failed to create scaletempo");
2118 GstElement* convert = gst_element_factory_make("audioconvert", 0);
2119 GstElement* resample = gst_element_factory_make("audioresample", 0);
2120 GstElement* sink = gst_element_factory_make("autoaudiosink", 0);
2122 GstElement* audioSink = gst_bin_new("audio-sink");
2123 gst_bin_add_many(GST_BIN(audioSink), scale, convert, resample, sink, NULL);
2125 if (!gst_element_link_many(scale, convert, resample, sink, NULL)) {
2126 GST_WARNING("Failed to link audio sink elements");
2127 gst_object_unref(audioSink);
2131 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(scale, "sink"));
2132 gst_element_add_pad(audioSink, gst_ghost_pad_new("sink", pad.get()));
2134 g_object_set(m_playBin.get(), "audio-sink", audioSink, NULL);
2137 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2138 GstElement* MediaPlayerPrivateGStreamer::createVideoSink()
2140 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2141 m_webkitVideoSink = m_videoLayer->createVideoSink();
2142 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2144 // Primary video should be OFF and Secondary video should be FULL SCREEN mode
2145 g_object_set(m_webkitVideoSink, "display-mode", 2, NULL);
2146 #else // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2147 #ifndef GST_API_VERSION_1
2148 m_webkitVideoSink = webkitVideoSinkNew(m_gstGWorld.get());
2150 m_webkitVideoSink = webkitVideoSinkNew();
2152 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2153 g_signal_connect(m_webkitVideoSink, "repaint-requested", G_CALLBACK(mediaPlayerPrivateRepaintCallback), this);
2154 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2156 #ifndef GST_API_VERSION_1
2157 m_videoSinkBin = gst_bin_new("video-sink");
2158 GstElement* videoTee = gst_element_factory_make("tee", "videoTee");
2159 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2160 GstElement* queue = gst_element_factory_make("queue", 0);
2163 gst_object_ref_sink(m_videoSinkBin);
2165 // Build a new video sink consisting of a bin containing a tee
2166 // (meant to distribute data to multiple video sinks) and our
2167 // internal video sink. For fullscreen we create an autovideosink
2168 // and initially block the data flow towards it and configure it
2169 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2170 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, queue, NULL);
2172 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, NULL);
2175 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2176 // Link a new src pad from tee to queue1.
2177 gst_element_link_pads_full(videoTee, 0, queue, "sink", GST_PAD_LINK_CHECK_NOTHING);
2181 GstElement* actualVideoSink = 0;
2182 m_fpsSink = gst_element_factory_make("fpsdisplaysink", "sink");
2184 // The verbose property has been added in -bad 0.10.22. Making
2185 // this whole code depend on it because we don't want
2186 // fpsdiplaysink to spit data on stdout.
2187 GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(m_fpsSink)->elementfactory);
2188 if (gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 22)) {
2189 g_object_set(m_fpsSink, "silent", TRUE , NULL);
2191 // Turn off text overlay unless logging is enabled.
2193 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2195 WTFLogChannel* channel = getChannelFromName("Media");
2196 if (channel->state != WTFLogChannelOn)
2197 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2198 #endif // LOG_DISABLED
2200 if (g_object_class_find_property(G_OBJECT_GET_CLASS(m_fpsSink), "video-sink")) {
2201 g_object_set(m_fpsSink, "video-sink", m_webkitVideoSink, NULL);
2202 #ifndef GST_API_VERSION_1
2203 gst_bin_add(GST_BIN(m_videoSinkBin), m_fpsSink);
2205 actualVideoSink = m_fpsSink;
2213 #ifndef GST_API_VERSION_1
2214 gst_bin_add(GST_BIN(m_videoSinkBin), m_webkitVideoSink);
2216 actualVideoSink = m_webkitVideoSink;
2219 ASSERT(actualVideoSink);
2221 #ifndef GST_API_VERSION_1
2222 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2223 // Link a new src pad from tee to queue1.
2224 GRefPtr<GstPad> srcPad = adoptGRef(gst_element_get_request_pad(videoTee, "src%d"));
2225 GRefPtr<GstPad> sinkPad = adoptGRef(gst_element_get_static_pad(actualVideoSink, "sink"));
2226 gst_pad_link(srcPad.get(), sinkPad.get());
2228 // Faster elements linking.
2229 gst_element_link_pads_full(queue, "src", actualVideoSink, "sink", GST_PAD_LINK_CHECK_NOTHING);
2231 // Add a ghostpad to the bin so it can proxy to tee.
2232 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(videoTee, "sink"));
2233 gst_element_add_pad(m_videoSinkBin, gst_ghost_pad_new("sink", pad.get()));
2235 // Set the bin as video sink of playbin.
2236 return m_videoSinkBin;
2238 return actualVideoSink;
2243 void MediaPlayerPrivateGStreamer::createGSTPlayBin()
2247 // gst_element_factory_make() returns a floating reference so
2248 // we should not adopt.
2249 m_playBin = gst_element_factory_make(gPlaybinName, "play");
2251 #ifndef GST_API_VERSION_1
2252 m_gstGWorld = GStreamerGWorld::createGWorld(m_playBin.get());
2255 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
2256 gst_bus_add_signal_watch(bus.get());
2257 g_signal_connect(bus.get(), "message", G_CALLBACK(mediaPlayerPrivateMessageCallback), this);
2258 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2259 gst_bus_set_sync_handler(bus.get(), GstBusSyncHandler(mediaPlayerPrivateSyncHandler), this);
2261 gst_object_unref(bus.get());
2263 g_object_set(m_playBin.get(), "mute", m_player->muted(), NULL);
2265 g_signal_connect(m_playBin.get(), "notify::volume", G_CALLBACK(mediaPlayerPrivateVolumeChangedCallback), this);
2266 g_signal_connect(m_playBin.get(), "notify::source", G_CALLBACK(mediaPlayerPrivateSourceChangedCallback), this);
2267 g_signal_connect(m_playBin.get(), "notify::mute", G_CALLBACK(mediaPlayerPrivateMuteChangedCallback), this);
2268 g_signal_connect(m_playBin.get(), "video-changed", G_CALLBACK(mediaPlayerPrivateVideoChangedCallback), this);
2269 g_signal_connect(m_playBin.get(), "audio-changed", G_CALLBACK(mediaPlayerPrivateAudioChangedCallback), this);
2270 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2271 g_signal_connect(m_playBin.get(), "source-setup", G_CALLBACK(mediaPlayerPrivateSourceSetupCallback), this);
2274 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2275 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
2276 if (element->isVideo()) {
2277 GstElement* videoElement = createVideoSink();
2278 g_object_set(m_playBin.get(), "video-sink", videoElement, NULL);
2280 GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2282 g_signal_connect(videoSinkPad.get(), "notify::caps", G_CALLBACK(mediaPlayerPrivateVideoSinkCapsChangedCallback), this);
2284 GstElement* fakeSink = gst_element_factory_make("fakesink", 0);
2285 g_object_set(fakeSink, "sync", true, NULL);
2286 g_object_set(m_playBin.get(), "video-sink", fakeSink, NULL);
2289 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2290 GstElement* realSink = gst_element_factory_make("avsysaudiosink", 0);
2291 g_object_set(realSink, "close-handle-on-prepare", 1, NULL);
2292 g_object_set(m_playBin.get(), "audio-sink", realSink, NULL);
2294 if (m_audioSessionManager)
2295 m_audioSessionManager->registerAudioSessionManager(MM_SESSION_TYPE_SHARE, mediaPlayerPrivateAudioSessionNotifyCallback, player());
2301 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2302 bool MediaPlayerPrivateGStreamer::supportsAcceleratedRendering() const
2304 bool isEmbedVideo = false;
2305 if (m_player->mediaPlayerClient()) {
2306 Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
2307 if (document && document->settings()) {
2308 isEmbedVideo = document->settings()->acceleratedCompositingForVideoEnabled()
2309 && document->settings()->acceleratedCompositingEnabled();
2310 LOG_MEDIA_MESSAGE("isEmbedVideo: %d", isEmbedVideo);
2314 return isEmbedVideo;
2317 PlatformLayer* MediaPlayerPrivateGStreamer::platformLayer() const
2319 return m_videoLayer->platformLayer();
2322 #if ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2323 void MediaPlayerPrivateGStreamer::paintCurrentFrameInContext(GraphicsContext* context, const IntRect& rect)
2325 m_videoLayer->paintCurrentFrameInContext(context, rect);
2328 #if USE(ACCELERATED_VIDEO_VAAPI)
2329 // Other device doesn't prefer such optimization, so enclose it in USE(ACCELERATED_VIDEO_VAAPI) macro
2330 IntSize MediaPlayerPrivateGStreamer::scaleHDVideoToDisplaySize(int videoWidth, int videoHeight, int displayWidth, int displayHeight) const
2332 int fitWidth, fitHeight;
2334 #if ENABLE(TIZEN_DLOG_SUPPORT)
2335 TIZEN_LOGI("videoWidth: %d, videoHeight: %d, displayWidth: %d, displayHeight: %d ", videoWidth, videoHeight, displayWidth, displayHeight);
2337 fitWidth = videoWidth;
2338 fitHeight = videoHeight;
2339 if (displayWidth > 0 && displayHeight > 0) {
2340 // In case video is rotated, we always use a 'better'
2341 // orientation (landscape or portrait) to calculate fitWidth/fitHeight.
2342 // It means we use a bigger size which doesn't lose quality
2343 // in either landscape or portrait orientation
2344 if ((videoWidth > videoHeight && displayWidth < displayHeight)
2345 || (videoWidth < videoHeight && displayWidth > displayHeight)) {
2348 displayWidth = displayHeight;
2349 displayHeight = tmp;
2352 if (videoWidth > displayWidth || videoHeight > displayHeight) {
2353 if (videoWidth * displayHeight > videoHeight * displayWidth) {
2354 fitWidth = displayWidth;
2355 fitHeight = videoHeight * displayWidth / videoWidth;
2356 ASSERT(fitHeight <= displayHeight);
2358 fitWidth = videoWidth * displayHeight / videoHeight;
2359 fitHeight = displayHeight;
2360 ASSERT(fitWidth <= displayWidth);
2365 return IntSize(fitWidth, fitHeight);
2368 void MediaPlayerPrivateGStreamer::xWindowIdPrepared(GstMessage* message)
2370 // It is called in streaming thread.
2371 // It should be used only to set window handle to video sink.
2373 int videoWidth, videoHeight;
2374 gst_structure_get_int(message->structure, "video-width", &videoWidth);
2375 gst_structure_get_int(message->structure, "video-height", &videoHeight);
2377 #if ENABLE(TIZEN_DLOG_SUPPORT)
2378 TIZEN_LOGI("videoWidth: %d, videoHeight: %d", videoWidth, videoHeight);
2381 #if USE(ACCELERATED_VIDEO_VAAPI)
2382 int displayWidth, displayHeight;
2383 gst_structure_get_int(message->structure, "display-width", &displayWidth);
2384 gst_structure_get_int(message->structure, "display-height", &displayHeight);
2386 m_displaySize = IntSize(displayWidth, displayHeight);
2387 m_videoSize = scaleHDVideoToDisplaySize(videoWidth, videoHeight, displayWidth, displayHeight);
2389 m_videoSize = IntSize(videoWidth, videoHeight);
2391 m_videoLayer->setOverlay(m_videoSize);
2394 #endif // ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2395 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2397 #if ENABLE(TIZEN_WEBKIT2_PROXY)
2398 void MediaPlayerPrivateGStreamer::setProxy(GstElement* source)
2400 SoupSession* session = WebCore::ResourceHandle::defaultSession();
2404 SoupURI* proxyUri = 0;
2405 g_object_get(session, SOUP_SESSION_PROXY_URI, &proxyUri, NULL);
2409 char* proxy = soup_uri_to_string(proxyUri, false);
2410 g_object_set(source, "proxy", proxy, NULL);
2412 soup_uri_free(proxyUri);
2417 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2418 void MediaPlayerPrivateGStreamer::suspend()
2420 m_suspendTime = currentTime();
2421 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
2422 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2423 if (m_audioSessionManager)
2424 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
2428 void MediaPlayerPrivateGStreamer::resume()
2430 if (isLocalMediaStream()) {
2431 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
2432 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2433 if (m_audioSessionManager)
2434 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
2437 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
2438 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2439 if (m_audioSessionManager)
2440 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
2445 bool MediaPlayerPrivateGStreamer::isLocalMediaStream()
2447 if (m_url.string().contains("camera://"))
2452 #endif // ENABLE(TIZEN_GSTREAMER_VIDEO)
2456 #endif // USE(GSTREAMER)