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:
254 return ASM_CB_RES_PAUSE;
255 case ASM_EVENT_SOURCE_EARJACK_UNPLUG:
256 if (!player->url().string().contains("camera://")) {
258 return ASM_CB_RES_PAUSE;
261 return ASM_CB_RES_NONE;
265 static ASM_cb_result_t MediaPlayerAudioSessionEventSourcePlay(ASM_event_sources_t eventSource, void* callbackData)
267 MediaPlayer* player = static_cast<MediaPlayer*>(callbackData);
269 return ASM_CB_RES_IGNORE;
271 switch (eventSource) {
272 case ASM_EVENT_SOURCE_ALARM_END:
273 if (!player->hasVideo()) {
275 return ASM_CB_RES_PLAYING;
276 } else if (player->url().string().contains("camera://")) {
278 return ASM_CB_RES_PLAYING;
280 return ASM_CB_RES_NONE;
282 return ASM_CB_RES_NONE;
286 static ASM_cb_result_t mediaPlayerPrivateAudioSessionNotifyCallback(int, ASM_event_sources_t eventSource, ASM_sound_commands_t command, unsigned int, void* callbackData)
288 if (command == ASM_COMMAND_STOP || command == ASM_COMMAND_PAUSE)
289 return MediaPlayerAudioSessionEventSourcePause(eventSource, callbackData);
290 if (command == ASM_COMMAND_PLAY || command == ASM_COMMAND_RESUME)
291 return MediaPlayerAudioSessionEventSourcePlay(eventSource, callbackData);
293 return ASM_CB_RES_NONE;
297 PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivateGStreamer::create(MediaPlayer* player)
299 return adoptPtr(new MediaPlayerPrivateGStreamer(player));
302 void MediaPlayerPrivateGStreamer::registerMediaEngine(MediaEngineRegistrar registrar)
305 registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
308 bool initializeGStreamerAndRegisterWebKitElements()
310 if (!initializeGStreamer())
313 GRefPtr<GstElementFactory> srcFactory = gst_element_factory_find("webkitwebsrc");
315 #if ENABLE(TIZEN_MEDIA_STREAM)
316 return gst_element_register(0, "webkitcamerasrc", GST_RANK_PRIMARY + 200, WEBKIT_TYPE_CAMERA_SRC);
318 GST_DEBUG_CATEGORY_INIT(webkit_media_player_debug, "webkitmediaplayer", 0, "WebKit media player");
319 return gst_element_register(0, "webkitwebsrc", GST_RANK_PRIMARY + 100, WEBKIT_TYPE_WEB_SRC);
320 #endif // ENABLE(TIZEN_MEDIA_STREAM)
325 bool MediaPlayerPrivateGStreamer::isAvailable()
327 if (!initializeGStreamerAndRegisterWebKitElements())
330 GRefPtr<GstElementFactory> factory = gst_element_factory_find(gPlaybinName);
334 MediaPlayerPrivateGStreamer::MediaPlayerPrivateGStreamer(MediaPlayer* player)
336 , m_webkitVideoSink(0)
337 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
343 , m_changingRate(false)
344 , m_endTime(numeric_limits<float>::infinity())
345 , m_isEndReached(false)
346 , m_networkState(MediaPlayer::Empty)
347 , m_readyState(MediaPlayer::HaveNothing)
348 , m_isStreaming(false)
351 , m_mediaLocations(0)
352 , m_mediaLocationCurrentIndex(0)
353 , m_resetPipeline(false)
358 , m_errorOccured(false)
360 , m_startedBuffering(false)
361 , m_fillTimer(this, &MediaPlayerPrivateGStreamer::fillTimerFired)
363 , m_bufferingPercentage(0)
364 , m_preload(MediaPlayer::Auto)
365 , m_delayingLoad(false)
366 , m_mediaDurationKnown(true)
367 , m_maxTimeLoadedAtLastDidLoadingProgress(0)
368 , m_volumeTimerHandler(0)
369 , m_muteTimerHandler(0)
372 , m_audioTimerHandler(0)
373 , m_videoTimerHandler(0)
374 , m_webkitAudioSink(0)
376 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
377 , m_videoLayer(VideoLayerTizen::create(static_cast<HTMLMediaElement*>(player->mediaPlayerClient())))
378 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
379 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
380 , m_audioSessionManager(AudioSessionManagerGStreamerTizen::createAudioSessionManager())
382 , m_originalPreloadWasAutoAndWasOverridden(false)
383 , m_preservesPitch(false)
384 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
390 MediaPlayerPrivateGStreamer::~MediaPlayerPrivateGStreamer()
392 if (m_fillTimer.isActive())
396 gst_buffer_unref(m_buffer);
399 if (m_mediaLocations) {
400 gst_structure_free(m_mediaLocations);
401 m_mediaLocations = 0;
404 #ifndef GST_API_VERSION_1
405 if (m_videoSinkBin) {
406 gst_object_unref(m_videoSinkBin);
412 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
414 g_signal_handlers_disconnect_by_func(bus.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateMessageCallback), this);
415 gst_bus_remove_signal_watch(bus.get());
417 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
423 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
424 if (m_audioSessionManager)
425 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
428 if (m_muteTimerHandler)
429 g_source_remove(m_muteTimerHandler);
431 if (m_volumeTimerHandler)
432 g_source_remove(m_volumeTimerHandler);
434 if (m_videoTimerHandler)
435 g_source_remove(m_videoTimerHandler);
437 if (m_audioTimerHandler)
438 g_source_remove(m_audioTimerHandler);
441 void MediaPlayerPrivateGStreamer::load(const String& url)
443 if (!initializeGStreamerAndRegisterWebKitElements())
446 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
448 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
449 KURL kurl(KURL(), url);
450 String cleanUrl(url);
452 // Clean out everything after file:// url path.
453 if (kurl.isLocalFile())
454 cleanUrl = cleanUrl.substring(0, kurl.pathEnd());
458 setDownloadBuffering();
463 m_url = KURL(KURL(), cleanUrl);
464 g_object_set(m_playBin.get(), "uri", cleanUrl.utf8().data(), NULL);
466 LOG_MEDIA_MESSAGE("Load %s", cleanUrl.utf8().data());
468 if (m_preload == MediaPlayer::None) {
469 LOG_MEDIA_MESSAGE("Delaying load.");
470 m_delayingLoad = true;
473 // Reset network and ready states. Those will be set properly once
474 // the pipeline pre-rolled.
475 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
477 m_networkState = MediaPlayer::Loading;
479 m_networkState = MediaPlayer::Idle;
481 m_networkState = MediaPlayer::Loading;
483 m_player->networkStateChanged();
484 m_readyState = MediaPlayer::HaveNothing;
485 m_player->readyStateChanged();
486 m_volumeAndMuteInitialized = false;
488 // GStreamer needs to have the pipeline set to a paused state to
489 // start providing anything useful.
490 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
493 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
495 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
496 if (m_audioSessionManager && !m_delayingLoad)
497 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
504 void MediaPlayerPrivateGStreamer::commitLoad()
506 ASSERT(!m_delayingLoad);
507 LOG_MEDIA_MESSAGE("Committing load.");
511 float MediaPlayerPrivateGStreamer::playbackPosition() const
513 if (m_isEndReached) {
514 // Position queries on a null pipeline return 0. If we're at
515 // the end of the stream the pipeline is null but we want to
516 // report either the seek time or the duration because this is
517 // what the Media element spec expects us to do.
521 return m_mediaDuration;
526 GstQuery* query = gst_query_new_position(GST_FORMAT_TIME);
527 if (!gst_element_query(m_playBin.get(), query)) {
528 LOG_MEDIA_MESSAGE("Position query failed...");
529 gst_query_unref(query);
534 gst_query_parse_position(query, 0, &position);
536 // Position is available only if the pipeline is not in GST_STATE_NULL or
537 // GST_STATE_READY state.
538 if (position != static_cast<gint64>(GST_CLOCK_TIME_NONE))
539 ret = static_cast<double>(position) / GST_SECOND;
541 LOG_MEDIA_MESSAGE("Position %" GST_TIME_FORMAT, GST_TIME_ARGS(position));
543 gst_query_unref(query);
548 bool MediaPlayerPrivateGStreamer::changePipelineState(GstState newState)
550 ASSERT(newState == GST_STATE_PLAYING || newState == GST_STATE_PAUSED);
552 GstState currentState;
555 gst_element_get_state(m_playBin.get(), ¤tState, &pending, 0);
556 LOG_MEDIA_MESSAGE("Current state: %s, pending: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
557 #if ENABLE(TIZEN_DLOG_SUPPORT)
558 TIZEN_LOGI("Current state: %s, New state: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(newState));
560 if (currentState == newState || pending == newState)
563 GstStateChangeReturn setStateResult = gst_element_set_state(m_playBin.get(), newState);
564 GstState pausedOrPlaying = newState == GST_STATE_PLAYING ? GST_STATE_PAUSED : GST_STATE_PLAYING;
565 if (currentState != pausedOrPlaying && setStateResult == GST_STATE_CHANGE_FAILURE) {
566 loadingFailed(MediaPlayer::Empty);
572 void MediaPlayerPrivateGStreamer::prepareToPlay()
574 m_isEndReached = false;
577 if (m_delayingLoad) {
578 m_delayingLoad = false;
583 void MediaPlayerPrivateGStreamer::play()
585 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
586 if (m_audioSessionManager && !m_audioSessionManager->setSoundState(ASM_STATE_PLAYING))
589 if (changePipelineState(GST_STATE_PLAYING)) {
590 m_isEndReached = false;
591 LOG_MEDIA_MESSAGE("Play");
595 void MediaPlayerPrivateGStreamer::pause()
597 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
598 if (m_audioSessionManager && !m_audioSessionManager->setSoundState(ASM_STATE_PAUSE))
604 if (changePipelineState(GST_STATE_PAUSED))
605 LOG_MEDIA_MESSAGE("Pause");
608 float MediaPlayerPrivateGStreamer::duration() const
616 // Media duration query failed already, don't attempt new useless queries.
617 if (!m_mediaDurationKnown)
618 return numeric_limits<float>::infinity();
621 return m_mediaDuration;
623 GstFormat timeFormat = GST_FORMAT_TIME;
624 gint64 timeLength = 0;
626 #ifdef GST_API_VERSION_1
627 bool failure = !gst_element_query_duration(m_playBin.get(), timeFormat, &timeLength) || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
629 bool failure = !gst_element_query_duration(m_playBin.get(), &timeFormat, &timeLength) || timeFormat != GST_FORMAT_TIME || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
632 LOG_MEDIA_MESSAGE("Time duration query failed for %s", m_url.string().utf8().data());
633 return numeric_limits<float>::infinity();
636 LOG_MEDIA_MESSAGE("Duration: %" GST_TIME_FORMAT, GST_TIME_ARGS(timeLength));
638 return static_cast<double>(timeLength) / GST_SECOND;
639 // FIXME: handle 3.14.9.5 properly
642 float MediaPlayerPrivateGStreamer::currentTime() const
654 // https://bugzilla.gnome.org/show_bug.cgi?id=639941 In GStreamer
655 // 0.10.35 basesink reports wrong duration in case of EOS and
656 // negative playback rate. There's no upstream accepted patch for
657 // this bug yet, hence this temporary workaround.
658 if (m_isEndReached && m_playbackRate < 0)
661 return playbackPosition();
665 void MediaPlayerPrivateGStreamer::seek(float time)
673 LOG_MEDIA_MESSAGE("Seek attempt to %f secs", time);
674 #if ENABLE(TIZEN_DLOG_SUPPORT)
675 TIZEN_LOGI("Seek attempt to %f secs", time);
678 // Avoid useless seeking.
679 if (time == currentTime())
682 // Extract the integer part of the time (seconds) and the
683 // fractional part (microseconds). Attempt to round the
684 // microseconds so no floating point precision is lost and we can
685 // perform an accurate seek.
687 float microSeconds = modf(time, &seconds) * 1000000;
689 timeValue.tv_sec = static_cast<glong>(seconds);
690 timeValue.tv_usec = static_cast<glong>(roundf(microSeconds / 10000) * 10000);
692 GstClockTime clockTime = GST_TIMEVAL_TO_TIME(timeValue);
693 LOG_MEDIA_MESSAGE("Seek: %" GST_TIME_FORMAT, GST_TIME_ARGS(clockTime));
695 if (!gst_element_seek(m_playBin.get(), m_player->rate(),
697 (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE),
698 GST_SEEK_TYPE_SET, clockTime,
699 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) {
700 LOG_MEDIA_MESSAGE("Seek to %f failed", time);
701 #if ENABLE(TIZEN_DLOG_SUPPORT)
702 TIZEN_LOGE("Seek to %f failed", time);
710 bool MediaPlayerPrivateGStreamer::paused() const
712 if (m_isEndReached) {
713 LOG_MEDIA_MESSAGE("Ignoring pause at EOS");
718 gst_element_get_state(m_playBin.get(), &state, 0, 0);
719 return state == GST_STATE_PAUSED;
722 bool MediaPlayerPrivateGStreamer::seeking() const
727 // Returns the size of the video
728 IntSize MediaPlayerPrivateGStreamer::naturalSize() const
733 if (!m_videoSize.isEmpty())
736 GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
741 // TODO: handle possible clean aperture data. See
742 // https://bugzilla.gnome.org/show_bug.cgi?id=596571
743 // TODO: handle possible transformation matrix. See
744 // https://bugzilla.gnome.org/show_bug.cgi?id=596326
746 // Get the video PAR and original size, if this fails the
747 // video-sink has likely not yet negotiated its caps.
748 int pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride;
749 IntSize originalSize;
750 GstVideoFormat format;
751 if (!getVideoSizeAndFormatFromCaps(caps.get(), originalSize, format, pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride))
754 LOG_MEDIA_MESSAGE("Original video size: %dx%d", originalSize.width(), originalSize.height());
755 LOG_MEDIA_MESSAGE("Pixel aspect ratio: %d/%d", pixelAspectRatioNumerator, pixelAspectRatioDenominator);
757 // Calculate DAR based on PAR and video size.
758 int displayWidth = originalSize.width() * pixelAspectRatioNumerator;
759 int displayHeight = originalSize.height() * pixelAspectRatioDenominator;
761 // Divide display width and height by their GCD to avoid possible overflows.
762 int displayAspectRatioGCD = greatestCommonDivisor(displayWidth, displayHeight);
763 displayWidth /= displayAspectRatioGCD;
764 displayHeight /= displayAspectRatioGCD;
766 // Apply DAR to original video size. This is the same behavior as in xvimagesink's setcaps function.
767 guint64 width = 0, height = 0;
768 if (!(originalSize.height() % displayHeight)) {
769 LOG_MEDIA_MESSAGE("Keeping video original height");
770 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
771 height = static_cast<guint64>(originalSize.height());
772 } else if (!(originalSize.width() % displayWidth)) {
773 LOG_MEDIA_MESSAGE("Keeping video original width");
774 height = gst_util_uint64_scale_int(originalSize.width(), displayHeight, displayWidth);
775 width = static_cast<guint64>(originalSize.width());
777 LOG_MEDIA_MESSAGE("Approximating while keeping original video height");
778 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
779 height = static_cast<guint64>(originalSize.height());
782 LOG_MEDIA_MESSAGE("Natural size: %" G_GUINT64_FORMAT "x%" G_GUINT64_FORMAT, width, height);
783 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE) && USE(ACCELERATED_VIDEO_VAAPI)
784 if (!m_displaySize.isEmpty())
785 m_videoSize = scaleHDVideoToDisplaySize(static_cast<int>(width), static_cast<int>(height), m_displaySize.width(), m_displaySize.height());
788 m_videoSize = IntSize(static_cast<int>(width), static_cast<int>(height));
792 void MediaPlayerPrivateGStreamer::videoChanged()
794 if (m_videoTimerHandler)
795 g_source_remove(m_videoTimerHandler);
796 m_videoTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVideoChangeTimeoutCallback), this);
799 void MediaPlayerPrivateGStreamer::notifyPlayerOfVideo()
801 m_videoTimerHandler = 0;
803 gint videoTracks = 0;
805 g_object_get(m_playBin.get(), "n-video", &videoTracks, NULL);
807 m_hasVideo = videoTracks > 0;
809 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
811 if (gst_video_get_size(m_videoSinkPad.get(), &width, &height)) {
812 IntSize size(width, height);
813 if (m_videoSize != size) {
814 m_videoSize = IntSize();
815 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
816 m_videoLayer->setOverlay(naturalSize());
821 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
822 #else // ENABLE(TIZEN_GSTREAMER_VIDEO)
823 m_videoSize = IntSize();
825 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
829 void MediaPlayerPrivateGStreamer::audioChanged()
831 if (m_audioTimerHandler)
832 g_source_remove(m_audioTimerHandler);
833 m_audioTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateAudioChangeTimeoutCallback), this);
836 void MediaPlayerPrivateGStreamer::notifyPlayerOfAudio()
838 m_audioTimerHandler = 0;
840 gint audioTracks = 0;
842 g_object_get(m_playBin.get(), "n-audio", &audioTracks, NULL);
843 m_hasAudio = audioTracks > 0;
844 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
847 void MediaPlayerPrivateGStreamer::setVolume(float volume)
852 gst_stream_volume_set_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC,
853 static_cast<double>(volume));
856 void MediaPlayerPrivateGStreamer::notifyPlayerOfVolumeChange()
858 m_volumeTimerHandler = 0;
860 if (!m_player || !m_playBin)
863 volume = gst_stream_volume_get_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC);
864 // get_volume() can return values superior to 1.0 if the user
865 // applies software user gain via third party application (GNOME
866 // volume control for instance).
867 volume = CLAMP(volume, 0.0, 1.0);
868 m_player->volumeChanged(static_cast<float>(volume));
871 void MediaPlayerPrivateGStreamer::volumeChanged()
873 if (m_volumeTimerHandler)
874 g_source_remove(m_volumeTimerHandler);
875 m_volumeTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVolumeChangeTimeoutCallback), this);
878 void MediaPlayerPrivateGStreamer::setRate(float rate)
880 // Avoid useless playback rate update.
881 if (m_playbackRate == rate)
887 gst_element_get_state(m_playBin.get(), &state, &pending, 0);
888 if ((state != GST_STATE_PLAYING && state != GST_STATE_PAUSED)
889 || (pending == GST_STATE_PAUSED))
895 m_playbackRate = rate;
896 m_changingRate = true;
899 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
900 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
901 if (m_audioSessionManager)
902 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
907 float currentPosition = static_cast<float>(playbackPosition() * GST_SECOND);
908 GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH);
912 LOG_MEDIA_MESSAGE("Set Rate to %f", rate);
914 // Mute the sound if the playback rate is too extreme and
915 // audio pitch is not adjusted.
916 mute = (!m_preservesPitch && (rate < 0.8 || rate > 2));
917 start = currentPosition;
918 end = GST_CLOCK_TIME_NONE;
923 // If we are at beginning of media, start from the end to
924 // avoid immediate EOS.
925 if (currentPosition <= 0)
926 end = static_cast<gint64>(duration() * GST_SECOND);
928 end = currentPosition;
931 LOG_MEDIA_MESSAGE("Need to mute audio: %d", (int) mute);
933 if (!gst_element_seek(m_playBin.get(), rate, GST_FORMAT_TIME, flags,
934 GST_SEEK_TYPE_SET, start,
935 GST_SEEK_TYPE_SET, end))
936 LOG_MEDIA_MESSAGE("Set rate to %f failed", rate);
938 g_object_set(m_playBin.get(), "mute", mute, NULL);
941 void MediaPlayerPrivateGStreamer::setPreservesPitch(bool preservesPitch)
943 m_preservesPitch = preservesPitch;
946 MediaPlayer::NetworkState MediaPlayerPrivateGStreamer::networkState() const
948 return m_networkState;
951 MediaPlayer::ReadyState MediaPlayerPrivateGStreamer::readyState() const
956 PassRefPtr<TimeRanges> MediaPlayerPrivateGStreamer::buffered() const
958 RefPtr<TimeRanges> timeRanges = TimeRanges::create();
959 if (m_errorOccured || isLiveStream())
960 return timeRanges.release();
962 #if GST_CHECK_VERSION(0, 10, 31)
963 float mediaDuration(duration());
964 if (!mediaDuration || isinf(mediaDuration))
965 return timeRanges.release();
967 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
969 if (!gst_element_query(m_playBin.get(), query)) {
970 gst_query_unref(query);
971 return timeRanges.release();
974 gint64 rangeStart = 0, rangeStop = 0;
975 for (guint index = 0; index < gst_query_get_n_buffering_ranges(query); index++) {
976 if (gst_query_parse_nth_buffering_range(query, index, &rangeStart, &rangeStop))
977 timeRanges->add(static_cast<float>((rangeStart * mediaDuration) / 100),
978 static_cast<float>((rangeStop * mediaDuration) / 100));
981 // Fallback to the more general maxTimeLoaded() if no range has
983 if (!timeRanges->length())
984 if (float loaded = maxTimeLoaded())
985 timeRanges->add(0, loaded);
987 gst_query_unref(query);
989 float loaded = maxTimeLoaded();
990 if (!m_errorOccured && !isLiveStream() && loaded > 0)
991 timeRanges->add(0, loaded);
993 return timeRanges.release();
996 gboolean MediaPlayerPrivateGStreamer::handleMessage(GstMessage* message)
999 GOwnPtr<gchar> debug;
1000 MediaPlayer::NetworkState error;
1001 bool issueError = true;
1002 bool attemptNextLocation = false;
1003 const GstStructure* structure = gst_message_get_structure(message);
1006 const gchar* messageTypeName = gst_structure_get_name(structure);
1008 // Redirect messages are sent from elements, like qtdemux, to
1009 // notify of the new location(s) of the media.
1010 if (!g_strcmp0(messageTypeName, "redirect")) {
1011 mediaLocationChanged(message);
1016 LOG_MEDIA_MESSAGE("Message received from element %s", GST_MESSAGE_SRC_NAME(message));
1017 switch (GST_MESSAGE_TYPE(message)) {
1018 case GST_MESSAGE_ERROR:
1019 if (m_resetPipeline)
1021 gst_message_parse_error(message, &err.outPtr(), &debug.outPtr());
1022 LOG_MEDIA_MESSAGE("Error %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1024 #if ENABLE(TIZEN_DLOG_SUPPORT)
1025 TIZEN_LOGE("GST_MESSAGE_ERROR %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1028 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, "webkit-video.error");
1030 error = MediaPlayer::Empty;
1031 if (err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND
1032 || err->code == GST_STREAM_ERROR_WRONG_TYPE
1033 || err->code == GST_STREAM_ERROR_FAILED
1034 || err->code == GST_CORE_ERROR_MISSING_PLUGIN
1035 || err->code == GST_RESOURCE_ERROR_NOT_FOUND)
1036 error = MediaPlayer::FormatError;
1037 else if (err->domain == GST_STREAM_ERROR) {
1038 // Let the mediaPlayerClient handle the stream error, in
1039 // this case the HTMLMediaElement will emit a stalled
1041 #if !ENABLE(TIZEN_MEDIA_STREAM)
1042 if (err->code == GST_STREAM_ERROR_TYPE_NOT_FOUND) {
1043 LOG_MEDIA_MESSAGE("Decode error, let the Media element emit a stalled event.");
1047 error = MediaPlayer::DecodeError;
1048 attemptNextLocation = true;
1049 } else if (err->domain == GST_RESOURCE_ERROR)
1050 error = MediaPlayer::NetworkError;
1052 if (attemptNextLocation)
1053 issueError = !loadNextLocation();
1055 loadingFailed(error);
1057 case GST_MESSAGE_EOS:
1058 LOG_MEDIA_MESSAGE("End of Stream");
1061 case GST_MESSAGE_STATE_CHANGED:
1062 // Ignore state changes if load is delayed (preload=none). The
1063 // player state will be updated once commitLoad() is called.
1064 if (m_delayingLoad) {
1065 LOG_MEDIA_MESSAGE("Media load has been delayed. Ignoring state changes for now");
1069 // Ignore state changes from internal elements. They are
1070 // forwarded to playbin2 anyway.
1071 if (GST_MESSAGE_SRC(message) == reinterpret_cast<GstObject*>(m_playBin.get())) {
1074 // Construct a filename for the graphviz dot file output.
1075 GstState oldState, newState;
1076 gst_message_parse_state_changed(message, &oldState, &newState, 0);
1078 CString dotFileName = String::format("webkit-video.%s_%s",
1079 gst_element_state_get_name(oldState),
1080 gst_element_state_get_name(newState)).utf8();
1082 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, dotFileName.data());
1084 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1085 if (m_suspendTime > 0 && newState == GST_STATE_PAUSED) {
1086 if (!isLocalMediaStream())
1087 seek(m_suspendTime);
1089 m_player->mediaPlayerClient()->setSuspended(false);
1094 case GST_MESSAGE_BUFFERING:
1095 processBufferingStats(message);
1097 case GST_MESSAGE_DURATION:
1098 LOG_MEDIA_MESSAGE("Duration changed");
1102 LOG_MEDIA_MESSAGE("Unhandled GStreamer message type: %s",
1103 GST_MESSAGE_TYPE_NAME(message));
1109 void MediaPlayerPrivateGStreamer::processBufferingStats(GstMessage* message)
1111 // This is the immediate buffering that needs to happen so we have
1112 // enough to play right now.
1114 const GstStructure *structure = gst_message_get_structure(message);
1115 gst_structure_get_int(structure, "buffer-percent", &m_bufferingPercentage);
1117 LOG_MEDIA_MESSAGE("[Buffering] Buffering: %d%%.", m_bufferingPercentage);
1119 GstBufferingMode mode;
1120 gst_message_parse_buffering_stats(message, &mode, 0, 0, 0);
1121 if (mode != GST_BUFFERING_DOWNLOAD) {
1126 // This is on-disk buffering, that allows us to download much more
1127 // than needed for right now.
1128 if (!m_startedBuffering) {
1129 LOG_MEDIA_MESSAGE("[Buffering] Starting on-disk buffering.");
1131 m_startedBuffering = true;
1133 if (m_fillTimer.isActive())
1136 m_fillTimer.startRepeating(0.2);
1140 void MediaPlayerPrivateGStreamer::fillTimerFired(Timer<MediaPlayerPrivateGStreamer>*)
1142 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
1144 if (!gst_element_query(m_playBin.get(), query)) {
1145 gst_query_unref(query);
1150 gdouble fillStatus = 100.0;
1152 gst_query_parse_buffering_range(query, 0, &start, &stop, 0);
1153 gst_query_unref(query);
1156 fillStatus = 100.0 * stop / GST_FORMAT_PERCENT_MAX;
1158 LOG_MEDIA_MESSAGE("[Buffering] Download buffer filled up to %f%%", fillStatus);
1160 if (!m_mediaDuration)
1163 // Update maxTimeLoaded only if the media duration is
1164 // available. Otherwise we can't compute it.
1165 if (m_mediaDuration) {
1166 if (fillStatus == 100.0)
1167 m_maxTimeLoaded = m_mediaDuration;
1169 m_maxTimeLoaded = static_cast<float>((fillStatus * m_mediaDuration) / 100.0);
1170 LOG_MEDIA_MESSAGE("[Buffering] Updated maxTimeLoaded: %f", m_maxTimeLoaded);
1173 if (fillStatus != 100.0) {
1178 // Media is now fully loaded. It will play even if network
1179 // connection is cut. Buffering is done, remove the fill source
1180 // from the main loop.
1182 m_startedBuffering = false;
1186 float MediaPlayerPrivateGStreamer::maxTimeSeekable() const
1191 LOG_MEDIA_MESSAGE("maxTimeSeekable");
1192 // infinite duration means live stream
1193 if (isinf(duration()))
1199 float MediaPlayerPrivateGStreamer::maxTimeLoaded() const
1204 float loaded = m_maxTimeLoaded;
1205 if (!loaded && !m_fillTimer.isActive())
1206 loaded = duration();
1207 LOG_MEDIA_MESSAGE("maxTimeLoaded: %f", loaded);
1211 bool MediaPlayerPrivateGStreamer::didLoadingProgress() const
1213 if (!m_playBin || !m_mediaDuration || !totalBytes())
1215 float currentMaxTimeLoaded = maxTimeLoaded();
1216 bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
1217 m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
1218 LOG_MEDIA_MESSAGE("didLoadingProgress: %d", didLoadingProgress);
1219 return didLoadingProgress;
1222 unsigned MediaPlayerPrivateGStreamer::totalBytes() const
1227 if (m_totalBytes != -1)
1228 return m_totalBytes;
1233 GstFormat fmt = GST_FORMAT_BYTES;
1235 #ifdef GST_API_VERSION_1
1236 if (gst_element_query_duration(m_source.get(), fmt, &length)) {
1238 if (gst_element_query_duration(m_source.get(), &fmt, &length)) {
1240 LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1241 m_totalBytes = static_cast<unsigned>(length);
1242 m_isStreaming = !length;
1243 return m_totalBytes;
1246 // Fall back to querying the source pads manually.
1247 // See also https://bugzilla.gnome.org/show_bug.cgi?id=638749
1248 GstIterator* iter = gst_element_iterate_src_pads(m_source.get());
1251 #ifdef GST_API_VERSION_1
1252 GValue item = G_VALUE_INIT;
1253 switch (gst_iterator_next(iter, &item)) {
1254 case GST_ITERATOR_OK: {
1255 GstPad* pad = static_cast<GstPad*>(g_value_get_object(&item));
1256 gint64 padLength = 0;
1257 if (gst_pad_query_duration(pad, fmt, &padLength) && padLength > length)
1264 switch (gst_iterator_next(iter, &data)) {
1265 case GST_ITERATOR_OK: {
1266 GRefPtr<GstPad> pad = adoptGRef(GST_PAD_CAST(data));
1267 gint64 padLength = 0;
1268 if (gst_pad_query_duration(pad.get(), &fmt, &padLength) && padLength > length)
1273 case GST_ITERATOR_RESYNC:
1274 gst_iterator_resync(iter);
1276 case GST_ITERATOR_ERROR:
1278 case GST_ITERATOR_DONE:
1283 #ifdef GST_API_VERSION_1
1284 g_value_unset(&item);
1288 gst_iterator_free(iter);
1290 LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1291 m_totalBytes = static_cast<unsigned>(length);
1292 m_isStreaming = !length;
1293 return m_totalBytes;
1296 unsigned MediaPlayerPrivateGStreamer::decodedFrameCount() const
1298 guint64 decodedFrames = 0;
1300 g_object_get(m_fpsSink, "frames-rendered", &decodedFrames, NULL);
1301 return static_cast<unsigned>(decodedFrames);
1304 unsigned MediaPlayerPrivateGStreamer::droppedFrameCount() const
1306 guint64 framesDropped = 0;
1308 g_object_get(m_fpsSink, "frames-dropped", &framesDropped, NULL);
1309 return static_cast<unsigned>(framesDropped);
1312 unsigned MediaPlayerPrivateGStreamer::audioDecodedByteCount() const
1314 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1315 gint64 position = 0;
1317 if (m_webkitAudioSink && gst_element_query(m_webkitAudioSink.get(), query))
1318 gst_query_parse_position(query, 0, &position);
1320 gst_query_unref(query);
1321 return static_cast<unsigned>(position);
1324 unsigned MediaPlayerPrivateGStreamer::videoDecodedByteCount() const
1326 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1327 gint64 position = 0;
1329 if (gst_element_query(m_webkitVideoSink, query))
1330 gst_query_parse_position(query, 0, &position);
1332 gst_query_unref(query);
1333 return static_cast<unsigned>(position);
1336 void MediaPlayerPrivateGStreamer::updateAudioSink()
1341 GstElement* sinkPtr = 0;
1343 g_object_get(m_playBin.get(), "audio-sink", &sinkPtr, NULL);
1344 m_webkitAudioSink = adoptGRef(sinkPtr);
1349 void MediaPlayerPrivateGStreamer::sourceChanged()
1351 GstElement* srcPtr = 0;
1353 g_object_get(m_playBin.get(), "source", &srcPtr, NULL);
1354 m_source = adoptGRef(srcPtr);
1356 if (WEBKIT_IS_WEB_SRC(m_source.get()))
1357 webKitWebSrcSetMediaPlayer(WEBKIT_WEB_SRC(m_source.get()), m_player);
1360 void MediaPlayerPrivateGStreamer::cancelLoad()
1362 if (m_networkState < MediaPlayer::Loading || m_networkState == MediaPlayer::Loaded)
1366 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1367 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1368 if (m_audioSessionManager)
1369 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
1373 void MediaPlayerPrivateGStreamer::updateStates()
1381 MediaPlayer::NetworkState oldNetworkState = m_networkState;
1382 MediaPlayer::ReadyState oldReadyState = m_readyState;
1386 GstStateChangeReturn ret = gst_element_get_state(m_playBin.get(),
1387 &state, &pending, 250 * GST_NSECOND);
1389 bool shouldUpdateAfterSeek = false;
1391 case GST_STATE_CHANGE_SUCCESS:
1392 LOG_MEDIA_MESSAGE("State: %s, pending: %s",
1393 gst_element_state_get_name(state),
1394 gst_element_state_get_name(pending));
1396 m_resetPipeline = state <= GST_STATE_READY;
1398 // Try to figure out ready and network states.
1399 if (state == GST_STATE_READY) {
1400 m_readyState = MediaPlayer::HaveMetadata;
1401 m_networkState = MediaPlayer::Empty;
1402 // Cache the duration without emiting the durationchange
1403 // event because it's taken care of by the media element
1404 // in this precise case.
1405 if (!m_isEndReached)
1407 } else if ((state == GST_STATE_NULL) || (maxTimeLoaded() == duration())) {
1408 m_networkState = MediaPlayer::Loaded;
1409 m_readyState = MediaPlayer::HaveEnoughData;
1411 m_readyState = currentTime() < maxTimeLoaded() ? MediaPlayer::HaveFutureData : MediaPlayer::HaveCurrentData;
1412 m_networkState = MediaPlayer::Loading;
1415 if (m_buffering && state != GST_STATE_READY) {
1416 m_readyState = MediaPlayer::HaveCurrentData;
1417 m_networkState = MediaPlayer::Loading;
1420 // Now let's try to get the states in more detail using
1421 // information from GStreamer, while we sync states where
1423 if (state == GST_STATE_PAUSED) {
1424 if (!m_webkitAudioSink)
1427 if (!m_volumeAndMuteInitialized) {
1428 notifyPlayerOfVolumeChange();
1429 notifyPlayerOfMute();
1430 m_volumeAndMuteInitialized = true;
1433 if (m_buffering && m_bufferingPercentage == 100) {
1434 m_buffering = false;
1435 m_bufferingPercentage = 0;
1436 m_readyState = MediaPlayer::HaveEnoughData;
1438 LOG_MEDIA_MESSAGE("[Buffering] Complete.");
1441 LOG_MEDIA_MESSAGE("[Buffering] Restarting playback.");
1442 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1443 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1444 if (m_audioSessionManager)
1445 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1448 } else if (!m_buffering && (currentTime() < duration())) {
1451 } else if (state == GST_STATE_PLAYING) {
1452 m_readyState = MediaPlayer::HaveEnoughData;
1455 if (m_buffering && !isLiveStream()) {
1456 m_readyState = MediaPlayer::HaveCurrentData;
1457 m_networkState = MediaPlayer::Loading;
1459 LOG_MEDIA_MESSAGE("[Buffering] Pausing stream for buffering.");
1461 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1462 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1463 if (m_audioSessionManager)
1464 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1470 // Is on-disk buffering in progress?
1471 if (m_fillTimer.isActive())
1472 m_networkState = MediaPlayer::Loading;
1474 if (m_changingRate) {
1475 m_player->rateChanged();
1476 m_changingRate = false;
1480 shouldUpdateAfterSeek = true;
1485 case GST_STATE_CHANGE_ASYNC:
1486 LOG_MEDIA_MESSAGE("Async: State: %s, pending: %s",
1487 gst_element_state_get_name(state),
1488 gst_element_state_get_name(pending));
1489 // Change in progress
1491 // On-disk buffering was attempted but the media is live. This
1492 // can't work so disable on-disk buffering and reset the
1494 if (state == GST_STATE_READY && isLiveStream() && m_preload == MediaPlayer::Auto) {
1495 setPreload(MediaPlayer::None);
1496 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1497 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1498 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1499 if (m_audioSessionManager)
1500 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1504 // A live stream was paused, reset the pipeline.
1505 if (state == GST_STATE_PAUSED && pending == GST_STATE_PLAYING && isLiveStream()) {
1506 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1507 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1508 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1509 if (m_audioSessionManager)
1510 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1514 if (!isLiveStream() && !m_buffering)
1518 shouldUpdateAfterSeek = true;
1522 case GST_STATE_CHANGE_FAILURE:
1523 LOG_MEDIA_MESSAGE("Failure: State: %s, pending: %s",
1524 gst_element_state_get_name(state),
1525 gst_element_state_get_name(pending));
1528 case GST_STATE_CHANGE_NO_PREROLL:
1529 LOG_MEDIA_MESSAGE("No preroll: State: %s, pending: %s",
1530 gst_element_state_get_name(state),
1531 gst_element_state_get_name(pending));
1533 if (state == GST_STATE_READY)
1534 m_readyState = MediaPlayer::HaveNothing;
1535 else if (state == GST_STATE_PAUSED) {
1536 m_readyState = MediaPlayer::HaveEnoughData;
1538 // Live pipelines go in PAUSED without prerolling.
1539 m_isStreaming = true;
1540 } else if (state == GST_STATE_PLAYING)
1544 shouldUpdateAfterSeek = true;
1547 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1548 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1549 if (m_audioSessionManager)
1550 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1553 } else if (!m_paused) {
1554 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1555 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1556 if (m_audioSessionManager)
1557 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1561 m_networkState = MediaPlayer::Loading;
1564 LOG_MEDIA_MESSAGE("Else : %d", ret);
1569 m_readyState = MediaPlayer::HaveNothing;
1571 if (shouldUpdateAfterSeek)
1574 if (m_networkState != oldNetworkState) {
1575 LOG_MEDIA_MESSAGE("Network State Changed from %u to %u",
1576 oldNetworkState, m_networkState);
1577 m_player->networkStateChanged();
1579 if (m_readyState != oldReadyState) {
1580 LOG_MEDIA_MESSAGE("Ready State Changed from %u to %u",
1581 oldReadyState, m_readyState);
1582 m_player->readyStateChanged();
1583 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1584 if (state == GST_STATE_PLAYING)
1585 m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
1590 void MediaPlayerPrivateGStreamer::mediaLocationChanged(GstMessage* message)
1592 if (m_mediaLocations)
1593 gst_structure_free(m_mediaLocations);
1595 const GstStructure* structure = gst_message_get_structure(message);
1597 // This structure can contain:
1598 // - both a new-location string and embedded locations structure
1599 // - or only a new-location string.
1600 m_mediaLocations = gst_structure_copy(structure);
1601 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1604 m_mediaLocationCurrentIndex = static_cast<int>(gst_value_list_get_size(locations)) -1;
1610 bool MediaPlayerPrivateGStreamer::loadNextLocation()
1612 if (!m_mediaLocations)
1615 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1616 const gchar* newLocation = 0;
1619 // Fallback on new-location string.
1620 newLocation = gst_structure_get_string(m_mediaLocations, "new-location");
1626 if (m_mediaLocationCurrentIndex < 0) {
1627 m_mediaLocations = 0;
1631 const GValue* location = gst_value_list_get_value(locations,
1632 m_mediaLocationCurrentIndex);
1633 const GstStructure* structure = gst_value_get_structure(location);
1636 m_mediaLocationCurrentIndex--;
1640 newLocation = gst_structure_get_string(structure, "new-location");
1644 // Found a candidate. new-location is not always an absolute url
1645 // though. We need to take the base of the current url and
1646 // append the value of new-location to it.
1648 gchar* currentLocation = 0;
1649 g_object_get(m_playBin.get(), "uri", ¤tLocation, NULL);
1651 KURL currentUrl(KURL(), currentLocation);
1652 g_free(currentLocation);
1656 if (gst_uri_is_valid(newLocation))
1657 newUrl = KURL(KURL(), newLocation);
1659 newUrl = KURL(KURL(), currentUrl.baseAsString() + newLocation);
1661 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(currentUrl);
1662 if (securityOrigin->canRequest(newUrl)) {
1663 LOG_MEDIA_MESSAGE("New media url: %s", newUrl.string().utf8().data());
1665 // Reset player states.
1666 m_networkState = MediaPlayer::Loading;
1667 m_player->networkStateChanged();
1668 m_readyState = MediaPlayer::HaveNothing;
1669 m_player->readyStateChanged();
1671 // Reset pipeline state.
1672 m_resetPipeline = true;
1673 gst_element_set_state(m_playBin.get(), GST_STATE_READY);
1674 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1675 if (m_audioSessionManager)
1676 m_audioSessionManager->setSoundState(ASM_STATE_NONE);
1679 gst_element_get_state(m_playBin.get(), &state, 0, 0);
1680 if (state <= GST_STATE_READY) {
1681 // Set the new uri and start playing.
1682 g_object_set(m_playBin.get(), "uri", newUrl.string().utf8().data(), NULL);
1683 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1684 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1685 if (m_audioSessionManager)
1686 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1692 m_mediaLocationCurrentIndex--;
1697 void MediaPlayerPrivateGStreamer::loadStateChanged()
1702 void MediaPlayerPrivateGStreamer::sizeChanged()
1707 void MediaPlayerPrivateGStreamer::timeChanged()
1710 m_player->timeChanged();
1713 void MediaPlayerPrivateGStreamer::didEnd()
1715 // Synchronize position and duration values to not confuse the
1716 // HTMLMediaElement. In some cases like reverse playback the
1717 // position is not always reported as 0 for instance.
1718 float now = currentTime();
1719 if (now > 0 && now <= duration() && m_mediaDuration != now) {
1720 m_mediaDurationKnown = true;
1721 m_mediaDuration = now;
1722 m_player->durationChanged();
1725 m_isEndReached = true;
1728 if (!m_player->mediaPlayerClient()->mediaPlayerIsLooping()) {
1730 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1731 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1732 if (m_audioSessionManager)
1733 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1735 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1738 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1739 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
1740 if (element->isVideo())
1741 power_unlock_state(POWER_STATE_NORMAL);
1746 void MediaPlayerPrivateGStreamer::cacheDuration()
1748 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1749 float previousDuration = m_mediaDuration;
1751 // Reset cached media duration
1752 m_mediaDuration = 0;
1754 // And re-cache it if possible.
1756 gst_element_get_state(m_playBin.get(), &state, 0, 0);
1757 float newDuration = duration();
1759 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1760 if (state > GST_STATE_READY) {
1761 // Don't set m_mediaDurationKnown yet if the pipeline is not
1762 // paused. This allows duration() query to fail at least once
1763 // before playback starts and duration becomes known.
1764 m_mediaDurationKnown = !isinf(newDuration);
1767 if (!isinf(newDuration))
1768 m_mediaDuration = newDuration;
1770 m_mediaDuration = previousDuration;
1772 if (state <= GST_STATE_READY) {
1773 // Don't set m_mediaDurationKnown yet if the pipeline is not
1774 // paused. This allows duration() query to fail at least once
1775 // before playback starts and duration becomes known.
1776 if (!isinf(newDuration))
1777 m_mediaDuration = newDuration;
1779 m_mediaDurationKnown = !isinf(newDuration);
1780 if (m_mediaDurationKnown)
1781 m_mediaDuration = newDuration;
1784 if (!isinf(newDuration))
1785 m_mediaDuration = newDuration;
1789 void MediaPlayerPrivateGStreamer::durationChanged()
1791 float previousDuration = m_mediaDuration;
1794 // Avoid emiting durationchanged in the case where the previous
1795 // duration was 0 because that case is already handled by the
1796 // HTMLMediaElement.
1797 if (previousDuration && m_mediaDuration != previousDuration)
1798 m_player->durationChanged();
1800 if (m_preload == MediaPlayer::None && m_originalPreloadWasAutoAndWasOverridden) {
1802 if (totalBytes() && !isLiveStream()) {
1803 setPreload(MediaPlayer::Auto);
1804 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1805 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1806 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1807 if (m_audioSessionManager)
1808 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1814 bool MediaPlayerPrivateGStreamer::supportsMuting() const
1819 void MediaPlayerPrivateGStreamer::setMuted(bool muted)
1824 g_object_set(m_playBin.get(), "mute", muted, NULL);
1827 void MediaPlayerPrivateGStreamer::notifyPlayerOfMute()
1829 m_muteTimerHandler = 0;
1831 if (!m_player || !m_playBin)
1835 g_object_get(m_playBin.get(), "mute", &muted, NULL);
1836 m_player->muteChanged(static_cast<bool>(muted));
1839 void MediaPlayerPrivateGStreamer::muteChanged()
1841 if (m_muteTimerHandler)
1842 g_source_remove(m_muteTimerHandler);
1843 m_muteTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateMuteChangeTimeoutCallback), this);
1846 void MediaPlayerPrivateGStreamer::loadingFailed(MediaPlayer::NetworkState error)
1848 #if ENABLE(TIZEN_DLOG_SUPPORT)
1849 TIZEN_LOGE("NetworkState : %d", error);
1852 m_errorOccured = true;
1853 if (m_networkState != error) {
1854 m_networkState = error;
1855 m_player->networkStateChanged();
1857 if (m_readyState != MediaPlayer::HaveNothing) {
1858 m_readyState = MediaPlayer::HaveNothing;
1859 m_player->readyStateChanged();
1863 void MediaPlayerPrivateGStreamer::setSize(const IntSize& size)
1868 void MediaPlayerPrivateGStreamer::setVisible(bool visible)
1872 void MediaPlayerPrivateGStreamer::triggerRepaint(GstBuffer* buffer)
1874 g_return_if_fail(GST_IS_BUFFER(buffer));
1875 gst_buffer_replace(&m_buffer, buffer);
1876 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1877 #if !ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1878 if (m_videoSize.isEmpty())
1879 m_videoSize = naturalSize();
1880 m_videoLayer->paintVideoLayer(m_videoSize);
1884 m_player->repaint();
1887 void MediaPlayerPrivateGStreamer::paint(GraphicsContext* context, const IntRect& rect)
1889 if (context->paintingDisabled())
1892 if (!m_player->visible())
1898 GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
1902 RefPtr<ImageGStreamer> gstImage = ImageGStreamer::createImage(m_buffer, caps.get());
1906 context->drawImage(reinterpret_cast<Image*>(gstImage->image().get()), ColorSpaceSRGB,
1907 rect, gstImage->rect(), CompositeCopy, DoNotRespectImageOrientation, false);
1910 static HashSet<String> mimeTypeCache()
1912 initializeGStreamerAndRegisterWebKitElements();
1914 DEFINE_STATIC_LOCAL(HashSet<String>, cache, ());
1915 static bool typeListInitialized = false;
1917 if (typeListInitialized)
1919 const char* mimeTypes[] = {
1921 "application/vnd.apple.mpegurl",
1922 "application/vnd.rn-realmedia",
1923 "application/x-3gp",
1924 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1925 "application/x-mpegurl",
1926 "application/x-mpegURL",
1928 "application/x-pn-realaudio",
1948 "audio/x-amr-nb-sh",
1949 "audio/x-amr-wb-sh",
1980 "audio/x-vorbis+ogg",
1984 "audio/x-wavpack-correction",
2011 for (unsigned i = 0; i < (sizeof(mimeTypes) / sizeof(*mimeTypes)); ++i)
2012 cache.add(String(mimeTypes[i]));
2014 typeListInitialized = true;
2018 void MediaPlayerPrivateGStreamer::getSupportedTypes(HashSet<String>& types)
2020 types = mimeTypeCache();
2023 MediaPlayer::SupportsType MediaPlayerPrivateGStreamer::supportsType(const String& type, const String& codecs, const KURL&)
2025 if (type.isNull() || type.isEmpty())
2026 return MediaPlayer::IsNotSupported;
2028 // spec says we should not return "probably" if the codecs string is empty
2029 if (mimeTypeCache().contains(type))
2030 return codecs.isEmpty() ? MediaPlayer::MayBeSupported : MediaPlayer::IsSupported;
2031 return MediaPlayer::IsNotSupported;
2034 bool MediaPlayerPrivateGStreamer::hasSingleSecurityOrigin() const
2039 bool MediaPlayerPrivateGStreamer::supportsFullscreen() const
2041 #if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
2042 // See <rdar://problem/7389945>
2049 PlatformMedia MediaPlayerPrivateGStreamer::platformMedia() const
2052 #ifndef GST_API_VERSION_1
2053 p.type = PlatformMedia::GStreamerGWorldType;
2054 p.media.gstreamerGWorld = m_gstGWorld.get();
2059 MediaPlayer::MovieLoadType MediaPlayerPrivateGStreamer::movieLoadType() const
2061 if (m_readyState == MediaPlayer::HaveNothing)
2062 return MediaPlayer::Unknown;
2065 return MediaPlayer::LiveStream;
2067 return MediaPlayer::Download;
2070 void MediaPlayerPrivateGStreamer::setDownloadBuffering()
2077 g_object_get(m_playBin.get(), "flags", &flags, NULL);
2078 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2079 flags = (GstPlayFlags)(flags | GST_PLAY_FLAG_NATIVE_VIDEO);
2081 if (m_preload == MediaPlayer::Auto) {
2082 LOG_MEDIA_MESSAGE("Enabling on-disk buffering");
2083 g_object_set(m_playBin.get(), "flags", flags | GST_PLAY_FLAG_DOWNLOAD, NULL);
2085 LOG_MEDIA_MESSAGE("Disabling on-disk buffering");
2086 g_object_set(m_playBin.get(), "flags", flags & ~GST_PLAY_FLAG_DOWNLOAD, NULL);
2090 void MediaPlayerPrivateGStreamer::setPreload(MediaPlayer::Preload preload)
2092 m_originalPreloadWasAutoAndWasOverridden = m_preload != preload && m_preload == MediaPlayer::Auto;
2094 m_preload = preload;
2096 setDownloadBuffering();
2098 if (m_delayingLoad && m_preload != MediaPlayer::None) {
2099 m_delayingLoad = false;
2104 void MediaPlayerPrivateGStreamer::createAudioSink()
2106 // Construct audio sink if pitch preserving is enabled.
2107 if (!m_preservesPitch)
2113 GstElement* scale = gst_element_factory_make("scaletempo", 0);
2115 GST_WARNING("Failed to create scaletempo");
2119 GstElement* convert = gst_element_factory_make("audioconvert", 0);
2120 GstElement* resample = gst_element_factory_make("audioresample", 0);
2121 GstElement* sink = gst_element_factory_make("autoaudiosink", 0);
2123 GstElement* audioSink = gst_bin_new("audio-sink");
2124 gst_bin_add_many(GST_BIN(audioSink), scale, convert, resample, sink, NULL);
2126 if (!gst_element_link_many(scale, convert, resample, sink, NULL)) {
2127 GST_WARNING("Failed to link audio sink elements");
2128 gst_object_unref(audioSink);
2132 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(scale, "sink"));
2133 gst_element_add_pad(audioSink, gst_ghost_pad_new("sink", pad.get()));
2135 g_object_set(m_playBin.get(), "audio-sink", audioSink, NULL);
2138 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2139 GstElement* MediaPlayerPrivateGStreamer::createVideoSink()
2141 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2142 m_webkitVideoSink = m_videoLayer->createVideoSink();
2143 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2145 // Primary video should be OFF and Secondary video should be FULL SCREEN mode
2146 g_object_set(m_webkitVideoSink, "display-mode", 2, NULL);
2147 #else // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2148 #ifndef GST_API_VERSION_1
2149 m_webkitVideoSink = webkitVideoSinkNew(m_gstGWorld.get());
2151 m_webkitVideoSink = webkitVideoSinkNew();
2153 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2154 g_signal_connect(m_webkitVideoSink, "repaint-requested", G_CALLBACK(mediaPlayerPrivateRepaintCallback), this);
2155 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2157 #ifndef GST_API_VERSION_1
2158 m_videoSinkBin = gst_bin_new("video-sink");
2159 GstElement* videoTee = gst_element_factory_make("tee", "videoTee");
2160 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2161 GstElement* queue = gst_element_factory_make("queue", 0);
2164 gst_object_ref_sink(m_videoSinkBin);
2166 // Build a new video sink consisting of a bin containing a tee
2167 // (meant to distribute data to multiple video sinks) and our
2168 // internal video sink. For fullscreen we create an autovideosink
2169 // and initially block the data flow towards it and configure it
2170 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2171 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, queue, NULL);
2173 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, NULL);
2176 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2177 // Link a new src pad from tee to queue1.
2178 gst_element_link_pads_full(videoTee, 0, queue, "sink", GST_PAD_LINK_CHECK_NOTHING);
2182 GstElement* actualVideoSink = 0;
2183 m_fpsSink = gst_element_factory_make("fpsdisplaysink", "sink");
2185 // The verbose property has been added in -bad 0.10.22. Making
2186 // this whole code depend on it because we don't want
2187 // fpsdiplaysink to spit data on stdout.
2188 GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(m_fpsSink)->elementfactory);
2189 if (gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 22)) {
2190 g_object_set(m_fpsSink, "silent", TRUE , NULL);
2192 // Turn off text overlay unless logging is enabled.
2194 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2196 WTFLogChannel* channel = getChannelFromName("Media");
2197 if (channel->state != WTFLogChannelOn)
2198 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2199 #endif // LOG_DISABLED
2201 if (g_object_class_find_property(G_OBJECT_GET_CLASS(m_fpsSink), "video-sink")) {
2202 g_object_set(m_fpsSink, "video-sink", m_webkitVideoSink, NULL);
2203 #ifndef GST_API_VERSION_1
2204 gst_bin_add(GST_BIN(m_videoSinkBin), m_fpsSink);
2206 actualVideoSink = m_fpsSink;
2214 #ifndef GST_API_VERSION_1
2215 gst_bin_add(GST_BIN(m_videoSinkBin), m_webkitVideoSink);
2217 actualVideoSink = m_webkitVideoSink;
2220 ASSERT(actualVideoSink);
2222 #ifndef GST_API_VERSION_1
2223 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2224 // Link a new src pad from tee to queue1.
2225 GRefPtr<GstPad> srcPad = adoptGRef(gst_element_get_request_pad(videoTee, "src%d"));
2226 GRefPtr<GstPad> sinkPad = adoptGRef(gst_element_get_static_pad(actualVideoSink, "sink"));
2227 gst_pad_link(srcPad.get(), sinkPad.get());
2229 // Faster elements linking.
2230 gst_element_link_pads_full(queue, "src", actualVideoSink, "sink", GST_PAD_LINK_CHECK_NOTHING);
2232 // Add a ghostpad to the bin so it can proxy to tee.
2233 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(videoTee, "sink"));
2234 gst_element_add_pad(m_videoSinkBin, gst_ghost_pad_new("sink", pad.get()));
2236 // Set the bin as video sink of playbin.
2237 return m_videoSinkBin;
2239 return actualVideoSink;
2244 void MediaPlayerPrivateGStreamer::createGSTPlayBin()
2248 // gst_element_factory_make() returns a floating reference so
2249 // we should not adopt.
2250 m_playBin = gst_element_factory_make(gPlaybinName, "play");
2252 #ifndef GST_API_VERSION_1
2253 m_gstGWorld = GStreamerGWorld::createGWorld(m_playBin.get());
2256 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
2257 gst_bus_add_signal_watch(bus.get());
2258 g_signal_connect(bus.get(), "message", G_CALLBACK(mediaPlayerPrivateMessageCallback), this);
2259 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2260 gst_bus_set_sync_handler(bus.get(), GstBusSyncHandler(mediaPlayerPrivateSyncHandler), this);
2262 gst_object_unref(bus.get());
2264 g_object_set(m_playBin.get(), "mute", m_player->muted(), NULL);
2266 g_signal_connect(m_playBin.get(), "notify::volume", G_CALLBACK(mediaPlayerPrivateVolumeChangedCallback), this);
2267 g_signal_connect(m_playBin.get(), "notify::source", G_CALLBACK(mediaPlayerPrivateSourceChangedCallback), this);
2268 g_signal_connect(m_playBin.get(), "notify::mute", G_CALLBACK(mediaPlayerPrivateMuteChangedCallback), this);
2269 g_signal_connect(m_playBin.get(), "video-changed", G_CALLBACK(mediaPlayerPrivateVideoChangedCallback), this);
2270 g_signal_connect(m_playBin.get(), "audio-changed", G_CALLBACK(mediaPlayerPrivateAudioChangedCallback), this);
2271 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2272 g_signal_connect(m_playBin.get(), "source-setup", G_CALLBACK(mediaPlayerPrivateSourceSetupCallback), this);
2275 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2276 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
2277 if (element->isVideo()) {
2278 GstElement* videoElement = createVideoSink();
2279 g_object_set(m_playBin.get(), "video-sink", videoElement, NULL);
2281 GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2283 g_signal_connect(videoSinkPad.get(), "notify::caps", G_CALLBACK(mediaPlayerPrivateVideoSinkCapsChangedCallback), this);
2285 GstElement* fakeSink = gst_element_factory_make("fakesink", 0);
2286 g_object_set(fakeSink, "sync", true, NULL);
2287 g_object_set(m_playBin.get(), "video-sink", fakeSink, NULL);
2290 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2291 GstElement* realSink = gst_element_factory_make("avsysaudiosink", 0);
2292 g_object_set(realSink, "close-handle-on-prepare", 1, NULL);
2293 g_object_set(m_playBin.get(), "audio-sink", realSink, NULL);
2295 if (m_audioSessionManager)
2296 m_audioSessionManager->registerAudioSessionManager(MM_SESSION_TYPE_SHARE, mediaPlayerPrivateAudioSessionNotifyCallback, player());
2302 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2303 bool MediaPlayerPrivateGStreamer::supportsAcceleratedRendering() const
2305 bool isEmbedVideo = false;
2306 if (m_player->mediaPlayerClient()) {
2307 Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
2308 if (document && document->settings()) {
2309 isEmbedVideo = document->settings()->acceleratedCompositingForVideoEnabled()
2310 && document->settings()->acceleratedCompositingEnabled();
2311 LOG_MEDIA_MESSAGE("isEmbedVideo: %d", isEmbedVideo);
2315 return isEmbedVideo;
2318 PlatformLayer* MediaPlayerPrivateGStreamer::platformLayer() const
2320 return m_videoLayer->platformLayer();
2323 #if ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2324 void MediaPlayerPrivateGStreamer::paintCurrentFrameInContext(GraphicsContext* context, const IntRect& rect)
2326 m_videoLayer->paintCurrentFrameInContext(context, rect);
2329 #if USE(ACCELERATED_VIDEO_VAAPI)
2330 // Other device doesn't prefer such optimization, so enclose it in USE(ACCELERATED_VIDEO_VAAPI) macro
2331 IntSize MediaPlayerPrivateGStreamer::scaleHDVideoToDisplaySize(int videoWidth, int videoHeight, int displayWidth, int displayHeight) const
2333 int fitWidth, fitHeight;
2335 #if ENABLE(TIZEN_DLOG_SUPPORT)
2336 TIZEN_LOGI("videoWidth: %d, videoHeight: %d, displayWidth: %d, displayHeight: %d ", videoWidth, videoHeight, displayWidth, displayHeight);
2338 fitWidth = videoWidth;
2339 fitHeight = videoHeight;
2340 if (displayWidth > 0 && displayHeight > 0) {
2341 // In case video is rotated, we always use a 'better'
2342 // orientation (landscape or portrait) to calculate fitWidth/fitHeight.
2343 // It means we use a bigger size which doesn't lose quality
2344 // in either landscape or portrait orientation
2345 if ((videoWidth > videoHeight && displayWidth < displayHeight)
2346 || (videoWidth < videoHeight && displayWidth > displayHeight)) {
2349 displayWidth = displayHeight;
2350 displayHeight = tmp;
2353 if (videoWidth > displayWidth || videoHeight > displayHeight) {
2354 if (videoWidth * displayHeight > videoHeight * displayWidth) {
2355 fitWidth = displayWidth;
2356 fitHeight = videoHeight * displayWidth / videoWidth;
2357 ASSERT(fitHeight <= displayHeight);
2359 fitWidth = videoWidth * displayHeight / videoHeight;
2360 fitHeight = displayHeight;
2361 ASSERT(fitWidth <= displayWidth);
2366 return IntSize(fitWidth, fitHeight);
2369 void MediaPlayerPrivateGStreamer::xWindowIdPrepared(GstMessage* message)
2371 // It is called in streaming thread.
2372 // It should be used only to set window handle to video sink.
2374 int videoWidth, videoHeight;
2375 gst_structure_get_int(message->structure, "video-width", &videoWidth);
2376 gst_structure_get_int(message->structure, "video-height", &videoHeight);
2378 #if ENABLE(TIZEN_DLOG_SUPPORT)
2379 TIZEN_LOGI("videoWidth: %d, videoHeight: %d", videoWidth, videoHeight);
2382 #if USE(ACCELERATED_VIDEO_VAAPI)
2383 int displayWidth, displayHeight;
2384 gst_structure_get_int(message->structure, "display-width", &displayWidth);
2385 gst_structure_get_int(message->structure, "display-height", &displayHeight);
2387 m_displaySize = IntSize(displayWidth, displayHeight);
2388 m_videoSize = scaleHDVideoToDisplaySize(videoWidth, videoHeight, displayWidth, displayHeight);
2390 m_videoSize = IntSize(videoWidth, videoHeight);
2392 m_videoLayer->setOverlay(m_videoSize);
2395 #endif // ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2396 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2398 #if ENABLE(TIZEN_WEBKIT2_PROXY)
2399 void MediaPlayerPrivateGStreamer::setProxy(GstElement* source)
2401 SoupSession* session = WebCore::ResourceHandle::defaultSession();
2405 SoupURI* proxyUri = 0;
2406 g_object_get(session, SOUP_SESSION_PROXY_URI, &proxyUri, NULL);
2410 char* proxy = soup_uri_to_string(proxyUri, false);
2411 g_object_set(source, "proxy", proxy, NULL);
2413 soup_uri_free(proxyUri);
2418 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2419 void MediaPlayerPrivateGStreamer::suspend()
2421 m_suspendTime = currentTime();
2422 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
2423 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2424 if (m_audioSessionManager)
2425 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
2429 void MediaPlayerPrivateGStreamer::resume()
2431 if (isLocalMediaStream()) {
2432 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
2433 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2434 if (m_audioSessionManager)
2435 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
2438 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
2439 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2440 if (m_audioSessionManager)
2441 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
2446 bool MediaPlayerPrivateGStreamer::isLocalMediaStream()
2448 if (m_url.string().contains("camera://"))
2453 #endif // ENABLE(TIZEN_GSTREAMER_VIDEO)
2457 #endif // USE(GSTREAMER)