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);
243 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->mediaPlayerClient());
246 return ASM_CB_RES_IGNORE;
248 switch (eventSource) {
249 case ASM_EVENT_SOURCE_CALL_START:
250 case ASM_EVENT_SOURCE_ALARM_START:
251 case ASM_EVENT_SOURCE_MEDIA:
252 case ASM_EVENT_SOURCE_EMERGENCY_START:
253 case ASM_EVENT_SOURCE_OTHER_PLAYER_APP:
254 case ASM_EVENT_SOURCE_RESOURCE_CONFLICT:
255 case ASM_EVENT_SOURCE_EARJACK_UNPLUG:
256 if (!player->url().string().contains("camera://")) {
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);
268 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->mediaPlayerClient());
271 return ASM_CB_RES_IGNORE;
273 switch (eventSource) {
274 case ASM_EVENT_SOURCE_ALARM_END:
275 if (!element->isVideo() && !player->url().string().contains("camera://")) {
277 return ASM_CB_RES_PLAYING;
279 return ASM_CB_RES_NONE;
281 return ASM_CB_RES_NONE;
285 static ASM_cb_result_t mediaPlayerPrivateAudioSessionNotifyCallback(int, ASM_event_sources_t eventSource, ASM_sound_commands_t command, unsigned int, void* callbackData)
287 if (command == ASM_COMMAND_STOP || command == ASM_COMMAND_PAUSE)
288 return MediaPlayerAudioSessionEventSourcePause(eventSource, callbackData);
289 if (command == ASM_COMMAND_PLAY || command == ASM_COMMAND_RESUME)
290 return MediaPlayerAudioSessionEventSourcePlay(eventSource, callbackData);
292 return ASM_CB_RES_NONE;
296 PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivateGStreamer::create(MediaPlayer* player)
298 return adoptPtr(new MediaPlayerPrivateGStreamer(player));
301 void MediaPlayerPrivateGStreamer::registerMediaEngine(MediaEngineRegistrar registrar)
304 registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
307 bool initializeGStreamerAndRegisterWebKitElements()
309 if (!initializeGStreamer())
312 GRefPtr<GstElementFactory> srcFactory = gst_element_factory_find("webkitwebsrc");
314 #if ENABLE(TIZEN_MEDIA_STREAM)
315 return gst_element_register(0, "webkitcamerasrc", GST_RANK_PRIMARY + 200, WEBKIT_TYPE_CAMERA_SRC);
317 GST_DEBUG_CATEGORY_INIT(webkit_media_player_debug, "webkitmediaplayer", 0, "WebKit media player");
318 return gst_element_register(0, "webkitwebsrc", GST_RANK_PRIMARY + 100, WEBKIT_TYPE_WEB_SRC);
319 #endif // ENABLE(TIZEN_MEDIA_STREAM)
324 bool MediaPlayerPrivateGStreamer::isAvailable()
326 if (!initializeGStreamerAndRegisterWebKitElements())
329 GRefPtr<GstElementFactory> factory = gst_element_factory_find(gPlaybinName);
333 MediaPlayerPrivateGStreamer::MediaPlayerPrivateGStreamer(MediaPlayer* player)
335 , m_webkitVideoSink(0)
336 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
342 , m_changingRate(false)
343 , m_endTime(numeric_limits<float>::infinity())
344 , m_isEndReached(false)
345 , m_networkState(MediaPlayer::Empty)
346 , m_readyState(MediaPlayer::HaveNothing)
347 , m_isStreaming(false)
350 , m_mediaLocations(0)
351 , m_mediaLocationCurrentIndex(0)
352 , m_resetPipeline(false)
357 , m_errorOccured(false)
359 , m_startedBuffering(false)
360 , m_fillTimer(this, &MediaPlayerPrivateGStreamer::fillTimerFired)
362 , m_bufferingPercentage(0)
363 , m_preload(MediaPlayer::Auto)
364 , m_delayingLoad(false)
365 , m_mediaDurationKnown(true)
366 , m_maxTimeLoadedAtLastDidLoadingProgress(0)
367 , m_volumeTimerHandler(0)
368 , m_muteTimerHandler(0)
371 , m_audioTimerHandler(0)
372 , m_videoTimerHandler(0)
373 , m_webkitAudioSink(0)
375 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
376 , m_videoLayer(VideoLayerTizen::create(static_cast<HTMLMediaElement*>(player->mediaPlayerClient())))
377 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
378 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
379 , m_audioSessionManager(AudioSessionManagerGStreamerTizen::createAudioSessionManager())
381 , m_originalPreloadWasAutoAndWasOverridden(false)
382 , m_preservesPitch(false)
383 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
389 MediaPlayerPrivateGStreamer::~MediaPlayerPrivateGStreamer()
391 if (m_fillTimer.isActive())
395 gst_buffer_unref(m_buffer);
398 if (m_mediaLocations) {
399 gst_structure_free(m_mediaLocations);
400 m_mediaLocations = 0;
403 #ifndef GST_API_VERSION_1
404 if (m_videoSinkBin) {
405 gst_object_unref(m_videoSinkBin);
411 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
413 g_signal_handlers_disconnect_by_func(bus.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateMessageCallback), this);
414 gst_bus_remove_signal_watch(bus.get());
416 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
422 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
423 if (m_audioSessionManager)
424 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
427 if (m_muteTimerHandler)
428 g_source_remove(m_muteTimerHandler);
430 if (m_volumeTimerHandler)
431 g_source_remove(m_volumeTimerHandler);
433 if (m_videoTimerHandler)
434 g_source_remove(m_videoTimerHandler);
436 if (m_audioTimerHandler)
437 g_source_remove(m_audioTimerHandler);
440 void MediaPlayerPrivateGStreamer::load(const String& url)
442 if (!initializeGStreamerAndRegisterWebKitElements())
445 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
447 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
448 KURL kurl(KURL(), url);
449 String cleanUrl(url);
451 // Clean out everything after file:// url path.
452 if (kurl.isLocalFile())
453 cleanUrl = cleanUrl.substring(0, kurl.pathEnd());
457 setDownloadBuffering();
462 m_url = KURL(KURL(), cleanUrl);
463 g_object_set(m_playBin.get(), "uri", cleanUrl.utf8().data(), NULL);
465 LOG_MEDIA_MESSAGE("Load %s", cleanUrl.utf8().data());
467 #if ENABLE(TIZEN_MEDIA_STREAM)
468 // Workaround modification for getUserMedia.
469 // When 'playing' event is fired videoWidth and videoHeight are not available.
470 // Set m_videoSize as frame size which comes from webkitCameraSource.
471 // This size is fixed.
472 if (isLocalMediaStream())
473 if (gst_element_factory_find("camerasrc"))
474 m_videoSize = IntSize(480, 640);
476 m_videoSize = IntSize(640, 480);
479 if (m_preload == MediaPlayer::None) {
480 LOG_MEDIA_MESSAGE("Delaying load.");
481 m_delayingLoad = true;
484 // Reset network and ready states. Those will be set properly once
485 // the pipeline pre-rolled.
486 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
488 m_networkState = MediaPlayer::Loading;
490 m_networkState = MediaPlayer::Idle;
492 m_networkState = MediaPlayer::Loading;
494 m_player->networkStateChanged();
495 m_readyState = MediaPlayer::HaveNothing;
496 m_player->readyStateChanged();
497 m_volumeAndMuteInitialized = false;
499 // GStreamer needs to have the pipeline set to a paused state to
500 // start providing anything useful.
501 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
504 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
506 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
507 if (m_audioSessionManager && !m_delayingLoad)
508 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
515 void MediaPlayerPrivateGStreamer::commitLoad()
517 ASSERT(!m_delayingLoad);
518 LOG_MEDIA_MESSAGE("Committing load.");
522 float MediaPlayerPrivateGStreamer::playbackPosition() const
524 if (m_isEndReached) {
525 // Position queries on a null pipeline return 0. If we're at
526 // the end of the stream the pipeline is null but we want to
527 // report either the seek time or the duration because this is
528 // what the Media element spec expects us to do.
532 return m_mediaDuration;
537 GstQuery* query = gst_query_new_position(GST_FORMAT_TIME);
538 if (!gst_element_query(m_playBin.get(), query)) {
539 LOG_MEDIA_MESSAGE("Position query failed...");
540 gst_query_unref(query);
545 gst_query_parse_position(query, 0, &position);
547 // Position is available only if the pipeline is not in GST_STATE_NULL or
548 // GST_STATE_READY state.
549 if (position != static_cast<gint64>(GST_CLOCK_TIME_NONE))
550 ret = static_cast<double>(position) / GST_SECOND;
552 LOG_MEDIA_MESSAGE("Position %" GST_TIME_FORMAT, GST_TIME_ARGS(position));
554 gst_query_unref(query);
559 bool MediaPlayerPrivateGStreamer::changePipelineState(GstState newState)
561 ASSERT(newState == GST_STATE_PLAYING || newState == GST_STATE_PAUSED);
563 GstState currentState;
566 gst_element_get_state(m_playBin.get(), ¤tState, &pending, 0);
567 LOG_MEDIA_MESSAGE("Current state: %s, pending: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
568 #if ENABLE(TIZEN_DLOG_SUPPORT)
569 TIZEN_LOGI("Current state: %s, New state: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(newState));
571 if (currentState == newState || pending == newState)
574 GstStateChangeReturn setStateResult = gst_element_set_state(m_playBin.get(), newState);
575 GstState pausedOrPlaying = newState == GST_STATE_PLAYING ? GST_STATE_PAUSED : GST_STATE_PLAYING;
576 if (currentState != pausedOrPlaying && setStateResult == GST_STATE_CHANGE_FAILURE) {
577 loadingFailed(MediaPlayer::Empty);
583 void MediaPlayerPrivateGStreamer::prepareToPlay()
585 m_isEndReached = false;
588 if (m_delayingLoad) {
589 m_delayingLoad = false;
594 void MediaPlayerPrivateGStreamer::play()
596 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
597 if (!m_audioSessionManager->setSoundState(ASM_STATE_PLAYING) && !isLocalMediaStream())
600 if (changePipelineState(GST_STATE_PLAYING)) {
601 m_isEndReached = false;
602 LOG_MEDIA_MESSAGE("Play");
606 void MediaPlayerPrivateGStreamer::pause()
608 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
609 if (!m_audioSessionManager->setSoundState(ASM_STATE_PAUSE) && !isLocalMediaStream())
615 if (changePipelineState(GST_STATE_PAUSED))
616 LOG_MEDIA_MESSAGE("Pause");
619 float MediaPlayerPrivateGStreamer::duration() const
627 // Media duration query failed already, don't attempt new useless queries.
628 if (!m_mediaDurationKnown)
629 return numeric_limits<float>::infinity();
632 return m_mediaDuration;
634 GstFormat timeFormat = GST_FORMAT_TIME;
635 gint64 timeLength = 0;
637 #ifdef GST_API_VERSION_1
638 bool failure = !gst_element_query_duration(m_playBin.get(), timeFormat, &timeLength) || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
640 bool failure = !gst_element_query_duration(m_playBin.get(), &timeFormat, &timeLength) || timeFormat != GST_FORMAT_TIME || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
643 LOG_MEDIA_MESSAGE("Time duration query failed for %s", m_url.string().utf8().data());
644 return numeric_limits<float>::infinity();
647 LOG_MEDIA_MESSAGE("Duration: %" GST_TIME_FORMAT, GST_TIME_ARGS(timeLength));
649 return static_cast<double>(timeLength) / GST_SECOND;
650 // FIXME: handle 3.14.9.5 properly
653 float MediaPlayerPrivateGStreamer::currentTime() const
665 // https://bugzilla.gnome.org/show_bug.cgi?id=639941 In GStreamer
666 // 0.10.35 basesink reports wrong duration in case of EOS and
667 // negative playback rate. There's no upstream accepted patch for
668 // this bug yet, hence this temporary workaround.
669 if (m_isEndReached && m_playbackRate < 0)
672 return playbackPosition();
676 void MediaPlayerPrivateGStreamer::seek(float time)
684 LOG_MEDIA_MESSAGE("Seek attempt to %f secs", time);
685 #if ENABLE(TIZEN_DLOG_SUPPORT)
686 TIZEN_LOGI("Seek attempt to %f secs", time);
689 // Avoid useless seeking.
690 if (time == currentTime())
693 // Extract the integer part of the time (seconds) and the
694 // fractional part (microseconds). Attempt to round the
695 // microseconds so no floating point precision is lost and we can
696 // perform an accurate seek.
698 float microSeconds = modf(time, &seconds) * 1000000;
700 timeValue.tv_sec = static_cast<glong>(seconds);
701 timeValue.tv_usec = static_cast<glong>(roundf(microSeconds / 10000) * 10000);
703 GstClockTime clockTime = GST_TIMEVAL_TO_TIME(timeValue);
704 LOG_MEDIA_MESSAGE("Seek: %" GST_TIME_FORMAT, GST_TIME_ARGS(clockTime));
706 if (!gst_element_seek(m_playBin.get(), m_player->rate(),
708 (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE),
709 GST_SEEK_TYPE_SET, clockTime,
710 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) {
711 LOG_MEDIA_MESSAGE("Seek to %f failed", time);
712 #if ENABLE(TIZEN_DLOG_SUPPORT)
713 TIZEN_LOGE("Seek to %f failed", time);
718 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
719 if (m_seekTime != m_mediaDuration)
720 m_isEndReached = false;
725 bool MediaPlayerPrivateGStreamer::paused() const
727 if (m_isEndReached) {
728 LOG_MEDIA_MESSAGE("Ignoring pause at EOS");
733 gst_element_get_state(m_playBin.get(), &state, 0, 0);
734 return state == GST_STATE_PAUSED;
737 bool MediaPlayerPrivateGStreamer::seeking() const
742 // Returns the size of the video
743 IntSize MediaPlayerPrivateGStreamer::naturalSize() const
748 if (!m_videoSize.isEmpty())
751 GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
756 // TODO: handle possible clean aperture data. See
757 // https://bugzilla.gnome.org/show_bug.cgi?id=596571
758 // TODO: handle possible transformation matrix. See
759 // https://bugzilla.gnome.org/show_bug.cgi?id=596326
761 // Get the video PAR and original size, if this fails the
762 // video-sink has likely not yet negotiated its caps.
763 int pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride;
764 IntSize originalSize;
765 GstVideoFormat format;
766 if (!getVideoSizeAndFormatFromCaps(caps.get(), originalSize, format, pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride))
769 LOG_MEDIA_MESSAGE("Original video size: %dx%d", originalSize.width(), originalSize.height());
770 LOG_MEDIA_MESSAGE("Pixel aspect ratio: %d/%d", pixelAspectRatioNumerator, pixelAspectRatioDenominator);
772 // Calculate DAR based on PAR and video size.
773 int displayWidth = originalSize.width() * pixelAspectRatioNumerator;
774 int displayHeight = originalSize.height() * pixelAspectRatioDenominator;
776 // Divide display width and height by their GCD to avoid possible overflows.
777 int displayAspectRatioGCD = greatestCommonDivisor(displayWidth, displayHeight);
778 displayWidth /= displayAspectRatioGCD;
779 displayHeight /= displayAspectRatioGCD;
781 // Apply DAR to original video size. This is the same behavior as in xvimagesink's setcaps function.
782 guint64 width = 0, height = 0;
783 if (!(originalSize.height() % displayHeight)) {
784 LOG_MEDIA_MESSAGE("Keeping video original height");
785 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
786 height = static_cast<guint64>(originalSize.height());
787 } else if (!(originalSize.width() % displayWidth)) {
788 LOG_MEDIA_MESSAGE("Keeping video original width");
789 height = gst_util_uint64_scale_int(originalSize.width(), displayHeight, displayWidth);
790 width = static_cast<guint64>(originalSize.width());
792 LOG_MEDIA_MESSAGE("Approximating while keeping original video height");
793 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
794 height = static_cast<guint64>(originalSize.height());
797 LOG_MEDIA_MESSAGE("Natural size: %" G_GUINT64_FORMAT "x%" G_GUINT64_FORMAT, width, height);
798 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE) && USE(ACCELERATED_VIDEO_VAAPI)
799 if (!m_displaySize.isEmpty())
800 m_videoSize = scaleHDVideoToDisplaySize(static_cast<int>(width), static_cast<int>(height), m_displaySize.width(), m_displaySize.height());
803 m_videoSize = IntSize(static_cast<int>(width), static_cast<int>(height));
807 void MediaPlayerPrivateGStreamer::videoChanged()
809 if (m_videoTimerHandler)
810 g_source_remove(m_videoTimerHandler);
811 m_videoTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVideoChangeTimeoutCallback), this);
814 void MediaPlayerPrivateGStreamer::notifyPlayerOfVideo()
816 m_videoTimerHandler = 0;
818 gint videoTracks = 0;
820 g_object_get(m_playBin.get(), "n-video", &videoTracks, NULL);
822 m_hasVideo = videoTracks > 0;
824 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
826 if (gst_video_get_size(m_videoSinkPad.get(), &width, &height)) {
827 IntSize size(width, height);
828 if (m_videoSize != size) {
829 m_videoSize = IntSize();
830 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
831 m_videoLayer->setOverlay(naturalSize());
836 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
837 #else // ENABLE(TIZEN_GSTREAMER_VIDEO)
838 m_videoSize = IntSize();
840 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
844 void MediaPlayerPrivateGStreamer::audioChanged()
846 if (m_audioTimerHandler)
847 g_source_remove(m_audioTimerHandler);
848 m_audioTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateAudioChangeTimeoutCallback), this);
851 void MediaPlayerPrivateGStreamer::notifyPlayerOfAudio()
853 m_audioTimerHandler = 0;
855 gint audioTracks = 0;
857 g_object_get(m_playBin.get(), "n-audio", &audioTracks, NULL);
858 m_hasAudio = audioTracks > 0;
859 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
862 void MediaPlayerPrivateGStreamer::setVolume(float volume)
867 gst_stream_volume_set_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC,
868 static_cast<double>(volume));
871 void MediaPlayerPrivateGStreamer::notifyPlayerOfVolumeChange()
873 m_volumeTimerHandler = 0;
875 if (!m_player || !m_playBin)
878 volume = gst_stream_volume_get_volume(GST_STREAM_VOLUME(m_playBin.get()), GST_STREAM_VOLUME_FORMAT_CUBIC);
879 // get_volume() can return values superior to 1.0 if the user
880 // applies software user gain via third party application (GNOME
881 // volume control for instance).
882 volume = CLAMP(volume, 0.0, 1.0);
883 m_player->volumeChanged(static_cast<float>(volume));
886 void MediaPlayerPrivateGStreamer::volumeChanged()
888 if (m_volumeTimerHandler)
889 g_source_remove(m_volumeTimerHandler);
890 m_volumeTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVolumeChangeTimeoutCallback), this);
893 void MediaPlayerPrivateGStreamer::setRate(float rate)
895 // Avoid useless playback rate update.
896 if (m_playbackRate == rate)
902 gst_element_get_state(m_playBin.get(), &state, &pending, 0);
903 if ((state != GST_STATE_PLAYING && state != GST_STATE_PAUSED)
904 || (pending == GST_STATE_PAUSED))
910 m_playbackRate = rate;
911 m_changingRate = true;
914 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
915 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
916 if (m_audioSessionManager)
917 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
922 float currentPosition = static_cast<float>(playbackPosition() * GST_SECOND);
923 GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH);
927 LOG_MEDIA_MESSAGE("Set Rate to %f", rate);
929 // Mute the sound if the playback rate is too extreme and
930 // audio pitch is not adjusted.
931 mute = (!m_preservesPitch && (rate < 0.8 || rate > 2));
932 start = currentPosition;
933 end = GST_CLOCK_TIME_NONE;
938 // If we are at beginning of media, start from the end to
939 // avoid immediate EOS.
940 if (currentPosition <= 0)
941 end = static_cast<gint64>(duration() * GST_SECOND);
943 end = currentPosition;
946 LOG_MEDIA_MESSAGE("Need to mute audio: %d", (int) mute);
948 if (!gst_element_seek(m_playBin.get(), rate, GST_FORMAT_TIME, flags,
949 GST_SEEK_TYPE_SET, start,
950 GST_SEEK_TYPE_SET, end))
951 LOG_MEDIA_MESSAGE("Set rate to %f failed", rate);
953 g_object_set(m_playBin.get(), "mute", mute, NULL);
956 void MediaPlayerPrivateGStreamer::setPreservesPitch(bool preservesPitch)
958 m_preservesPitch = preservesPitch;
961 MediaPlayer::NetworkState MediaPlayerPrivateGStreamer::networkState() const
963 return m_networkState;
966 MediaPlayer::ReadyState MediaPlayerPrivateGStreamer::readyState() const
971 PassRefPtr<TimeRanges> MediaPlayerPrivateGStreamer::buffered() const
973 RefPtr<TimeRanges> timeRanges = TimeRanges::create();
974 if (m_errorOccured || isLiveStream())
975 return timeRanges.release();
977 #if GST_CHECK_VERSION(0, 10, 31)
978 float mediaDuration(duration());
979 if (!mediaDuration || isinf(mediaDuration))
980 return timeRanges.release();
982 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
984 if (!gst_element_query(m_playBin.get(), query)) {
985 gst_query_unref(query);
986 return timeRanges.release();
989 gint64 rangeStart = 0, rangeStop = 0;
990 for (guint index = 0; index < gst_query_get_n_buffering_ranges(query); index++) {
991 if (gst_query_parse_nth_buffering_range(query, index, &rangeStart, &rangeStop))
992 timeRanges->add(static_cast<float>((rangeStart * mediaDuration) / 100),
993 static_cast<float>((rangeStop * mediaDuration) / 100));
996 // Fallback to the more general maxTimeLoaded() if no range has
998 if (!timeRanges->length())
999 if (float loaded = maxTimeLoaded())
1000 timeRanges->add(0, loaded);
1002 gst_query_unref(query);
1004 float loaded = maxTimeLoaded();
1005 if (!m_errorOccured && !isLiveStream() && loaded > 0)
1006 timeRanges->add(0, loaded);
1008 return timeRanges.release();
1011 gboolean MediaPlayerPrivateGStreamer::handleMessage(GstMessage* message)
1013 GOwnPtr<GError> err;
1014 GOwnPtr<gchar> debug;
1015 MediaPlayer::NetworkState error;
1016 bool issueError = true;
1017 bool attemptNextLocation = false;
1018 const GstStructure* structure = gst_message_get_structure(message);
1021 const gchar* messageTypeName = gst_structure_get_name(structure);
1023 // Redirect messages are sent from elements, like qtdemux, to
1024 // notify of the new location(s) of the media.
1025 if (!g_strcmp0(messageTypeName, "redirect")) {
1026 mediaLocationChanged(message);
1031 LOG_MEDIA_MESSAGE("Message received from element %s", GST_MESSAGE_SRC_NAME(message));
1032 switch (GST_MESSAGE_TYPE(message)) {
1033 case GST_MESSAGE_ERROR:
1034 if (m_resetPipeline)
1036 gst_message_parse_error(message, &err.outPtr(), &debug.outPtr());
1037 LOG_MEDIA_MESSAGE("Error %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1039 #if ENABLE(TIZEN_DLOG_SUPPORT)
1040 TIZEN_LOGE("GST_MESSAGE_ERROR %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
1043 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, "webkit-video.error");
1045 error = MediaPlayer::Empty;
1046 if (err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND
1047 || err->code == GST_STREAM_ERROR_WRONG_TYPE
1048 || err->code == GST_STREAM_ERROR_FAILED
1049 || err->code == GST_CORE_ERROR_MISSING_PLUGIN
1050 || err->code == GST_RESOURCE_ERROR_NOT_FOUND)
1051 error = MediaPlayer::FormatError;
1052 else if (err->domain == GST_STREAM_ERROR) {
1053 // Let the mediaPlayerClient handle the stream error, in
1054 // this case the HTMLMediaElement will emit a stalled
1056 #if !ENABLE(TIZEN_MEDIA_STREAM)
1057 if (err->code == GST_STREAM_ERROR_TYPE_NOT_FOUND) {
1058 LOG_MEDIA_MESSAGE("Decode error, let the Media element emit a stalled event.");
1062 error = MediaPlayer::DecodeError;
1063 attemptNextLocation = true;
1064 } else if (err->domain == GST_RESOURCE_ERROR)
1065 error = MediaPlayer::NetworkError;
1067 if (attemptNextLocation)
1068 issueError = !loadNextLocation();
1070 loadingFailed(error);
1072 case GST_MESSAGE_EOS:
1073 LOG_MEDIA_MESSAGE("End of Stream");
1076 case GST_MESSAGE_STATE_CHANGED:
1077 // Ignore state changes if load is delayed (preload=none). The
1078 // player state will be updated once commitLoad() is called.
1079 if (m_delayingLoad) {
1080 LOG_MEDIA_MESSAGE("Media load has been delayed. Ignoring state changes for now");
1084 // Ignore state changes from internal elements. They are
1085 // forwarded to playbin2 anyway.
1086 if (GST_MESSAGE_SRC(message) == reinterpret_cast<GstObject*>(m_playBin.get())) {
1089 // Construct a filename for the graphviz dot file output.
1090 GstState oldState, newState;
1091 gst_message_parse_state_changed(message, &oldState, &newState, 0);
1093 CString dotFileName = String::format("webkit-video.%s_%s",
1094 gst_element_state_get_name(oldState),
1095 gst_element_state_get_name(newState)).utf8();
1097 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, dotFileName.data());
1099 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1100 if (m_suspendTime > 0 && newState == GST_STATE_PAUSED) {
1101 if (!isLocalMediaStream())
1102 seek(m_suspendTime);
1104 m_player->mediaPlayerClient()->setSuspended(false);
1109 case GST_MESSAGE_BUFFERING:
1110 processBufferingStats(message);
1112 case GST_MESSAGE_DURATION:
1113 LOG_MEDIA_MESSAGE("Duration changed");
1117 LOG_MEDIA_MESSAGE("Unhandled GStreamer message type: %s",
1118 GST_MESSAGE_TYPE_NAME(message));
1124 void MediaPlayerPrivateGStreamer::processBufferingStats(GstMessage* message)
1126 // This is the immediate buffering that needs to happen so we have
1127 // enough to play right now.
1129 const GstStructure *structure = gst_message_get_structure(message);
1130 gst_structure_get_int(structure, "buffer-percent", &m_bufferingPercentage);
1132 LOG_MEDIA_MESSAGE("[Buffering] Buffering: %d%%.", m_bufferingPercentage);
1134 GstBufferingMode mode;
1135 gst_message_parse_buffering_stats(message, &mode, 0, 0, 0);
1136 if (mode != GST_BUFFERING_DOWNLOAD) {
1141 // This is on-disk buffering, that allows us to download much more
1142 // than needed for right now.
1143 if (!m_startedBuffering) {
1144 LOG_MEDIA_MESSAGE("[Buffering] Starting on-disk buffering.");
1146 m_startedBuffering = true;
1148 if (m_fillTimer.isActive())
1151 m_fillTimer.startRepeating(0.2);
1155 void MediaPlayerPrivateGStreamer::fillTimerFired(Timer<MediaPlayerPrivateGStreamer>*)
1157 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
1159 if (!gst_element_query(m_playBin.get(), query)) {
1160 gst_query_unref(query);
1165 gdouble fillStatus = 100.0;
1167 gst_query_parse_buffering_range(query, 0, &start, &stop, 0);
1168 gst_query_unref(query);
1171 fillStatus = 100.0 * stop / GST_FORMAT_PERCENT_MAX;
1173 LOG_MEDIA_MESSAGE("[Buffering] Download buffer filled up to %f%%", fillStatus);
1175 if (!m_mediaDuration)
1178 // Update maxTimeLoaded only if the media duration is
1179 // available. Otherwise we can't compute it.
1180 if (m_mediaDuration) {
1181 if (fillStatus == 100.0)
1182 m_maxTimeLoaded = m_mediaDuration;
1184 m_maxTimeLoaded = static_cast<float>((fillStatus * m_mediaDuration) / 100.0);
1185 LOG_MEDIA_MESSAGE("[Buffering] Updated maxTimeLoaded: %f", m_maxTimeLoaded);
1188 if (fillStatus != 100.0) {
1193 // Media is now fully loaded. It will play even if network
1194 // connection is cut. Buffering is done, remove the fill source
1195 // from the main loop.
1197 m_startedBuffering = false;
1201 float MediaPlayerPrivateGStreamer::maxTimeSeekable() const
1206 LOG_MEDIA_MESSAGE("maxTimeSeekable");
1207 // infinite duration means live stream
1208 if (isinf(duration()))
1214 float MediaPlayerPrivateGStreamer::maxTimeLoaded() const
1219 float loaded = m_maxTimeLoaded;
1220 if (!loaded && !m_fillTimer.isActive())
1221 loaded = duration();
1222 LOG_MEDIA_MESSAGE("maxTimeLoaded: %f", loaded);
1226 bool MediaPlayerPrivateGStreamer::didLoadingProgress() const
1228 if (!m_playBin || !m_mediaDuration || !totalBytes())
1230 float currentMaxTimeLoaded = maxTimeLoaded();
1231 bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
1232 m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
1233 LOG_MEDIA_MESSAGE("didLoadingProgress: %d", didLoadingProgress);
1234 return didLoadingProgress;
1237 unsigned MediaPlayerPrivateGStreamer::totalBytes() const
1242 if (m_totalBytes != -1)
1243 return m_totalBytes;
1248 GstFormat fmt = GST_FORMAT_BYTES;
1250 #ifdef GST_API_VERSION_1
1251 if (gst_element_query_duration(m_source.get(), fmt, &length)) {
1253 if (gst_element_query_duration(m_source.get(), &fmt, &length)) {
1255 LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1256 m_totalBytes = static_cast<unsigned>(length);
1257 m_isStreaming = !length;
1258 return m_totalBytes;
1261 // Fall back to querying the source pads manually.
1262 // See also https://bugzilla.gnome.org/show_bug.cgi?id=638749
1263 GstIterator* iter = gst_element_iterate_src_pads(m_source.get());
1266 #ifdef GST_API_VERSION_1
1267 GValue item = G_VALUE_INIT;
1268 switch (gst_iterator_next(iter, &item)) {
1269 case GST_ITERATOR_OK: {
1270 GstPad* pad = static_cast<GstPad*>(g_value_get_object(&item));
1271 gint64 padLength = 0;
1272 if (gst_pad_query_duration(pad, fmt, &padLength) && padLength > length)
1279 switch (gst_iterator_next(iter, &data)) {
1280 case GST_ITERATOR_OK: {
1281 GRefPtr<GstPad> pad = adoptGRef(GST_PAD_CAST(data));
1282 gint64 padLength = 0;
1283 if (gst_pad_query_duration(pad.get(), &fmt, &padLength) && padLength > length)
1288 case GST_ITERATOR_RESYNC:
1289 gst_iterator_resync(iter);
1291 case GST_ITERATOR_ERROR:
1293 case GST_ITERATOR_DONE:
1298 #ifdef GST_API_VERSION_1
1299 g_value_unset(&item);
1303 gst_iterator_free(iter);
1305 LOG_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1306 m_totalBytes = static_cast<unsigned>(length);
1307 m_isStreaming = !length;
1308 return m_totalBytes;
1311 unsigned MediaPlayerPrivateGStreamer::decodedFrameCount() const
1313 guint64 decodedFrames = 0;
1315 g_object_get(m_fpsSink, "frames-rendered", &decodedFrames, NULL);
1316 return static_cast<unsigned>(decodedFrames);
1319 unsigned MediaPlayerPrivateGStreamer::droppedFrameCount() const
1321 guint64 framesDropped = 0;
1323 g_object_get(m_fpsSink, "frames-dropped", &framesDropped, NULL);
1324 return static_cast<unsigned>(framesDropped);
1327 unsigned MediaPlayerPrivateGStreamer::audioDecodedByteCount() const
1329 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1330 gint64 position = 0;
1332 if (m_webkitAudioSink && gst_element_query(m_webkitAudioSink.get(), query))
1333 gst_query_parse_position(query, 0, &position);
1335 gst_query_unref(query);
1336 return static_cast<unsigned>(position);
1339 unsigned MediaPlayerPrivateGStreamer::videoDecodedByteCount() const
1341 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1342 gint64 position = 0;
1344 if (gst_element_query(m_webkitVideoSink, query))
1345 gst_query_parse_position(query, 0, &position);
1347 gst_query_unref(query);
1348 return static_cast<unsigned>(position);
1351 void MediaPlayerPrivateGStreamer::updateAudioSink()
1356 GstElement* sinkPtr = 0;
1358 g_object_get(m_playBin.get(), "audio-sink", &sinkPtr, NULL);
1359 m_webkitAudioSink = adoptGRef(sinkPtr);
1364 void MediaPlayerPrivateGStreamer::sourceChanged()
1366 GstElement* srcPtr = 0;
1368 g_object_get(m_playBin.get(), "source", &srcPtr, NULL);
1369 m_source = adoptGRef(srcPtr);
1371 if (WEBKIT_IS_WEB_SRC(m_source.get()))
1372 webKitWebSrcSetMediaPlayer(WEBKIT_WEB_SRC(m_source.get()), m_player);
1375 void MediaPlayerPrivateGStreamer::cancelLoad()
1377 if (m_networkState < MediaPlayer::Loading || m_networkState == MediaPlayer::Loaded)
1381 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1382 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1383 if (m_audioSessionManager)
1384 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
1388 void MediaPlayerPrivateGStreamer::updateStates()
1396 MediaPlayer::NetworkState oldNetworkState = m_networkState;
1397 MediaPlayer::ReadyState oldReadyState = m_readyState;
1401 GstStateChangeReturn ret = gst_element_get_state(m_playBin.get(),
1402 &state, &pending, 250 * GST_NSECOND);
1404 bool shouldUpdateAfterSeek = false;
1406 case GST_STATE_CHANGE_SUCCESS:
1407 LOG_MEDIA_MESSAGE("State: %s, pending: %s",
1408 gst_element_state_get_name(state),
1409 gst_element_state_get_name(pending));
1411 m_resetPipeline = state <= GST_STATE_READY;
1413 // Try to figure out ready and network states.
1414 if (state == GST_STATE_READY) {
1415 m_readyState = MediaPlayer::HaveMetadata;
1416 m_networkState = MediaPlayer::Empty;
1417 // Cache the duration without emiting the durationchange
1418 // event because it's taken care of by the media element
1419 // in this precise case.
1420 if (!m_isEndReached)
1422 } else if ((state == GST_STATE_NULL) || (maxTimeLoaded() == duration())) {
1423 m_networkState = MediaPlayer::Loaded;
1424 m_readyState = MediaPlayer::HaveEnoughData;
1426 m_readyState = currentTime() < maxTimeLoaded() ? MediaPlayer::HaveFutureData : MediaPlayer::HaveCurrentData;
1427 m_networkState = MediaPlayer::Loading;
1430 if (m_buffering && state != GST_STATE_READY) {
1431 m_readyState = MediaPlayer::HaveCurrentData;
1432 m_networkState = MediaPlayer::Loading;
1435 // Now let's try to get the states in more detail using
1436 // information from GStreamer, while we sync states where
1438 if (state == GST_STATE_PAUSED) {
1439 if (!m_webkitAudioSink)
1442 if (!m_volumeAndMuteInitialized) {
1443 notifyPlayerOfVolumeChange();
1444 notifyPlayerOfMute();
1445 m_volumeAndMuteInitialized = true;
1448 if (m_buffering && m_bufferingPercentage == 100) {
1449 m_buffering = false;
1450 m_bufferingPercentage = 0;
1451 m_readyState = MediaPlayer::HaveEnoughData;
1453 LOG_MEDIA_MESSAGE("[Buffering] Complete.");
1456 LOG_MEDIA_MESSAGE("[Buffering] Restarting playback.");
1457 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1458 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1459 if (m_audioSessionManager)
1460 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1463 } else if (!m_buffering && (currentTime() < duration())) {
1466 } else if (state == GST_STATE_PLAYING) {
1467 m_readyState = MediaPlayer::HaveEnoughData;
1470 if (m_buffering && !isLiveStream()) {
1471 m_readyState = MediaPlayer::HaveCurrentData;
1472 m_networkState = MediaPlayer::Loading;
1474 LOG_MEDIA_MESSAGE("[Buffering] Pausing stream for buffering.");
1476 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1477 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1478 if (m_audioSessionManager)
1479 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1485 // Is on-disk buffering in progress?
1486 if (m_fillTimer.isActive())
1487 m_networkState = MediaPlayer::Loading;
1489 if (m_changingRate) {
1490 m_player->rateChanged();
1491 m_changingRate = false;
1495 shouldUpdateAfterSeek = true;
1500 case GST_STATE_CHANGE_ASYNC:
1501 LOG_MEDIA_MESSAGE("Async: State: %s, pending: %s",
1502 gst_element_state_get_name(state),
1503 gst_element_state_get_name(pending));
1504 // Change in progress
1506 // On-disk buffering was attempted but the media is live. This
1507 // can't work so disable on-disk buffering and reset the
1510 #if ENABLE(TIZEN_MEDIA_STREAM)
1511 if (state == GST_STATE_READY && isLiveStream() && m_preload == MediaPlayer::Auto && !isLocalMediaStream()) {
1513 if (state == GST_STATE_READY && isLiveStream() && m_preload == MediaPlayer::Auto) {
1515 setPreload(MediaPlayer::None);
1516 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1517 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1518 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1519 if (m_audioSessionManager)
1520 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1524 // A live stream was paused, reset the pipeline.
1525 #if ENABLE(TIZEN_MEDIA_STREAM)
1526 if (state == GST_STATE_PAUSED && pending == GST_STATE_PLAYING && isLiveStream() && !isLocalMediaStream()) {
1528 if (state == GST_STATE_PAUSED && pending == GST_STATE_PLAYING && isLiveStream()) {
1530 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1531 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1532 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1533 if (m_audioSessionManager)
1534 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1538 if (!isLiveStream() && !m_buffering)
1542 shouldUpdateAfterSeek = true;
1546 case GST_STATE_CHANGE_FAILURE:
1547 LOG_MEDIA_MESSAGE("Failure: State: %s, pending: %s",
1548 gst_element_state_get_name(state),
1549 gst_element_state_get_name(pending));
1552 case GST_STATE_CHANGE_NO_PREROLL:
1553 LOG_MEDIA_MESSAGE("No preroll: State: %s, pending: %s",
1554 gst_element_state_get_name(state),
1555 gst_element_state_get_name(pending));
1557 if (state == GST_STATE_READY)
1558 m_readyState = MediaPlayer::HaveNothing;
1559 else if (state == GST_STATE_PAUSED) {
1560 m_readyState = MediaPlayer::HaveEnoughData;
1562 // Live pipelines go in PAUSED without prerolling.
1563 m_isStreaming = true;
1564 } else if (state == GST_STATE_PLAYING)
1568 shouldUpdateAfterSeek = true;
1571 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1572 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1573 if (m_audioSessionManager)
1574 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1577 } else if (!m_paused) {
1578 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1579 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1580 if (m_audioSessionManager)
1581 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1585 m_networkState = MediaPlayer::Loading;
1588 LOG_MEDIA_MESSAGE("Else : %d", ret);
1593 m_readyState = MediaPlayer::HaveNothing;
1595 if (shouldUpdateAfterSeek)
1598 if (m_networkState != oldNetworkState) {
1599 LOG_MEDIA_MESSAGE("Network State Changed from %u to %u",
1600 oldNetworkState, m_networkState);
1601 m_player->networkStateChanged();
1603 if (m_readyState != oldReadyState) {
1604 LOG_MEDIA_MESSAGE("Ready State Changed from %u to %u",
1605 oldReadyState, m_readyState);
1606 m_player->readyStateChanged();
1607 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1608 if (state == GST_STATE_PLAYING)
1609 m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
1614 void MediaPlayerPrivateGStreamer::mediaLocationChanged(GstMessage* message)
1616 if (m_mediaLocations)
1617 gst_structure_free(m_mediaLocations);
1619 const GstStructure* structure = gst_message_get_structure(message);
1621 // This structure can contain:
1622 // - both a new-location string and embedded locations structure
1623 // - or only a new-location string.
1624 m_mediaLocations = gst_structure_copy(structure);
1625 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1628 m_mediaLocationCurrentIndex = static_cast<int>(gst_value_list_get_size(locations)) -1;
1634 bool MediaPlayerPrivateGStreamer::loadNextLocation()
1636 if (!m_mediaLocations)
1639 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1640 const gchar* newLocation = 0;
1643 // Fallback on new-location string.
1644 newLocation = gst_structure_get_string(m_mediaLocations, "new-location");
1650 if (m_mediaLocationCurrentIndex < 0) {
1651 m_mediaLocations = 0;
1655 const GValue* location = gst_value_list_get_value(locations,
1656 m_mediaLocationCurrentIndex);
1657 const GstStructure* structure = gst_value_get_structure(location);
1660 m_mediaLocationCurrentIndex--;
1664 newLocation = gst_structure_get_string(structure, "new-location");
1668 // Found a candidate. new-location is not always an absolute url
1669 // though. We need to take the base of the current url and
1670 // append the value of new-location to it.
1672 gchar* currentLocation = 0;
1673 g_object_get(m_playBin.get(), "uri", ¤tLocation, NULL);
1675 KURL currentUrl(KURL(), currentLocation);
1676 g_free(currentLocation);
1680 if (gst_uri_is_valid(newLocation))
1681 newUrl = KURL(KURL(), newLocation);
1683 newUrl = KURL(KURL(), currentUrl.baseAsString() + newLocation);
1685 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(currentUrl);
1686 if (securityOrigin->canRequest(newUrl)) {
1687 LOG_MEDIA_MESSAGE("New media url: %s", newUrl.string().utf8().data());
1689 // Reset player states.
1690 m_networkState = MediaPlayer::Loading;
1691 m_player->networkStateChanged();
1692 m_readyState = MediaPlayer::HaveNothing;
1693 m_player->readyStateChanged();
1695 // Reset pipeline state.
1696 m_resetPipeline = true;
1697 gst_element_set_state(m_playBin.get(), GST_STATE_READY);
1698 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1699 if (m_audioSessionManager)
1700 m_audioSessionManager->setSoundState(ASM_STATE_NONE);
1703 gst_element_get_state(m_playBin.get(), &state, 0, 0);
1704 if (state <= GST_STATE_READY) {
1705 // Set the new uri and start playing.
1706 g_object_set(m_playBin.get(), "uri", newUrl.string().utf8().data(), NULL);
1707 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
1708 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1709 if (m_audioSessionManager)
1710 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1716 m_mediaLocationCurrentIndex--;
1721 void MediaPlayerPrivateGStreamer::loadStateChanged()
1726 void MediaPlayerPrivateGStreamer::sizeChanged()
1731 void MediaPlayerPrivateGStreamer::timeChanged()
1734 m_player->timeChanged();
1737 void MediaPlayerPrivateGStreamer::didEnd()
1739 // Synchronize position and duration values to not confuse the
1740 // HTMLMediaElement. In some cases like reverse playback the
1741 // position is not always reported as 0 for instance.
1742 float now = currentTime();
1743 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1744 if (now > 0 && now != duration()) {
1746 if (now > 0 && now <= duration() && m_mediaDuration != now) {
1748 m_mediaDurationKnown = true;
1749 m_mediaDuration = now;
1750 m_player->durationChanged();
1753 m_isEndReached = true;
1756 if (!m_player->mediaPlayerClient()->mediaPlayerIsLooping()) {
1758 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1759 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1760 if (m_audioSessionManager)
1761 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1763 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1766 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1767 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
1768 if (element->isVideo())
1769 power_unlock_state(POWER_STATE_NORMAL);
1774 void MediaPlayerPrivateGStreamer::cacheDuration()
1776 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1777 float previousDuration = m_mediaDuration;
1779 // Reset cached media duration
1780 m_mediaDuration = 0;
1782 // And re-cache it if possible.
1784 gst_element_get_state(m_playBin.get(), &state, 0, 0);
1785 float newDuration = duration();
1787 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1788 if (state > GST_STATE_READY) {
1789 // Don't set m_mediaDurationKnown yet if the pipeline is not
1790 // paused. This allows duration() query to fail at least once
1791 // before playback starts and duration becomes known.
1792 m_mediaDurationKnown = !isinf(newDuration);
1795 if (!isinf(newDuration))
1796 m_mediaDuration = newDuration;
1798 m_mediaDuration = previousDuration;
1800 if (state <= GST_STATE_READY) {
1801 // Don't set m_mediaDurationKnown yet if the pipeline is not
1802 // paused. This allows duration() query to fail at least once
1803 // before playback starts and duration becomes known.
1804 if (!isinf(newDuration))
1805 m_mediaDuration = newDuration;
1807 m_mediaDurationKnown = !isinf(newDuration);
1808 if (m_mediaDurationKnown)
1809 m_mediaDuration = newDuration;
1812 if (!isinf(newDuration))
1813 m_mediaDuration = newDuration;
1817 void MediaPlayerPrivateGStreamer::durationChanged()
1819 float previousDuration = m_mediaDuration;
1822 // Avoid emiting durationchanged in the case where the previous
1823 // duration was 0 because that case is already handled by the
1824 // HTMLMediaElement.
1825 if (previousDuration && m_mediaDuration != previousDuration)
1826 m_player->durationChanged();
1828 if (m_preload == MediaPlayer::None && m_originalPreloadWasAutoAndWasOverridden) {
1830 if (totalBytes() && !isLiveStream()) {
1831 setPreload(MediaPlayer::Auto);
1832 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1833 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
1834 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1835 if (m_audioSessionManager)
1836 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1842 bool MediaPlayerPrivateGStreamer::supportsMuting() const
1847 void MediaPlayerPrivateGStreamer::setMuted(bool muted)
1852 g_object_set(m_playBin.get(), "mute", muted, NULL);
1855 void MediaPlayerPrivateGStreamer::notifyPlayerOfMute()
1857 m_muteTimerHandler = 0;
1859 if (!m_player || !m_playBin)
1863 g_object_get(m_playBin.get(), "mute", &muted, NULL);
1864 m_player->muteChanged(static_cast<bool>(muted));
1867 void MediaPlayerPrivateGStreamer::muteChanged()
1869 if (m_muteTimerHandler)
1870 g_source_remove(m_muteTimerHandler);
1871 m_muteTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateMuteChangeTimeoutCallback), this);
1874 void MediaPlayerPrivateGStreamer::loadingFailed(MediaPlayer::NetworkState error)
1876 #if ENABLE(TIZEN_DLOG_SUPPORT)
1877 TIZEN_LOGE("NetworkState : %d", error);
1880 m_errorOccured = true;
1881 if (m_networkState != error) {
1882 m_networkState = error;
1883 m_player->networkStateChanged();
1885 if (m_readyState != MediaPlayer::HaveNothing) {
1886 m_readyState = MediaPlayer::HaveNothing;
1887 m_player->readyStateChanged();
1891 void MediaPlayerPrivateGStreamer::setSize(const IntSize& size)
1896 void MediaPlayerPrivateGStreamer::setVisible(bool visible)
1900 void MediaPlayerPrivateGStreamer::triggerRepaint(GstBuffer* buffer)
1902 g_return_if_fail(GST_IS_BUFFER(buffer));
1903 gst_buffer_replace(&m_buffer, buffer);
1904 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1905 #if !ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1906 if (m_videoSize.isEmpty())
1907 m_videoSize = naturalSize();
1908 m_videoLayer->paintVideoLayer(m_videoSize);
1912 m_player->repaint();
1915 void MediaPlayerPrivateGStreamer::paint(GraphicsContext* context, const IntRect& rect)
1917 if (context->paintingDisabled())
1920 if (!m_player->visible())
1926 GRefPtr<GstCaps> caps = webkitGstGetPadCaps(m_videoSinkPad.get());
1930 RefPtr<ImageGStreamer> gstImage = ImageGStreamer::createImage(m_buffer, caps.get());
1934 context->drawImage(reinterpret_cast<Image*>(gstImage->image().get()), ColorSpaceSRGB,
1935 rect, gstImage->rect(), CompositeCopy, DoNotRespectImageOrientation, false);
1938 static HashSet<String> mimeTypeCache()
1940 initializeGStreamerAndRegisterWebKitElements();
1942 DEFINE_STATIC_LOCAL(HashSet<String>, cache, ());
1943 static bool typeListInitialized = false;
1945 if (typeListInitialized)
1947 const char* mimeTypes[] = {
1949 "application/vnd.apple.mpegurl",
1950 "application/vnd.rn-realmedia",
1951 "application/x-3gp",
1952 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1953 "application/x-mpegurl",
1954 "application/x-mpegURL",
1956 "application/x-pn-realaudio",
1976 "audio/x-amr-nb-sh",
1977 "audio/x-amr-wb-sh",
2008 "audio/x-vorbis+ogg",
2012 "audio/x-wavpack-correction",
2021 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2041 for (unsigned i = 0; i < (sizeof(mimeTypes) / sizeof(*mimeTypes)); ++i)
2042 cache.add(String(mimeTypes[i]));
2044 typeListInitialized = true;
2048 void MediaPlayerPrivateGStreamer::getSupportedTypes(HashSet<String>& types)
2050 types = mimeTypeCache();
2053 MediaPlayer::SupportsType MediaPlayerPrivateGStreamer::supportsType(const String& type, const String& codecs, const KURL&)
2055 if (type.isNull() || type.isEmpty())
2056 return MediaPlayer::IsNotSupported;
2058 // spec says we should not return "probably" if the codecs string is empty
2059 if (mimeTypeCache().contains(type))
2060 return codecs.isEmpty() ? MediaPlayer::MayBeSupported : MediaPlayer::IsSupported;
2061 return MediaPlayer::IsNotSupported;
2064 bool MediaPlayerPrivateGStreamer::hasSingleSecurityOrigin() const
2069 bool MediaPlayerPrivateGStreamer::supportsFullscreen() const
2071 #if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
2072 // See <rdar://problem/7389945>
2079 PlatformMedia MediaPlayerPrivateGStreamer::platformMedia() const
2082 #ifndef GST_API_VERSION_1
2083 p.type = PlatformMedia::GStreamerGWorldType;
2084 p.media.gstreamerGWorld = m_gstGWorld.get();
2089 MediaPlayer::MovieLoadType MediaPlayerPrivateGStreamer::movieLoadType() const
2091 if (m_readyState == MediaPlayer::HaveNothing)
2092 return MediaPlayer::Unknown;
2095 return MediaPlayer::LiveStream;
2097 return MediaPlayer::Download;
2100 void MediaPlayerPrivateGStreamer::setDownloadBuffering()
2107 g_object_get(m_playBin.get(), "flags", &flags, NULL);
2108 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2109 flags = (GstPlayFlags)(flags | GST_PLAY_FLAG_NATIVE_VIDEO);
2111 if (m_preload == MediaPlayer::Auto) {
2112 LOG_MEDIA_MESSAGE("Enabling on-disk buffering");
2113 g_object_set(m_playBin.get(), "flags", flags | GST_PLAY_FLAG_DOWNLOAD, NULL);
2115 LOG_MEDIA_MESSAGE("Disabling on-disk buffering");
2116 g_object_set(m_playBin.get(), "flags", flags & ~GST_PLAY_FLAG_DOWNLOAD, NULL);
2120 void MediaPlayerPrivateGStreamer::setPreload(MediaPlayer::Preload preload)
2122 m_originalPreloadWasAutoAndWasOverridden = m_preload != preload && m_preload == MediaPlayer::Auto;
2124 m_preload = preload;
2126 setDownloadBuffering();
2128 if (m_delayingLoad && m_preload != MediaPlayer::None) {
2129 m_delayingLoad = false;
2134 void MediaPlayerPrivateGStreamer::createAudioSink()
2136 // Construct audio sink if pitch preserving is enabled.
2137 if (!m_preservesPitch)
2143 GstElement* scale = gst_element_factory_make("scaletempo", 0);
2145 GST_WARNING("Failed to create scaletempo");
2149 GstElement* convert = gst_element_factory_make("audioconvert", 0);
2150 GstElement* resample = gst_element_factory_make("audioresample", 0);
2151 GstElement* sink = gst_element_factory_make("autoaudiosink", 0);
2153 GstElement* audioSink = gst_bin_new("audio-sink");
2154 gst_bin_add_many(GST_BIN(audioSink), scale, convert, resample, sink, NULL);
2156 if (!gst_element_link_many(scale, convert, resample, sink, NULL)) {
2157 GST_WARNING("Failed to link audio sink elements");
2158 gst_object_unref(audioSink);
2162 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(scale, "sink"));
2163 gst_element_add_pad(audioSink, gst_ghost_pad_new("sink", pad.get()));
2165 g_object_set(m_playBin.get(), "audio-sink", audioSink, NULL);
2168 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2169 GstElement* MediaPlayerPrivateGStreamer::createVideoSink()
2171 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2172 m_webkitVideoSink = m_videoLayer->createVideoSink();
2173 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2175 // Primary video should be OFF and Secondary video should be FULL SCREEN mode
2176 g_object_set(m_webkitVideoSink, "display-mode", 2, NULL);
2177 #else // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2178 #ifndef GST_API_VERSION_1
2179 m_webkitVideoSink = webkitVideoSinkNew(m_gstGWorld.get());
2181 m_webkitVideoSink = webkitVideoSinkNew();
2183 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2184 g_signal_connect(m_webkitVideoSink, "repaint-requested", G_CALLBACK(mediaPlayerPrivateRepaintCallback), this);
2185 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2187 #ifndef GST_API_VERSION_1
2188 m_videoSinkBin = gst_bin_new("video-sink");
2189 GstElement* videoTee = gst_element_factory_make("tee", "videoTee");
2190 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2191 GstElement* queue = gst_element_factory_make("queue", 0);
2194 gst_object_ref_sink(m_videoSinkBin);
2196 // Build a new video sink consisting of a bin containing a tee
2197 // (meant to distribute data to multiple video sinks) and our
2198 // internal video sink. For fullscreen we create an autovideosink
2199 // and initially block the data flow towards it and configure it
2200 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2201 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, queue, NULL);
2203 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, NULL);
2206 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
2207 // Link a new src pad from tee to queue1.
2208 gst_element_link_pads_full(videoTee, 0, queue, "sink", GST_PAD_LINK_CHECK_NOTHING);
2212 GstElement* actualVideoSink = 0;
2213 m_fpsSink = gst_element_factory_make("fpsdisplaysink", "sink");
2215 // The verbose property has been added in -bad 0.10.22. Making
2216 // this whole code depend on it because we don't want
2217 // fpsdiplaysink to spit data on stdout.
2218 GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(m_fpsSink)->elementfactory);
2219 if (gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 22)) {
2220 g_object_set(m_fpsSink, "silent", TRUE , NULL);
2222 // Turn off text overlay unless logging is enabled.
2224 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2226 WTFLogChannel* channel = getChannelFromName("Media");
2227 if (channel->state != WTFLogChannelOn)
2228 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2229 #endif // LOG_DISABLED
2231 if (g_object_class_find_property(G_OBJECT_GET_CLASS(m_fpsSink), "video-sink")) {
2232 g_object_set(m_fpsSink, "video-sink", m_webkitVideoSink, NULL);
2233 #ifndef GST_API_VERSION_1
2234 gst_bin_add(GST_BIN(m_videoSinkBin), m_fpsSink);
2236 actualVideoSink = m_fpsSink;
2244 #ifndef GST_API_VERSION_1
2245 gst_bin_add(GST_BIN(m_videoSinkBin), m_webkitVideoSink);
2247 actualVideoSink = m_webkitVideoSink;
2250 ASSERT(actualVideoSink);
2252 #ifndef GST_API_VERSION_1
2253 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2254 // Link a new src pad from tee to queue1.
2255 GRefPtr<GstPad> srcPad = adoptGRef(gst_element_get_request_pad(videoTee, "src%d"));
2256 GRefPtr<GstPad> sinkPad = adoptGRef(gst_element_get_static_pad(actualVideoSink, "sink"));
2257 gst_pad_link(srcPad.get(), sinkPad.get());
2259 // Faster elements linking.
2260 gst_element_link_pads_full(queue, "src", actualVideoSink, "sink", GST_PAD_LINK_CHECK_NOTHING);
2262 // Add a ghostpad to the bin so it can proxy to tee.
2263 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(videoTee, "sink"));
2264 gst_element_add_pad(m_videoSinkBin, gst_ghost_pad_new("sink", pad.get()));
2266 // Set the bin as video sink of playbin.
2267 return m_videoSinkBin;
2269 return actualVideoSink;
2274 void MediaPlayerPrivateGStreamer::createGSTPlayBin()
2278 // gst_element_factory_make() returns a floating reference so
2279 // we should not adopt.
2280 m_playBin = gst_element_factory_make(gPlaybinName, "play");
2282 #ifndef GST_API_VERSION_1
2283 m_gstGWorld = GStreamerGWorld::createGWorld(m_playBin.get());
2286 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
2287 gst_bus_add_signal_watch(bus.get());
2288 g_signal_connect(bus.get(), "message", G_CALLBACK(mediaPlayerPrivateMessageCallback), this);
2289 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2290 gst_bus_set_sync_handler(bus.get(), GstBusSyncHandler(mediaPlayerPrivateSyncHandler), this);
2292 gst_object_unref(bus.get());
2294 g_object_set(m_playBin.get(), "mute", m_player->muted(), NULL);
2296 g_signal_connect(m_playBin.get(), "notify::volume", G_CALLBACK(mediaPlayerPrivateVolumeChangedCallback), this);
2297 g_signal_connect(m_playBin.get(), "notify::source", G_CALLBACK(mediaPlayerPrivateSourceChangedCallback), this);
2298 g_signal_connect(m_playBin.get(), "notify::mute", G_CALLBACK(mediaPlayerPrivateMuteChangedCallback), this);
2299 g_signal_connect(m_playBin.get(), "video-changed", G_CALLBACK(mediaPlayerPrivateVideoChangedCallback), this);
2300 g_signal_connect(m_playBin.get(), "audio-changed", G_CALLBACK(mediaPlayerPrivateAudioChangedCallback), this);
2301 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2302 g_signal_connect(m_playBin.get(), "source-setup", G_CALLBACK(mediaPlayerPrivateSourceSetupCallback), this);
2305 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2306 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player()->mediaPlayerClient());
2307 if (element->isVideo()) {
2308 GstElement* videoElement = createVideoSink();
2309 g_object_set(m_playBin.get(), "video-sink", videoElement, NULL);
2311 GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2313 g_signal_connect(videoSinkPad.get(), "notify::caps", G_CALLBACK(mediaPlayerPrivateVideoSinkCapsChangedCallback), this);
2315 GstElement* fakeSink = gst_element_factory_make("fakesink", 0);
2316 g_object_set(fakeSink, "sync", true, NULL);
2317 g_object_set(m_playBin.get(), "video-sink", fakeSink, NULL);
2320 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2321 GstElement* realSink = gst_element_factory_make("avsysaudiosink", 0);
2322 g_object_set(realSink, "close-handle-on-prepare", 1, NULL);
2323 g_object_set(m_playBin.get(), "audio-sink", realSink, NULL);
2325 if (m_audioSessionManager)
2326 m_audioSessionManager->registerAudioSessionManager(MM_SESSION_TYPE_SHARE, mediaPlayerPrivateAudioSessionNotifyCallback, player());
2332 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2333 bool MediaPlayerPrivateGStreamer::supportsAcceleratedRendering() const
2335 bool isEmbedVideo = false;
2336 if (m_player->mediaPlayerClient()) {
2337 Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
2338 if (document && document->settings()) {
2339 isEmbedVideo = document->settings()->acceleratedCompositingForVideoEnabled()
2340 && document->settings()->acceleratedCompositingEnabled();
2341 LOG_MEDIA_MESSAGE("isEmbedVideo: %d", isEmbedVideo);
2345 return isEmbedVideo;
2348 PlatformLayer* MediaPlayerPrivateGStreamer::platformLayer() const
2350 return m_videoLayer->platformLayer();
2353 #if ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2354 void MediaPlayerPrivateGStreamer::paintCurrentFrameInContext(GraphicsContext* context, const IntRect& rect)
2356 m_videoLayer->paintCurrentFrameInContext(context, rect);
2359 #if USE(ACCELERATED_VIDEO_VAAPI)
2360 // Other device doesn't prefer such optimization, so enclose it in USE(ACCELERATED_VIDEO_VAAPI) macro
2361 IntSize MediaPlayerPrivateGStreamer::scaleHDVideoToDisplaySize(int videoWidth, int videoHeight, int displayWidth, int displayHeight) const
2363 int fitWidth, fitHeight;
2365 #if ENABLE(TIZEN_DLOG_SUPPORT)
2366 TIZEN_LOGI("videoWidth: %d, videoHeight: %d, displayWidth: %d, displayHeight: %d ", videoWidth, videoHeight, displayWidth, displayHeight);
2368 fitWidth = videoWidth;
2369 fitHeight = videoHeight;
2370 if (displayWidth > 0 && displayHeight > 0) {
2371 // In case video is rotated, we always use a 'better'
2372 // orientation (landscape or portrait) to calculate fitWidth/fitHeight.
2373 // It means we use a bigger size which doesn't lose quality
2374 // in either landscape or portrait orientation
2375 if ((videoWidth > videoHeight && displayWidth < displayHeight)
2376 || (videoWidth < videoHeight && displayWidth > displayHeight)) {
2379 displayWidth = displayHeight;
2380 displayHeight = tmp;
2383 if (videoWidth > displayWidth || videoHeight > displayHeight) {
2384 if (videoWidth * displayHeight > videoHeight * displayWidth) {
2385 fitWidth = displayWidth;
2386 fitHeight = videoHeight * displayWidth / videoWidth;
2387 ASSERT(fitHeight <= displayHeight);
2389 fitWidth = videoWidth * displayHeight / videoHeight;
2390 fitHeight = displayHeight;
2391 ASSERT(fitWidth <= displayWidth);
2396 return IntSize(fitWidth, fitHeight);
2399 void MediaPlayerPrivateGStreamer::xWindowIdPrepared(GstMessage* message)
2401 // It is called in streaming thread.
2402 // It should be used only to set window handle to video sink.
2404 int videoWidth, videoHeight;
2405 gst_structure_get_int(message->structure, "video-width", &videoWidth);
2406 gst_structure_get_int(message->structure, "video-height", &videoHeight);
2408 #if ENABLE(TIZEN_DLOG_SUPPORT)
2409 TIZEN_LOGI("videoWidth: %d, videoHeight: %d", videoWidth, videoHeight);
2412 #if USE(ACCELERATED_VIDEO_VAAPI)
2413 int displayWidth, displayHeight;
2414 gst_structure_get_int(message->structure, "display-width", &displayWidth);
2415 gst_structure_get_int(message->structure, "display-height", &displayHeight);
2417 m_displaySize = IntSize(displayWidth, displayHeight);
2418 m_videoSize = scaleHDVideoToDisplaySize(videoWidth, videoHeight, displayWidth, displayHeight);
2420 m_videoSize = IntSize(videoWidth, videoHeight);
2422 m_videoLayer->setOverlay(m_videoSize);
2425 #endif // ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2426 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2428 #if ENABLE(TIZEN_WEBKIT2_PROXY)
2429 void MediaPlayerPrivateGStreamer::setProxy(GstElement* source)
2431 SoupSession* session = WebCore::ResourceHandle::defaultSession();
2435 SoupURI* proxyUri = 0;
2436 g_object_get(session, SOUP_SESSION_PROXY_URI, &proxyUri, NULL);
2440 char* proxy = soup_uri_to_string(proxyUri, false);
2441 g_object_set(source, "proxy", proxy, NULL);
2443 soup_uri_free(proxyUri);
2448 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2449 void MediaPlayerPrivateGStreamer::suspend()
2451 m_suspendTime = currentTime();
2452 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
2453 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2454 if (m_audioSessionManager)
2455 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
2459 void MediaPlayerPrivateGStreamer::resume()
2461 if (isLocalMediaStream()) {
2462 gst_element_set_state(m_playBin.get(), GST_STATE_PLAYING);
2463 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2464 if (m_audioSessionManager)
2465 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
2468 gst_element_set_state(m_playBin.get(), GST_STATE_PAUSED);
2469 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2470 if (m_audioSessionManager)
2471 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
2476 bool MediaPlayerPrivateGStreamer::isLocalMediaStream()
2478 if (m_url.string().contains("camera://"))
2483 #endif // ENABLE(TIZEN_GSTREAMER_VIDEO)
2487 #endif // USE(GSTREAMER)