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"
35 #include "FrameView.h"
36 #include "GStreamerGWorld.h"
37 #include "GStreamerUtilities.h"
38 #include "GStreamerVersioning.h"
39 #include "GraphicsContext.h"
40 #include "GraphicsTypes.h"
41 #if ENABLE(TIZEN_MEDIA_STREAM)
42 #include "HTMLMediaElement.h"
44 #include "ImageGStreamer.h"
45 #include "ImageOrientation.h"
48 #include "MIMETypeRegistry.h"
49 #include "MediaPlayer.h"
50 #include "NotImplemented.h"
51 #include "SecurityOrigin.h"
52 #include "TimeRanges.h"
53 #include "VideoSinkGStreamer.h"
54 #include "WebKitWebSourceGStreamer.h"
56 #include <gst/video/video.h>
59 #include <wtf/gobject/GOwnPtr.h>
60 #include <wtf/text/CString.h>
62 #ifdef GST_API_VERSION_1
63 #include <gst/audio/streamvolume.h>
65 #include <gst/interfaces/streamvolume.h>
68 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
71 #include "VideoLayerTizen.h"
72 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
74 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
76 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
78 #if ENABLE(TIZEN_MEDIA_STREAM)
79 #include "WebKitCameraSourceGStreamer.h"
80 #endif // ENABLE(TIZEN_MEDIA_STREAM)
82 // GstPlayFlags flags from playbin2. It is the policy of GStreamer to
83 // not publicly expose element-specific enums. That's why this
84 // GstPlayFlags enum has been copied here.
86 GST_PLAY_FLAG_VIDEO = 0x00000001,
87 GST_PLAY_FLAG_AUDIO = 0x00000002,
88 GST_PLAY_FLAG_TEXT = 0x00000004,
89 GST_PLAY_FLAG_VIS = 0x00000008,
90 GST_PLAY_FLAG_SOFT_VOLUME = 0x00000010,
91 GST_PLAY_FLAG_NATIVE_AUDIO = 0x00000020,
92 GST_PLAY_FLAG_NATIVE_VIDEO = 0x00000040,
93 GST_PLAY_FLAG_DOWNLOAD = 0x00000080,
94 GST_PLAY_FLAG_BUFFERING = 0x000000100
97 #ifdef GST_API_VERSION_1
98 static const char* gPlaybinName = "playbin";
100 static const char* gPlaybinName = "playbin2";
107 static int greatestCommonDivisor(int a, int b)
118 static gboolean mediaPlayerPrivateMessageCallback(GstBus*, GstMessage* message, MediaPlayerPrivateGStreamer* player)
120 return player->handleMessage(message);
123 static void mediaPlayerPrivateSourceChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
125 player->sourceChanged();
128 static void mediaPlayerPrivateVolumeChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
130 // This is called when playbin receives the notify::volume signal.
131 player->volumeChanged();
134 static gboolean mediaPlayerPrivateVolumeChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
136 // This is the callback of the timeout source created in ::volumeChanged.
137 player->notifyPlayerOfVolumeChange();
141 static void mediaPlayerPrivateMuteChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
143 // This is called when playbin receives the notify::mute signal.
144 player->muteChanged();
147 static gboolean mediaPlayerPrivateMuteChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
149 // This is the callback of the timeout source created in ::muteChanged.
150 player->notifyPlayerOfMute();
154 static void mediaPlayerPrivateVideoSinkCapsChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
156 player->videoChanged();
159 static void mediaPlayerPrivateVideoChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
161 player->videoChanged();
164 static void mediaPlayerPrivateAudioChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
166 player->audioChanged();
169 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
170 static void mediaPlayerPrivateSourceSetupCallback(GObject*, GstElement* source, MediaPlayerPrivateGStreamer* player)
172 HTMLMediaElement* element = static_cast<HTMLMediaElement*>(player->player()->mediaPlayerClient());
174 // Grab the current document
175 Document* document = element->document();
177 document = element->ownerDocument();
179 // Grab the frame and network manager
180 Frame* frame = document ? document->frame() : 0;
181 FrameLoader* frameLoader = frame ? frame->loader() : 0;
183 String cookie = cookies(document, player->url());
184 GstStructure* headers = gst_structure_new("extra-headers", "Cookie", G_TYPE_STRING, cookie.utf8().data(), NULL);
185 g_object_set(source, "extra-headers", headers, NULL);
186 gst_structure_free(headers);
188 #if ENABLE(TIZEN_WEBKIT2_PROXY)
189 player->setProxy(source);
193 g_object_set(source, "user-agent", frameLoader->userAgent(player->url()).utf8().data(), NULL);
197 static gboolean mediaPlayerPrivateAudioChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
199 // This is the callback of the timeout source created in ::audioChanged.
200 player->notifyPlayerOfAudio();
204 static gboolean mediaPlayerPrivateVideoChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
206 // This is the callback of the timeout source created in ::videoChanged.
207 player->notifyPlayerOfVideo();
211 static void mediaPlayerPrivateRepaintCallback(WebKitVideoSink*, GstBuffer *buffer, MediaPlayerPrivateGStreamer* playerPrivate)
213 playerPrivate->triggerRepaint(buffer);
216 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
217 static GstBusSyncReply mediaPlayerPrivateSyncHandler(GstBus* bus, GstMessage* message, MediaPlayerPrivateGStreamer* playerPrivate)
219 // ignore anything but 'prepare-xid' message
220 if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_ELEMENT)
222 if (!gst_structure_has_name (message->structure, "prepare-xid"))
225 playerPrivate->xWindowIdPrepared(message);
230 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
231 static ASM_cb_result_t MediaPlayerAudioSessionEventSourcePause(ASM_event_sources_t eventSource, void* callbackData)
233 MediaPlayer* player = static_cast<MediaPlayer*>(callbackData);
235 return ASM_CB_RES_IGNORE;
237 switch (eventSource) {
238 case ASM_EVENT_SOURCE_CALL_START:
239 case ASM_EVENT_SOURCE_ALARM_START:
240 case ASM_EVENT_SOURCE_EARJACK_UNPLUG:
241 case ASM_EVENT_SOURCE_MEDIA:
242 case ASM_EVENT_SOURCE_EMERGENCY_START:
243 case ASM_EVENT_SOURCE_OTHER_PLAYER_APP:
244 case ASM_EVENT_SOURCE_RESOURCE_CONFLICT:
246 return ASM_CB_RES_PAUSE;
248 return ASM_CB_RES_NONE;
252 static ASM_cb_result_t MediaPlayerAudioSessionEventSourcePlay(ASM_event_sources_t eventSource, void* callbackData)
254 MediaPlayer* player = static_cast<MediaPlayer*>(callbackData);
256 return ASM_CB_RES_IGNORE;
258 switch (eventSource) {
259 case ASM_EVENT_SOURCE_ALARM_END:
260 if (!player->hasVideo()) {
262 return ASM_CB_RES_PLAYING;
264 return ASM_CB_RES_NONE;
266 return ASM_CB_RES_NONE;
270 static ASM_cb_result_t mediaPlayerPrivateAudioSessionNotifyCallback(int, ASM_event_sources_t eventSource, ASM_sound_commands_t command, unsigned int, void* callbackData)
272 if (command == ASM_COMMAND_STOP || command == ASM_COMMAND_PAUSE)
273 return MediaPlayerAudioSessionEventSourcePause(eventSource, callbackData);
274 if (command == ASM_COMMAND_PLAY || command == ASM_COMMAND_RESUME)
275 return MediaPlayerAudioSessionEventSourcePlay(eventSource, callbackData);
277 return ASM_CB_RES_NONE;
281 PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivateGStreamer::create(MediaPlayer* player)
283 return adoptPtr(new MediaPlayerPrivateGStreamer(player));
286 void MediaPlayerPrivateGStreamer::registerMediaEngine(MediaEngineRegistrar registrar)
289 registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
292 bool initializeGStreamerAndRegisterWebKitElements()
294 if (!initializeGStreamer())
297 GRefPtr<GstElementFactory> srcFactory = gst_element_factory_find("webkitwebsrc");
299 #if ENABLE(TIZEN_MEDIA_STREAM)
300 return gst_element_register(0, "webkitcamerasrc", GST_RANK_PRIMARY + 200, WEBKIT_TYPE_CAMERA_SRC);
302 return gst_element_register(0, "webkitwebsrc", GST_RANK_PRIMARY + 100, WEBKIT_TYPE_WEB_SRC);
303 #endif // ENABLE(TIZEN_MEDIA_STREAM)
308 bool MediaPlayerPrivateGStreamer::isAvailable()
310 if (!initializeGStreamerAndRegisterWebKitElements())
313 GRefPtr<GstElementFactory> factory = gst_element_factory_find(gPlaybinName);
317 MediaPlayerPrivateGStreamer::MediaPlayerPrivateGStreamer(MediaPlayer* player)
320 , m_webkitVideoSink(0)
324 , m_changingRate(false)
325 , m_endTime(numeric_limits<float>::infinity())
326 , m_isEndReached(false)
327 , m_networkState(MediaPlayer::Empty)
328 , m_readyState(MediaPlayer::HaveNothing)
329 , m_isStreaming(false)
332 , m_mediaLocations(0)
333 , m_mediaLocationCurrentIndex(0)
334 , m_resetPipeline(false)
339 , m_errorOccured(false)
341 , m_startedBuffering(false)
342 , m_fillTimer(this, &MediaPlayerPrivateGStreamer::fillTimerFired)
344 , m_bufferingPercentage(0)
345 , m_preload(MediaPlayer::Auto)
346 , m_delayingLoad(false)
347 , m_mediaDurationKnown(true)
348 , m_maxTimeLoadedAtLastDidLoadingProgress(0)
349 , m_volumeTimerHandler(0)
350 , m_muteTimerHandler(0)
353 , m_audioTimerHandler(0)
354 , m_videoTimerHandler(0)
355 , m_webkitAudioSink(0)
356 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
357 , m_videoLayer(VideoLayerTizen::create(static_cast<HTMLMediaElement*>(player->mediaPlayerClient())))
358 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
359 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
360 , m_audioSessionManager(AudioSessionManagerGStreamerTizen::createAudioSessionManager())
363 if (initializeGStreamerAndRegisterWebKitElements())
367 MediaPlayerPrivateGStreamer::~MediaPlayerPrivateGStreamer()
369 if (m_fillTimer.isActive())
373 gst_buffer_unref(m_buffer);
376 if (m_mediaLocations) {
377 gst_structure_free(m_mediaLocations);
378 m_mediaLocations = 0;
381 #ifndef GST_API_VERSION_1
382 if (m_videoSinkBin) {
383 gst_object_unref(m_videoSinkBin);
389 gst_element_set_state(m_playBin, GST_STATE_NULL);
390 gst_object_unref(GST_OBJECT(m_playBin));
394 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
395 if (m_audioSessionManager)
396 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
401 if (m_muteTimerHandler)
402 g_source_remove(m_muteTimerHandler);
404 if (m_volumeTimerHandler)
405 g_source_remove(m_volumeTimerHandler);
407 if (m_videoTimerHandler)
408 g_source_remove(m_videoTimerHandler);
410 if (m_audioTimerHandler)
411 g_source_remove(m_audioTimerHandler);
414 void MediaPlayerPrivateGStreamer::load(const String& url)
416 #if ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
418 #endif // ENABLE(TIZEN_MEDIA_STREAM) || ENABLE(TIZEN_FILE_SYSTEM)
419 KURL kurl(KURL(), url);
420 String cleanUrl(url);
422 // Clean out everything after file:// url path.
423 if (kurl.isLocalFile())
424 cleanUrl = cleanUrl.substring(0, kurl.pathEnd());
426 m_url = KURL(KURL(), cleanUrl);
427 g_object_set(m_playBin, "uri", cleanUrl.utf8().data(), NULL);
429 LOG_VERBOSE(Media, "Load %s", cleanUrl.utf8().data());
431 if (m_preload == MediaPlayer::None) {
432 LOG_VERBOSE(Media, "Delaying load.");
433 m_delayingLoad = true;
436 // GStreamer needs to have the pipeline set to a paused state to
437 // start providing anything useful.
438 gst_element_set_state(m_playBin, GST_STATE_PAUSED);
440 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
441 if (m_audioSessionManager)
442 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
449 void MediaPlayerPrivateGStreamer::commitLoad()
451 ASSERT(!m_delayingLoad);
452 LOG_VERBOSE(Media, "Committing load.");
456 float MediaPlayerPrivateGStreamer::playbackPosition() const
458 if (m_isEndReached) {
459 // Position queries on a null pipeline return 0. If we're at
460 // the end of the stream the pipeline is null but we want to
461 // report either the seek time or the duration because this is
462 // what the Media element spec expects us to do.
466 return m_mediaDuration;
471 GstQuery* query = gst_query_new_position(GST_FORMAT_TIME);
472 if (!gst_element_query(m_playBin, query)) {
473 LOG_VERBOSE(Media, "Position query failed...");
474 gst_query_unref(query);
479 gst_query_parse_position(query, 0, &position);
481 // Position is available only if the pipeline is not in GST_STATE_NULL or
482 // GST_STATE_READY state.
483 if (position != static_cast<gint64>(GST_CLOCK_TIME_NONE))
484 ret = static_cast<double>(position) / GST_SECOND;
486 LOG_VERBOSE(Media, "Position %" GST_TIME_FORMAT, GST_TIME_ARGS(position));
488 gst_query_unref(query);
493 bool MediaPlayerPrivateGStreamer::changePipelineState(GstState newState)
495 ASSERT(newState == GST_STATE_PLAYING || newState == GST_STATE_PAUSED);
497 GstState currentState;
500 gst_element_get_state(m_playBin, ¤tState, &pending, 0);
501 LOG_VERBOSE(Media, "Current state: %s, pending: %s", gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
502 if (currentState == newState || pending == newState)
505 GstStateChangeReturn setStateResult = gst_element_set_state(m_playBin, newState);
506 GstState pausedOrPlaying = newState == GST_STATE_PLAYING ? GST_STATE_PAUSED : GST_STATE_PLAYING;
507 if (currentState != pausedOrPlaying && setStateResult == GST_STATE_CHANGE_FAILURE) {
508 loadingFailed(MediaPlayer::Empty);
514 void MediaPlayerPrivateGStreamer::prepareToPlay()
516 m_isEndReached = false;
519 if (m_delayingLoad) {
520 m_delayingLoad = false;
525 void MediaPlayerPrivateGStreamer::play()
527 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
528 if (m_audioSessionManager && !m_audioSessionManager->setSoundState(ASM_STATE_PLAYING))
531 if (changePipelineState(GST_STATE_PLAYING)) {
532 m_isEndReached = false;
533 LOG_VERBOSE(Media, "Play");
537 void MediaPlayerPrivateGStreamer::pause()
539 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
540 if (m_audioSessionManager && !m_audioSessionManager->setSoundState(ASM_STATE_PAUSE))
546 if (changePipelineState(GST_STATE_PAUSED))
547 LOG_VERBOSE(Media, "Pause");
550 float MediaPlayerPrivateGStreamer::duration() const
558 // Media duration query failed already, don't attempt new useless queries.
559 if (!m_mediaDurationKnown)
560 return numeric_limits<float>::infinity();
563 return m_mediaDuration;
565 GstFormat timeFormat = GST_FORMAT_TIME;
566 gint64 timeLength = 0;
568 #ifdef GST_API_VERSION_1
569 bool failure = !gst_element_query_duration(m_playBin, timeFormat, &timeLength) || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
571 bool failure = !gst_element_query_duration(m_playBin, &timeFormat, &timeLength) || timeFormat != GST_FORMAT_TIME || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
574 LOG_VERBOSE(Media, "Time duration query failed.");
575 return numeric_limits<float>::infinity();
578 LOG_VERBOSE(Media, "Duration: %" GST_TIME_FORMAT, GST_TIME_ARGS(timeLength));
580 return static_cast<double>(timeLength) / GST_SECOND;
581 // FIXME: handle 3.14.9.5 properly
584 float MediaPlayerPrivateGStreamer::currentTime() const
596 // https://bugzilla.gnome.org/show_bug.cgi?id=639941 In GStreamer
597 // 0.10.35 basesink reports wrong duration in case of EOS and
598 // negative playback rate. There's no upstream accepted patch for
599 // this bug yet, hence this temporary workaround.
600 if (m_isEndReached && m_playbackRate < 0)
603 return playbackPosition();
607 void MediaPlayerPrivateGStreamer::seek(float time)
615 LOG_VERBOSE(Media, "Seek attempt to %f secs", time);
617 // Avoid useless seeking.
618 if (time == currentTime())
621 // Extract the integer part of the time (seconds) and the
622 // fractional part (microseconds). Attempt to round the
623 // microseconds so no floating point precision is lost and we can
624 // perform an accurate seek.
626 float microSeconds = modf(time, &seconds) * 1000000;
628 timeValue.tv_sec = static_cast<glong>(seconds);
629 timeValue.tv_usec = static_cast<glong>(roundf(microSeconds / 10000) * 10000);
631 GstClockTime clockTime = GST_TIMEVAL_TO_TIME(timeValue);
632 LOG_VERBOSE(Media, "Seek: %" GST_TIME_FORMAT, GST_TIME_ARGS(clockTime));
634 if (!gst_element_seek(m_playBin, m_player->rate(),
636 (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE),
637 GST_SEEK_TYPE_SET, clockTime,
638 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
639 LOG_VERBOSE(Media, "Seek to %f failed", time);
646 bool MediaPlayerPrivateGStreamer::paused() const
648 if (m_isEndReached) {
649 LOG_VERBOSE(Media, "Ignoring pause at EOS");
654 gst_element_get_state(m_playBin, &state, 0, 0);
655 return state == GST_STATE_PAUSED;
658 bool MediaPlayerPrivateGStreamer::seeking() const
663 // Returns the size of the video
664 IntSize MediaPlayerPrivateGStreamer::naturalSize() const
669 if (!m_videoSize.isEmpty())
672 GstCaps* caps = webkitGstGetPadCaps(m_videoSinkPad.get());
677 // TODO: handle possible clean aperture data. See
678 // https://bugzilla.gnome.org/show_bug.cgi?id=596571
679 // TODO: handle possible transformation matrix. See
680 // https://bugzilla.gnome.org/show_bug.cgi?id=596326
682 // Get the video PAR and original size, if this fails the
683 // video-sink has likely not yet negotiated its caps.
684 int pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride;
685 IntSize originalSize;
686 GstVideoFormat format;
687 if (!getVideoSizeAndFormatFromCaps(caps, originalSize, format, pixelAspectRatioNumerator, pixelAspectRatioDenominator, stride))
690 LOG_VERBOSE(Media, "Original video size: %dx%d", originalSize.width(), originalSize.height());
691 LOG_VERBOSE(Media, "Pixel aspect ratio: %d/%d", pixelAspectRatioNumerator, pixelAspectRatioDenominator);
693 // Calculate DAR based on PAR and video size.
694 int displayWidth = originalSize.width() * pixelAspectRatioNumerator;
695 int displayHeight = originalSize.height() * pixelAspectRatioDenominator;
697 // Divide display width and height by their GCD to avoid possible overflows.
698 int displayAspectRatioGCD = greatestCommonDivisor(displayWidth, displayHeight);
699 displayWidth /= displayAspectRatioGCD;
700 displayHeight /= displayAspectRatioGCD;
702 // Apply DAR to original video size. This is the same behavior as in xvimagesink's setcaps function.
703 guint64 width = 0, height = 0;
704 if (!(originalSize.height() % displayHeight)) {
705 LOG_VERBOSE(Media, "Keeping video original height");
706 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
707 height = static_cast<guint64>(originalSize.height());
708 } else if (!(originalSize.width() % displayWidth)) {
709 LOG_VERBOSE(Media, "Keeping video original width");
710 height = gst_util_uint64_scale_int(originalSize.width(), displayHeight, displayWidth);
711 width = static_cast<guint64>(originalSize.width());
713 LOG_VERBOSE(Media, "Approximating while keeping original video height");
714 width = gst_util_uint64_scale_int(originalSize.height(), displayWidth, displayHeight);
715 height = static_cast<guint64>(originalSize.height());
718 LOG_VERBOSE(Media, "Natural size: %" G_GUINT64_FORMAT "x%" G_GUINT64_FORMAT, width, height);
719 m_videoSize = IntSize(static_cast<int>(width), static_cast<int>(height));
723 void MediaPlayerPrivateGStreamer::videoChanged()
725 if (m_videoTimerHandler)
726 g_source_remove(m_videoTimerHandler);
727 m_videoTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVideoChangeTimeoutCallback), this);
730 void MediaPlayerPrivateGStreamer::notifyPlayerOfVideo()
732 m_videoTimerHandler = 0;
734 gint videoTracks = 0;
736 g_object_get(m_playBin, "n-video", &videoTracks, NULL);
738 m_hasVideo = videoTracks > 0;
740 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
743 if (gst_video_get_size(m_videoSinkPad.get(), &width, &height)) {
744 IntSize size(width, height);
745 if (m_videoSize != size) {
746 m_videoSize = IntSize();
747 m_videoLayer->setOverlay(naturalSize());
751 m_videoSize = IntSize();
753 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
756 void MediaPlayerPrivateGStreamer::audioChanged()
758 if (m_audioTimerHandler)
759 g_source_remove(m_audioTimerHandler);
760 m_audioTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateAudioChangeTimeoutCallback), this);
763 void MediaPlayerPrivateGStreamer::notifyPlayerOfAudio()
765 m_audioTimerHandler = 0;
767 gint audioTracks = 0;
769 g_object_get(m_playBin, "n-audio", &audioTracks, NULL);
770 m_hasAudio = audioTracks > 0;
771 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
774 void MediaPlayerPrivateGStreamer::setVolume(float volume)
779 gst_stream_volume_set_volume(GST_STREAM_VOLUME(m_playBin), GST_STREAM_VOLUME_FORMAT_CUBIC,
780 static_cast<double>(volume));
783 void MediaPlayerPrivateGStreamer::notifyPlayerOfVolumeChange()
785 m_volumeTimerHandler = 0;
787 if (!m_player || !m_playBin)
790 volume = gst_stream_volume_get_volume(GST_STREAM_VOLUME(m_playBin), GST_STREAM_VOLUME_FORMAT_CUBIC);
791 // get_volume() can return values superior to 1.0 if the user
792 // applies software user gain via third party application (GNOME
793 // volume control for instance).
794 volume = CLAMP(volume, 0.0, 1.0);
795 m_player->volumeChanged(static_cast<float>(volume));
798 void MediaPlayerPrivateGStreamer::volumeChanged()
800 if (m_volumeTimerHandler)
801 g_source_remove(m_volumeTimerHandler);
802 m_volumeTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVolumeChangeTimeoutCallback), this);
805 void MediaPlayerPrivateGStreamer::setRate(float rate)
807 // Avoid useless playback rate update.
808 if (m_playbackRate == rate)
814 gst_element_get_state(m_playBin, &state, &pending, 0);
815 if ((state != GST_STATE_PLAYING && state != GST_STATE_PAUSED)
816 || (pending == GST_STATE_PAUSED))
822 m_playbackRate = rate;
823 m_changingRate = true;
826 gst_element_set_state(m_playBin, GST_STATE_PAUSED);
828 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
829 if (m_audioSessionManager)
830 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
835 float currentPosition = static_cast<float>(playbackPosition() * GST_SECOND);
836 GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH);
840 LOG_VERBOSE(Media, "Set Rate to %f", rate);
842 // Mute the sound if the playback rate is too extreme.
843 // TODO: in other cases we should perform pitch adjustments.
844 mute = (bool) (rate < 0.8 || rate > 2);
845 start = currentPosition;
846 end = GST_CLOCK_TIME_NONE;
851 // If we are at beginning of media, start from the end to
852 // avoid immediate EOS.
853 if (currentPosition <= 0)
854 end = static_cast<gint64>(duration() * GST_SECOND);
856 end = currentPosition;
859 LOG_VERBOSE(Media, "Need to mute audio: %d", (int) mute);
861 if (!gst_element_seek(m_playBin, rate, GST_FORMAT_TIME, flags,
862 GST_SEEK_TYPE_SET, start,
863 GST_SEEK_TYPE_SET, end))
864 LOG_VERBOSE(Media, "Set rate to %f failed", rate);
866 g_object_set(m_playBin, "mute", mute, NULL);
869 MediaPlayer::NetworkState MediaPlayerPrivateGStreamer::networkState() const
871 return m_networkState;
874 MediaPlayer::ReadyState MediaPlayerPrivateGStreamer::readyState() const
879 PassRefPtr<TimeRanges> MediaPlayerPrivateGStreamer::buffered() const
881 RefPtr<TimeRanges> timeRanges = TimeRanges::create();
882 if (m_errorOccured || m_isStreaming)
883 return timeRanges.release();
885 #if GST_CHECK_VERSION(0, 10, 31)
886 float mediaDuration(duration());
887 if (!mediaDuration || isinf(mediaDuration))
888 return timeRanges.release();
890 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
892 if (!gst_element_query(m_playBin, query)) {
893 gst_query_unref(query);
894 return timeRanges.release();
897 gint64 rangeStart = 0, rangeStop = 0;
898 for (guint index = 0; index < gst_query_get_n_buffering_ranges(query); index++) {
899 if (gst_query_parse_nth_buffering_range(query, index, &rangeStart, &rangeStop))
900 timeRanges->add(static_cast<float>((rangeStart * mediaDuration) / 100),
901 static_cast<float>((rangeStop * mediaDuration) / 100));
904 // Fallback to the more general maxTimeLoaded() if no range has
906 if (!timeRanges->length())
907 if (float loaded = maxTimeLoaded())
908 timeRanges->add(0, loaded);
910 gst_query_unref(query);
912 float loaded = maxTimeLoaded();
913 if (!m_errorOccured && !m_isStreaming && loaded > 0)
914 timeRanges->add(0, loaded);
916 return timeRanges.release();
919 gboolean MediaPlayerPrivateGStreamer::handleMessage(GstMessage* message)
922 GOwnPtr<gchar> debug;
923 MediaPlayer::NetworkState error;
924 bool issueError = true;
925 bool attemptNextLocation = false;
926 const GstStructure* structure = gst_message_get_structure(message);
929 const gchar* messageTypeName = gst_structure_get_name(structure);
931 // Redirect messages are sent from elements, like qtdemux, to
932 // notify of the new location(s) of the media.
933 if (!g_strcmp0(messageTypeName, "redirect")) {
934 mediaLocationChanged(message);
939 switch (GST_MESSAGE_TYPE(message)) {
940 case GST_MESSAGE_ERROR:
943 gst_message_parse_error(message, &err.outPtr(), &debug.outPtr());
944 LOG_VERBOSE(Media, "Error: %d, %s", err->code, err->message);
946 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin), GST_DEBUG_GRAPH_SHOW_ALL, "webkit-video.error");
948 error = MediaPlayer::Empty;
949 if (err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND
950 || err->code == GST_STREAM_ERROR_WRONG_TYPE
951 || err->code == GST_STREAM_ERROR_FAILED
952 || err->code == GST_CORE_ERROR_MISSING_PLUGIN
953 || err->code == GST_RESOURCE_ERROR_NOT_FOUND)
954 error = MediaPlayer::FormatError;
955 else if (err->domain == GST_STREAM_ERROR) {
956 // Let the mediaPlayerClient handle the stream error, in
957 // this case the HTMLMediaElement will emit a stalled
959 if (err->code == GST_STREAM_ERROR_TYPE_NOT_FOUND) {
960 LOG_VERBOSE(Media, "Decode error, let the Media element emit a stalled event.");
963 error = MediaPlayer::DecodeError;
964 attemptNextLocation = true;
965 } else if (err->domain == GST_RESOURCE_ERROR)
966 error = MediaPlayer::NetworkError;
968 if (attemptNextLocation)
969 issueError = !loadNextLocation();
971 loadingFailed(error);
973 case GST_MESSAGE_EOS:
974 LOG_VERBOSE(Media, "End of Stream");
977 case GST_MESSAGE_STATE_CHANGED:
978 // Ignore state changes if load is delayed (preload=none). The
979 // player state will be updated once commitLoad() is called.
980 if (m_delayingLoad) {
981 LOG_VERBOSE(Media, "Media load has been delayed. Ignoring state changes for now");
985 // Ignore state changes from internal elements. They are
986 // forwarded to playbin2 anyway.
987 if (GST_MESSAGE_SRC(message) == reinterpret_cast<GstObject*>(m_playBin)) {
990 // Construct a filename for the graphviz dot file output.
991 GstState oldState, newState;
992 gst_message_parse_state_changed(message, &oldState, &newState, 0);
994 CString dotFileName = String::format("webkit-video.%s_%s",
995 gst_element_state_get_name(oldState),
996 gst_element_state_get_name(newState)).utf8();
998 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin), GST_DEBUG_GRAPH_SHOW_ALL, dotFileName.data());
1001 case GST_MESSAGE_BUFFERING:
1002 processBufferingStats(message);
1004 case GST_MESSAGE_DURATION:
1005 LOG_VERBOSE(Media, "Duration changed");
1009 LOG_VERBOSE(Media, "Unhandled GStreamer message type: %s",
1010 GST_MESSAGE_TYPE_NAME(message));
1016 void MediaPlayerPrivateGStreamer::processBufferingStats(GstMessage* message)
1018 // This is the immediate buffering that needs to happen so we have
1019 // enough to play right now.
1021 const GstStructure *structure = gst_message_get_structure(message);
1022 gst_structure_get_int(structure, "buffer-percent", &m_bufferingPercentage);
1024 LOG_VERBOSE(Media, "[Buffering] Buffering: %d%%.", m_bufferingPercentage);
1026 GstBufferingMode mode;
1027 gst_message_parse_buffering_stats(message, &mode, 0, 0, 0);
1028 if (mode != GST_BUFFERING_DOWNLOAD) {
1033 // This is on-disk buffering, that allows us to download much more
1034 // than needed for right now.
1035 if (!m_startedBuffering) {
1036 LOG_VERBOSE(Media, "[Buffering] Starting on-disk buffering.");
1038 m_startedBuffering = true;
1040 if (m_fillTimer.isActive())
1043 m_fillTimer.startRepeating(0.2);
1047 void MediaPlayerPrivateGStreamer::fillTimerFired(Timer<MediaPlayerPrivateGStreamer>*)
1049 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
1051 if (!gst_element_query(m_playBin, query)) {
1052 gst_query_unref(query);
1057 gdouble fillStatus = 100.0;
1059 gst_query_parse_buffering_range(query, 0, &start, &stop, 0);
1060 gst_query_unref(query);
1063 fillStatus = 100.0 * stop / GST_FORMAT_PERCENT_MAX;
1065 LOG_VERBOSE(Media, "[Buffering] Download buffer filled up to %f%%", fillStatus);
1067 if (!m_mediaDuration)
1070 // Update maxTimeLoaded only if the media duration is
1071 // available. Otherwise we can't compute it.
1072 if (m_mediaDuration) {
1073 if (fillStatus == 100.0)
1074 m_maxTimeLoaded = m_mediaDuration;
1076 m_maxTimeLoaded = static_cast<float>((fillStatus * m_mediaDuration) / 100.0);
1077 LOG_VERBOSE(Media, "[Buffering] Updated maxTimeLoaded: %f", m_maxTimeLoaded);
1080 if (fillStatus != 100.0) {
1085 // Media is now fully loaded. It will play even if network
1086 // connection is cut. Buffering is done, remove the fill source
1087 // from the main loop.
1089 m_startedBuffering = false;
1093 float MediaPlayerPrivateGStreamer::maxTimeSeekable() const
1098 LOG_VERBOSE(Media, "maxTimeSeekable");
1099 // infinite duration means live stream
1100 if (isinf(duration()))
1106 float MediaPlayerPrivateGStreamer::maxTimeLoaded() const
1111 float loaded = m_maxTimeLoaded;
1112 if (!loaded && !m_fillTimer.isActive())
1113 loaded = duration();
1114 LOG_VERBOSE(Media, "maxTimeLoaded: %f", loaded);
1118 bool MediaPlayerPrivateGStreamer::didLoadingProgress() const
1120 if (!m_playBin || !m_mediaDuration || !totalBytes())
1122 float currentMaxTimeLoaded = maxTimeLoaded();
1123 bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
1124 m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
1125 LOG_VERBOSE(Media, "didLoadingProgress: %d", didLoadingProgress);
1126 return didLoadingProgress;
1129 unsigned MediaPlayerPrivateGStreamer::totalBytes() const
1137 GstFormat fmt = GST_FORMAT_BYTES;
1139 #ifdef GST_API_VERSION_1
1140 if (gst_element_query_duration(m_source.get(), fmt, &length)) {
1142 if (gst_element_query_duration(m_source.get(), &fmt, &length)) {
1144 LOG_VERBOSE(Media, "totalBytes %" G_GINT64_FORMAT, length);
1145 return static_cast<unsigned>(length);
1148 // Fall back to querying the source pads manually.
1149 // See also https://bugzilla.gnome.org/show_bug.cgi?id=638749
1150 GstIterator* iter = gst_element_iterate_src_pads(m_source.get());
1153 #ifdef GST_API_VERSION_1
1154 GValue item = G_VALUE_INIT;
1155 switch (gst_iterator_next(iter, &item)) {
1156 case GST_ITERATOR_OK: {
1157 GstPad* pad = static_cast<GstPad*>(g_value_get_object(&item));
1158 gint64 padLength = 0;
1159 if (gst_pad_query_duration(pad, fmt, &padLength) && padLength > length)
1166 switch (gst_iterator_next(iter, &data)) {
1167 case GST_ITERATOR_OK: {
1168 GRefPtr<GstPad> pad = adoptGRef(GST_PAD_CAST(data));
1169 gint64 padLength = 0;
1170 if (gst_pad_query_duration(pad.get(), &fmt, &padLength) && padLength > length)
1175 case GST_ITERATOR_RESYNC:
1176 gst_iterator_resync(iter);
1178 case GST_ITERATOR_ERROR:
1180 case GST_ITERATOR_DONE:
1185 #ifdef GST_API_VERSION_1
1186 g_value_unset(&item);
1190 gst_iterator_free(iter);
1192 LOG_VERBOSE(Media, "totalBytes %" G_GINT64_FORMAT, length);
1194 return static_cast<unsigned>(length);
1197 unsigned MediaPlayerPrivateGStreamer::decodedFrameCount() const
1199 guint64 decodedFrames = 0;
1201 g_object_get(m_fpsSink, "frames-rendered", &decodedFrames, NULL);
1202 return static_cast<unsigned>(decodedFrames);
1205 unsigned MediaPlayerPrivateGStreamer::droppedFrameCount() const
1207 guint64 framesDropped = 0;
1209 g_object_get(m_fpsSink, "frames-dropped", &framesDropped, NULL);
1210 return static_cast<unsigned>(framesDropped);
1213 unsigned MediaPlayerPrivateGStreamer::audioDecodedByteCount() const
1215 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1216 gint64 position = 0;
1218 if (m_webkitAudioSink && gst_element_query(m_webkitAudioSink.get(), query))
1219 gst_query_parse_position(query, 0, &position);
1221 gst_query_unref(query);
1222 return static_cast<unsigned>(position);
1225 unsigned MediaPlayerPrivateGStreamer::videoDecodedByteCount() const
1227 GstQuery* query = gst_query_new_position(GST_FORMAT_BYTES);
1228 gint64 position = 0;
1230 if (gst_element_query(m_webkitVideoSink, query))
1231 gst_query_parse_position(query, 0, &position);
1233 gst_query_unref(query);
1234 return static_cast<unsigned>(position);
1237 void MediaPlayerPrivateGStreamer::updateAudioSink()
1242 GstElement* sinkPtr = 0;
1244 g_object_get(m_playBin, "audio-sink", &sinkPtr, NULL);
1245 m_webkitAudioSink = adoptGRef(sinkPtr);
1250 void MediaPlayerPrivateGStreamer::sourceChanged()
1252 GstElement* srcPtr = 0;
1254 g_object_get(m_playBin, "source", &srcPtr, NULL);
1255 m_source = adoptGRef(srcPtr);
1257 if (WEBKIT_IS_WEB_SRC(m_source.get()))
1258 webKitWebSrcSetMediaPlayer(WEBKIT_WEB_SRC(m_source.get()), m_player);
1261 void MediaPlayerPrivateGStreamer::cancelLoad()
1263 if (m_networkState < MediaPlayer::Loading || m_networkState == MediaPlayer::Loaded)
1267 gst_element_set_state(m_playBin, GST_STATE_NULL);
1269 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1270 if (m_audioSessionManager)
1271 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
1275 void MediaPlayerPrivateGStreamer::updateStates()
1283 MediaPlayer::NetworkState oldNetworkState = m_networkState;
1284 MediaPlayer::ReadyState oldReadyState = m_readyState;
1288 GstStateChangeReturn ret = gst_element_get_state(m_playBin,
1289 &state, &pending, 250 * GST_NSECOND);
1291 bool shouldUpdateAfterSeek = false;
1293 case GST_STATE_CHANGE_SUCCESS:
1294 LOG_VERBOSE(Media, "State: %s, pending: %s",
1295 gst_element_state_get_name(state),
1296 gst_element_state_get_name(pending));
1298 m_resetPipeline = state <= GST_STATE_READY;
1300 // Try to figure out ready and network states.
1301 if (state == GST_STATE_READY) {
1302 m_readyState = MediaPlayer::HaveMetadata;
1303 m_networkState = MediaPlayer::Empty;
1304 // Cache the duration without emiting the durationchange
1305 // event because it's taken care of by the media element
1306 // in this precise case.
1307 if (!m_isEndReached)
1309 } else if ((state == GST_STATE_NULL) || (maxTimeLoaded() == duration())) {
1310 m_networkState = MediaPlayer::Loaded;
1311 m_readyState = MediaPlayer::HaveEnoughData;
1313 m_readyState = currentTime() < maxTimeLoaded() ? MediaPlayer::HaveFutureData : MediaPlayer::HaveCurrentData;
1314 m_networkState = MediaPlayer::Loading;
1317 if (m_buffering && state != GST_STATE_READY) {
1318 m_readyState = MediaPlayer::HaveCurrentData;
1319 m_networkState = MediaPlayer::Loading;
1322 // Now let's try to get the states in more detail using
1323 // information from GStreamer, while we sync states where
1325 if (state == GST_STATE_PAUSED) {
1326 if (!m_webkitAudioSink)
1328 if (m_buffering && m_bufferingPercentage == 100) {
1329 m_buffering = false;
1330 m_bufferingPercentage = 0;
1331 m_readyState = MediaPlayer::HaveEnoughData;
1333 LOG_VERBOSE(Media, "[Buffering] Complete.");
1336 LOG_VERBOSE(Media, "[Buffering] Restarting playback.");
1337 gst_element_set_state(m_playBin, GST_STATE_PLAYING);
1339 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1340 if (m_audioSessionManager)
1341 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1344 } else if (!m_buffering && (currentTime() < duration())) {
1347 } else if (state == GST_STATE_PLAYING) {
1348 m_readyState = MediaPlayer::HaveEnoughData;
1352 m_readyState = MediaPlayer::HaveCurrentData;
1353 m_networkState = MediaPlayer::Loading;
1355 LOG_VERBOSE(Media, "[Buffering] Pausing stream for buffering.");
1357 gst_element_set_state(m_playBin, GST_STATE_PAUSED);
1359 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1360 if (m_audioSessionManager)
1361 m_audioSessionManager->setSoundState(ASM_STATE_PAUSE);
1367 // Is on-disk buffering in progress?
1368 if (m_fillTimer.isActive())
1369 m_networkState = MediaPlayer::Loading;
1371 if (m_changingRate) {
1372 m_player->rateChanged();
1373 m_changingRate = false;
1377 shouldUpdateAfterSeek = true;
1382 case GST_STATE_CHANGE_ASYNC:
1383 LOG_VERBOSE(Media, "Async: State: %s, pending: %s",
1384 gst_element_state_get_name(state),
1385 gst_element_state_get_name(pending));
1386 // Change in progress
1388 if (!m_isStreaming && !m_buffering)
1392 shouldUpdateAfterSeek = true;
1396 case GST_STATE_CHANGE_FAILURE:
1397 LOG_VERBOSE(Media, "Failure: State: %s, pending: %s",
1398 gst_element_state_get_name(state),
1399 gst_element_state_get_name(pending));
1402 case GST_STATE_CHANGE_NO_PREROLL:
1403 LOG_VERBOSE(Media, "No preroll: State: %s, pending: %s",
1404 gst_element_state_get_name(state),
1405 gst_element_state_get_name(pending));
1407 if (state == GST_STATE_READY)
1408 m_readyState = MediaPlayer::HaveNothing;
1409 else if (state == GST_STATE_PAUSED) {
1410 m_readyState = MediaPlayer::HaveEnoughData;
1412 // Live pipelines go in PAUSED without prerolling.
1413 m_isStreaming = true;
1414 } else if (state == GST_STATE_PLAYING)
1418 shouldUpdateAfterSeek = true;
1421 gst_element_set_state(m_playBin, GST_STATE_PLAYING);
1423 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1424 if (m_audioSessionManager)
1425 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1428 } else if (!m_paused) {
1429 gst_element_set_state(m_playBin, GST_STATE_PLAYING);
1431 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1432 if (m_audioSessionManager)
1433 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1437 m_networkState = MediaPlayer::Loading;
1440 LOG_VERBOSE(Media, "Else : %d", ret);
1445 m_readyState = MediaPlayer::HaveNothing;
1447 if (shouldUpdateAfterSeek)
1450 if (m_networkState != oldNetworkState) {
1451 LOG_VERBOSE(Media, "Network State Changed from %u to %u",
1452 oldNetworkState, m_networkState);
1453 m_player->networkStateChanged();
1455 if (m_readyState != oldReadyState) {
1456 LOG_VERBOSE(Media, "Ready State Changed from %u to %u",
1457 oldReadyState, m_readyState);
1458 m_player->readyStateChanged();
1459 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
1460 if (state == GST_STATE_PLAYING)
1461 m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
1466 void MediaPlayerPrivateGStreamer::mediaLocationChanged(GstMessage* message)
1468 if (m_mediaLocations)
1469 gst_structure_free(m_mediaLocations);
1471 const GstStructure* structure = gst_message_get_structure(message);
1473 // This structure can contain:
1474 // - both a new-location string and embedded locations structure
1475 // - or only a new-location string.
1476 m_mediaLocations = gst_structure_copy(structure);
1477 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1480 m_mediaLocationCurrentIndex = static_cast<int>(gst_value_list_get_size(locations)) -1;
1486 bool MediaPlayerPrivateGStreamer::loadNextLocation()
1488 if (!m_mediaLocations)
1491 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1492 const gchar* newLocation = 0;
1495 // Fallback on new-location string.
1496 newLocation = gst_structure_get_string(m_mediaLocations, "new-location");
1502 if (m_mediaLocationCurrentIndex < 0) {
1503 m_mediaLocations = 0;
1507 const GValue* location = gst_value_list_get_value(locations,
1508 m_mediaLocationCurrentIndex);
1509 const GstStructure* structure = gst_value_get_structure(location);
1512 m_mediaLocationCurrentIndex--;
1516 newLocation = gst_structure_get_string(structure, "new-location");
1520 // Found a candidate. new-location is not always an absolute url
1521 // though. We need to take the base of the current url and
1522 // append the value of new-location to it.
1524 gchar* currentLocation = 0;
1525 g_object_get(m_playBin, "uri", ¤tLocation, NULL);
1527 KURL currentUrl(KURL(), currentLocation);
1528 g_free(currentLocation);
1532 if (gst_uri_is_valid(newLocation))
1533 newUrl = KURL(KURL(), newLocation);
1535 newUrl = KURL(KURL(), currentUrl.baseAsString() + newLocation);
1537 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(currentUrl);
1538 if (securityOrigin->canRequest(newUrl)) {
1539 LOG_VERBOSE(Media, "New media url: %s", newUrl.string().utf8().data());
1541 // Reset player states.
1542 m_networkState = MediaPlayer::Loading;
1543 m_player->networkStateChanged();
1544 m_readyState = MediaPlayer::HaveNothing;
1545 m_player->readyStateChanged();
1547 // Reset pipeline state.
1548 m_resetPipeline = true;
1549 gst_element_set_state(m_playBin, GST_STATE_READY);
1551 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1552 if (m_audioSessionManager)
1553 m_audioSessionManager->setSoundState(ASM_STATE_NONE);
1556 gst_element_get_state(m_playBin, &state, 0, 0);
1557 if (state <= GST_STATE_READY) {
1558 // Set the new uri and start playing.
1559 g_object_set(m_playBin, "uri", newUrl.string().utf8().data(), NULL);
1560 gst_element_set_state(m_playBin, GST_STATE_PLAYING);
1562 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1563 if (m_audioSessionManager)
1564 m_audioSessionManager->setSoundState(ASM_STATE_PLAYING);
1570 m_mediaLocationCurrentIndex--;
1575 void MediaPlayerPrivateGStreamer::loadStateChanged()
1580 void MediaPlayerPrivateGStreamer::sizeChanged()
1585 void MediaPlayerPrivateGStreamer::timeChanged()
1588 m_player->timeChanged();
1591 void MediaPlayerPrivateGStreamer::didEnd()
1593 // Synchronize position and duration values to not confuse the
1594 // HTMLMediaElement. In some cases like reverse playback the
1595 // position is not always reported as 0 for instance.
1596 float now = currentTime();
1597 if (now > 0 && now <= duration() && m_mediaDuration != now) {
1598 m_mediaDurationKnown = true;
1599 m_mediaDuration = now;
1600 m_player->durationChanged();
1603 m_isEndReached = true;
1606 if (!m_player->mediaPlayerClient()->mediaPlayerIsLooping()) {
1608 gst_element_set_state(m_playBin, GST_STATE_NULL);
1610 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
1611 if (m_audioSessionManager)
1612 m_audioSessionManager->setSoundState(ASM_STATE_STOP);
1617 void MediaPlayerPrivateGStreamer::cacheDuration()
1619 // Reset cached media duration
1620 m_mediaDuration = 0;
1622 // And re-cache it if possible.
1624 gst_element_get_state(m_playBin, &state, 0, 0);
1625 float newDuration = duration();
1627 if (state <= GST_STATE_READY) {
1628 // Don't set m_mediaDurationKnown yet if the pipeline is not
1629 // paused. This allows duration() query to fail at least once
1630 // before playback starts and duration becomes known.
1631 if (!isinf(newDuration))
1632 m_mediaDuration = newDuration;
1634 m_mediaDurationKnown = !isinf(newDuration);
1635 if (m_mediaDurationKnown)
1636 m_mediaDuration = newDuration;
1639 if (!isinf(newDuration))
1640 m_mediaDuration = newDuration;
1643 void MediaPlayerPrivateGStreamer::durationChanged()
1645 float previousDuration = m_mediaDuration;
1648 // Avoid emiting durationchanged in the case where the previous
1649 // duration was 0 because that case is already handled by the
1650 // HTMLMediaElement.
1651 if (previousDuration && m_mediaDuration != previousDuration)
1652 m_player->durationChanged();
1655 bool MediaPlayerPrivateGStreamer::supportsMuting() const
1660 void MediaPlayerPrivateGStreamer::setMuted(bool muted)
1665 g_object_set(m_playBin, "mute", muted, NULL);
1668 void MediaPlayerPrivateGStreamer::notifyPlayerOfMute()
1670 m_muteTimerHandler = 0;
1672 if (!m_player || !m_playBin)
1676 g_object_get(m_playBin, "mute", &muted, NULL);
1677 m_player->muteChanged(static_cast<bool>(muted));
1680 void MediaPlayerPrivateGStreamer::muteChanged()
1682 if (m_muteTimerHandler)
1683 g_source_remove(m_muteTimerHandler);
1684 m_muteTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateMuteChangeTimeoutCallback), this);
1687 void MediaPlayerPrivateGStreamer::loadingFailed(MediaPlayer::NetworkState error)
1689 m_errorOccured = true;
1690 if (m_networkState != error) {
1691 m_networkState = error;
1692 m_player->networkStateChanged();
1694 if (m_readyState != MediaPlayer::HaveNothing) {
1695 m_readyState = MediaPlayer::HaveNothing;
1696 m_player->readyStateChanged();
1700 void MediaPlayerPrivateGStreamer::setSize(const IntSize& size)
1705 void MediaPlayerPrivateGStreamer::setVisible(bool visible)
1709 void MediaPlayerPrivateGStreamer::triggerRepaint(GstBuffer* buffer)
1711 g_return_if_fail(GST_IS_BUFFER(buffer));
1712 gst_buffer_replace(&m_buffer, buffer);
1713 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && !ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1714 if (m_videoSize.isEmpty())
1715 m_videoSize = naturalSize();
1716 m_videoLayer->paintVideoLayer(m_videoSize);
1718 m_player->repaint();
1722 void MediaPlayerPrivateGStreamer::paint(GraphicsContext* context, const IntRect& rect)
1724 if (context->paintingDisabled())
1727 if (!m_player->visible())
1733 GstCaps* caps = webkitGstGetPadCaps(m_videoSinkPad.get());
1737 RefPtr<ImageGStreamer> gstImage = ImageGStreamer::createImage(m_buffer, caps);
1741 context->drawImage(reinterpret_cast<Image*>(gstImage->image().get()), ColorSpaceSRGB,
1742 rect, gstImage->rect(), CompositeCopy, DoNotRespectImageOrientation, false);
1745 static HashSet<String> mimeTypeCache()
1747 initializeGStreamerAndRegisterWebKitElements();
1749 DEFINE_STATIC_LOCAL(HashSet<String>, cache, ());
1750 static bool typeListInitialized = false;
1752 if (typeListInitialized)
1754 const char* mimeTypes[] = {"application/ogg",
1755 "application/vnd.apple.mpegurl",
1756 "application/vnd.rn-realmedia",
1757 "application/x-3gp",
1758 "application/x-pn-realaudio",
1777 "audio/x-amr-nb-sh",
1778 "audio/x-amr-wb-sh",
1809 "audio/x-vorbis+ogg",
1813 "audio/x-wavpack-correction",
1839 for (unsigned i = 0; i < (sizeof(mimeTypes) / sizeof(*mimeTypes)); ++i)
1840 cache.add(String(mimeTypes[i]));
1842 typeListInitialized = true;
1846 void MediaPlayerPrivateGStreamer::getSupportedTypes(HashSet<String>& types)
1848 types = mimeTypeCache();
1851 MediaPlayer::SupportsType MediaPlayerPrivateGStreamer::supportsType(const String& type, const String& codecs, const KURL&)
1853 if (type.isNull() || type.isEmpty())
1854 return MediaPlayer::IsNotSupported;
1856 // spec says we should not return "probably" if the codecs string is empty
1857 if (mimeTypeCache().contains(type))
1858 return codecs.isEmpty() ? MediaPlayer::MayBeSupported : MediaPlayer::IsSupported;
1859 return MediaPlayer::IsNotSupported;
1862 bool MediaPlayerPrivateGStreamer::hasSingleSecurityOrigin() const
1867 bool MediaPlayerPrivateGStreamer::supportsFullscreen() const
1869 #if PLATFORM(MAC) && !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
1870 // See <rdar://problem/7389945>
1877 PlatformMedia MediaPlayerPrivateGStreamer::platformMedia() const
1880 #ifndef GST_API_VERSION_1
1881 p.type = PlatformMedia::GStreamerGWorldType;
1882 p.media.gstreamerGWorld = m_gstGWorld.get();
1887 void MediaPlayerPrivateGStreamer::setPreload(MediaPlayer::Preload preload)
1891 m_preload = preload;
1894 g_object_get(m_playBin, "flags", &flags, NULL);
1895 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1896 flags = (GstPlayFlags)(flags | GST_PLAY_FLAG_NATIVE_VIDEO);
1898 if (preload == MediaPlayer::None)
1899 g_object_set(m_playBin, "flags", flags & ~GST_PLAY_FLAG_DOWNLOAD, NULL);
1901 g_object_set(m_playBin, "flags", flags | GST_PLAY_FLAG_DOWNLOAD, NULL);
1903 if (m_delayingLoad && m_preload != MediaPlayer::None) {
1904 m_delayingLoad = false;
1909 const char * MediaPlayerPrivateGStreamer::mediaClass() const
1911 static const gchar *default_media_class = "music";
1913 return default_media_class;
1916 void MediaPlayerPrivateGStreamer::createGSTPlayBin()
1919 const gchar *media_class = mediaClass();
1921 m_playBin = gst_element_factory_make(gPlaybinName, "play");
1923 GstElement *sink = gst_element_factory_make("pulsesink", "audio-sink");
1925 GstStructure *props;
1926 gchar prop_str[256] = "props,media.role=";
1928 strncat(prop_str, media_class, sizeof(prop_str));
1929 prop_str[sizeof(prop_str)-1] = 0;
1931 props = gst_structure_from_string(prop_str, NULL);
1932 g_object_set(sink, "stream-properties", props, NULL);
1933 gst_structure_free(props);
1935 g_object_set(m_playBin, "audio-sink", sink, NULL);
1938 #ifndef GST_API_VERSION_1
1939 m_gstGWorld = GStreamerGWorld::createGWorld(m_playBin);
1942 GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(m_playBin));
1943 gst_bus_add_signal_watch(bus);
1944 g_signal_connect(bus, "message", G_CALLBACK(mediaPlayerPrivateMessageCallback), this);
1945 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1946 gst_bus_set_sync_handler(bus, GstBusSyncHandler(mediaPlayerPrivateSyncHandler), this);
1948 gst_object_unref(bus);
1950 g_object_set(m_playBin, "mute", m_player->muted(), NULL);
1952 g_signal_connect(m_playBin, "notify::volume", G_CALLBACK(mediaPlayerPrivateVolumeChangedCallback), this);
1953 g_signal_connect(m_playBin, "notify::source", G_CALLBACK(mediaPlayerPrivateSourceChangedCallback), this);
1954 g_signal_connect(m_playBin, "notify::mute", G_CALLBACK(mediaPlayerPrivateMuteChangedCallback), this);
1955 g_signal_connect(m_playBin, "video-changed", G_CALLBACK(mediaPlayerPrivateVideoChangedCallback), this);
1956 g_signal_connect(m_playBin, "audio-changed", G_CALLBACK(mediaPlayerPrivateAudioChangedCallback), this);
1957 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
1958 g_signal_connect(m_playBin, "source-setup", G_CALLBACK(mediaPlayerPrivateSourceSetupCallback), this);
1961 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1962 m_webkitVideoSink = m_videoLayer->createVideoSink();
1963 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
1964 #else // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1965 #ifndef GST_API_VERSION_1
1966 m_webkitVideoSink = webkitVideoSinkNew(m_gstGWorld.get());
1968 m_webkitVideoSink = webkitVideoSinkNew();
1970 m_videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
1972 g_signal_connect(m_webkitVideoSink, "repaint-requested", G_CALLBACK(mediaPlayerPrivateRepaintCallback), this);
1973 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER) && ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
1975 #ifndef GST_API_VERSION_1
1976 m_videoSinkBin = gst_bin_new("sink");
1978 GstElement* videoTee = gst_element_factory_make("tee", "videoTee");
1979 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
1980 GstElement* queue = gst_element_factory_make("queue", 0);
1983 gst_object_ref_sink(m_videoSinkBin);
1985 // Build a new video sink consisting of a bin containing a tee
1986 // (meant to distribute data to multiple video sinks) and our
1987 // internal video sink. For fullscreen we create an autovideosink
1988 // and initially block the data flow towards it and configure it
1989 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
1990 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, queue, NULL);
1992 gst_bin_add_many(GST_BIN(m_videoSinkBin), videoTee, NULL);
1995 #if !ENABLE(TIZEN_GSTREAMER_VIDEO)
1996 // Link a new src pad from tee to queue1.
1997 GRefPtr<GstPad> srcPad = adoptGRef(gst_element_get_request_pad(videoTee, "src%d"));
1998 GRefPtr<GstPad> sinkPad = adoptGRef(gst_element_get_static_pad(queue, "sink"));
1999 gst_pad_link(srcPad.get(), sinkPad.get());
2003 GstElement* actualVideoSink = 0;
2004 m_fpsSink = gst_element_factory_make("fpsdisplaysink", "sink");
2006 // The verbose property has been added in -bad 0.10.22. Making
2007 // this whole code depend on it because we don't want
2008 // fpsdiplaysink to spit data on stdout.
2009 GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(m_fpsSink)->elementfactory);
2010 if (gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 22)) {
2011 g_object_set(m_fpsSink, "silent", TRUE , NULL);
2013 // Turn off text overlay unless logging is enabled.
2015 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2017 WTFLogChannel* channel = getChannelFromName("Media");
2018 if (channel->state != WTFLogChannelOn)
2019 g_object_set(m_fpsSink, "text-overlay", FALSE , NULL);
2020 #endif // LOG_DISABLED
2022 if (g_object_class_find_property(G_OBJECT_GET_CLASS(m_fpsSink), "video-sink")) {
2023 g_object_set(m_fpsSink, "video-sink", m_webkitVideoSink, NULL);
2024 #ifndef GST_API_VERSION_1
2025 gst_bin_add(GST_BIN(m_videoSinkBin), m_fpsSink);
2027 actualVideoSink = m_fpsSink;
2035 #ifndef GST_API_VERSION_1
2036 gst_bin_add(GST_BIN(m_videoSinkBin), m_webkitVideoSink);
2038 actualVideoSink = m_webkitVideoSink;
2041 ASSERT(actualVideoSink);
2043 #ifndef GST_API_VERSION_1
2044 #if ENABLE(TIZEN_GSTREAMER_VIDEO)
2045 // Link a new src pad from tee to queue1.
2046 GRefPtr<GstPad> srcPad = adoptGRef(gst_element_get_request_pad(videoTee, "src%d"));
2047 GRefPtr<GstPad> sinkPad = adoptGRef(gst_element_get_static_pad(actualVideoSink, "sink"));
2048 gst_pad_link(srcPad.get(), sinkPad.get());
2050 // Faster elements linking.
2051 gst_element_link_pads_full(queue, "src", actualVideoSink, "sink", GST_PAD_LINK_CHECK_NOTHING);
2053 // Add a ghostpad to the bin so it can proxy to tee.
2054 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(videoTee, "sink"));
2055 gst_element_add_pad(m_videoSinkBin, gst_ghost_pad_new("sink", pad.get()));
2057 // Set the bin as video sink of playbin.
2058 g_object_set(m_playBin, "video-sink", m_videoSinkBin, NULL);
2060 g_object_set(m_playBin, "video-sink", actualVideoSink, NULL);
2063 GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink, "sink"));
2065 g_signal_connect(videoSinkPad.get(), "notify::caps", G_CALLBACK(mediaPlayerPrivateVideoSinkCapsChangedCallback), this);
2067 #if ENABLE(TIZEN_GSTREAMER_AUDIO)
2068 if (m_audioSessionManager)
2069 m_audioSessionManager->registerAudioSessionManager(MM_SESSION_TYPE_SHARE, mediaPlayerPrivateAudioSessionNotifyCallback, player());
2073 #if ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2074 bool MediaPlayerPrivateGStreamer::supportsAcceleratedRendering() const
2076 bool isEmbedVideo = false;
2077 if (m_player->mediaPlayerClient()) {
2078 Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
2079 if (document && document->settings()) {
2080 isEmbedVideo = document->settings()->acceleratedCompositingForVideoEnabled()
2081 && document->settings()->acceleratedCompositingEnabled();
2082 LOG_VERBOSE(Media, "isEmbedVideo: %d", isEmbedVideo);
2086 return isEmbedVideo;
2089 PlatformLayer* MediaPlayerPrivateGStreamer::platformLayer() const
2091 return m_videoLayer->platformLayer();
2094 #if ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2095 void MediaPlayerPrivateGStreamer::paintCurrentFrameInContext(GraphicsContext* context, const IntRect& rect)
2097 m_videoLayer->paintCurrentFrameInContext(context, rect);
2100 void MediaPlayerPrivateGStreamer::xWindowIdPrepared(GstMessage* message)
2104 gst_structure_get_int(message->structure, "video-width", &width);
2105 gst_structure_get_int(message->structure, "video-height", &height);
2107 IntSize size(width, height);
2109 m_videoLayer->setOverlay(size);
2111 #endif // ENABLE(TIZEN_WEBKIT2_TILED_AC_SHARED_PLATFORM_SURFACE)
2112 #endif // ENABLE(TIZEN_ACCELERATED_COMPOSITING) && USE(TIZEN_TEXTURE_MAPPER)
2114 #if ENABLE(TIZEN_WEBKIT2_PROXY)
2115 void MediaPlayerPrivateGStreamer::setProxy(GstElement* source)
2117 SoupSession* session = WebCore::ResourceHandle::defaultSession();
2121 SoupURI* proxyUri = 0;
2122 g_object_get(session, SOUP_SESSION_PROXY_URI, &proxyUri, NULL);
2126 char* proxy = soup_uri_to_string(proxyUri, false);
2127 g_object_set(source, "proxy", proxy, NULL);
2129 soup_uri_free(proxyUri);
2136 #endif // USE(GSTREAMER)