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, 2011, 2012, 2013 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 "GStreamerUtilities.h"
30 #include "GStreamerVersioning.h"
33 #include "MIMETypeRegistry.h"
34 #include "MediaPlayer.h"
35 #include "NotImplemented.h"
36 #include "SecurityOrigin.h"
37 #include "TimeRanges.h"
38 #include "WebKitWebSourceGStreamer.h"
40 #include <gst/pbutils/missing-plugins.h>
42 #include <wtf/gobject/GOwnPtr.h>
43 #include <wtf/text/CString.h>
45 #if ENABLE(VIDEO_TRACK) && defined(GST_API_VERSION_1)
46 #include "InbandTextTrackPrivateGStreamer.h"
47 #include "TextCombinerGStreamer.h"
48 #include "TextSinkGStreamer.h"
51 #ifdef GST_API_VERSION_1
52 #include <gst/audio/streamvolume.h>
54 #include <gst/interfaces/streamvolume.h>
57 // GstPlayFlags flags from playbin2. It is the policy of GStreamer to
58 // not publicly expose element-specific enums. That's why this
59 // GstPlayFlags enum has been copied here.
61 GST_PLAY_FLAG_VIDEO = 0x00000001,
62 GST_PLAY_FLAG_AUDIO = 0x00000002,
63 GST_PLAY_FLAG_TEXT = 0x00000004,
64 GST_PLAY_FLAG_VIS = 0x00000008,
65 GST_PLAY_FLAG_SOFT_VOLUME = 0x00000010,
66 GST_PLAY_FLAG_NATIVE_AUDIO = 0x00000020,
67 GST_PLAY_FLAG_NATIVE_VIDEO = 0x00000040,
68 GST_PLAY_FLAG_DOWNLOAD = 0x00000080,
69 GST_PLAY_FLAG_BUFFERING = 0x000000100
72 // gPercentMax is used when parsing buffering ranges with
73 // gst_query_parse_nth_buffering_range as there was a bug in GStreamer
74 // 0.10 that was using 100 instead of GST_FORMAT_PERCENT_MAX. This was
75 // corrected in 1.0. gst_query_parse_buffering_range worked as
76 // expected with GST_FORMAT_PERCENT_MAX in both cases.
77 #ifdef GST_API_VERSION_1
78 static const char* gPlaybinName = "playbin";
79 static const gint64 gPercentMax = GST_FORMAT_PERCENT_MAX;
81 static const char* gPlaybinName = "playbin2";
82 static const gint64 gPercentMax = 100;
84 // Max interval in seconds to stay in the READY state on manual
85 // state change requests.
86 static const guint gReadyStateTimerInterval = 60;
88 GST_DEBUG_CATEGORY_EXTERN(webkit_media_player_debug);
89 #define GST_CAT_DEFAULT webkit_media_player_debug
95 static gboolean mediaPlayerPrivateMessageCallback(GstBus*, GstMessage* message, MediaPlayerPrivateGStreamer* player)
97 return player->handleMessage(message);
100 static void mediaPlayerPrivateSourceChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
102 player->sourceChanged();
105 static void mediaPlayerPrivateVideoSinkCapsChangedCallback(GObject*, GParamSpec*, MediaPlayerPrivateGStreamer* player)
107 player->videoChanged();
110 static void mediaPlayerPrivateVideoChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
112 player->videoChanged();
115 static void mediaPlayerPrivateAudioChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
117 player->audioChanged();
120 static gboolean mediaPlayerPrivateAudioChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
122 // This is the callback of the timeout source created in ::audioChanged.
123 player->notifyPlayerOfAudio();
127 #ifdef GST_API_VERSION_1
128 static void setAudioStreamPropertiesCallback(GstChildProxy*, GObject* object, gchar*,
129 MediaPlayerPrivateGStreamer* player)
131 static void setAudioStreamPropertiesCallback(GstChildProxy*, GObject* object, MediaPlayerPrivateGStreamer* player)
134 player->setAudioStreamProperties(object);
137 static gboolean mediaPlayerPrivateVideoChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
139 // This is the callback of the timeout source created in ::videoChanged.
140 player->notifyPlayerOfVideo();
144 #if ENABLE(VIDEO_TRACK) && defined(GST_API_VERSION_1)
145 static void mediaPlayerPrivateTextChangedCallback(GObject*, MediaPlayerPrivateGStreamer* player)
147 player->textChanged();
150 static gboolean mediaPlayerPrivateTextChangeTimeoutCallback(MediaPlayerPrivateGStreamer* player)
152 // This is the callback of the timeout source created in ::textChanged.
153 player->notifyPlayerOfText();
157 static GstFlowReturn mediaPlayerPrivateNewTextSampleCallback(GObject*, MediaPlayerPrivateGStreamer* player)
159 player->newTextSample();
164 static gboolean mediaPlayerPrivateReadyStateTimeoutCallback(MediaPlayerPrivateGStreamer* player)
166 // This is the callback of the timeout source created in ::changePipelineState.
167 // Reset pipeline if we are sitting on READY state when timeout is reached
168 player->changePipelineState(GST_STATE_NULL);
172 static void mediaPlayerPrivatePluginInstallerResultFunction(GstInstallPluginsReturn result, gpointer userData)
174 MediaPlayerPrivateGStreamer* player = reinterpret_cast<MediaPlayerPrivateGStreamer*>(userData);
175 player->handlePluginInstallerResult(result);
178 static GstClockTime toGstClockTime(float time)
180 // Extract the integer part of the time (seconds) and the fractional part (microseconds). Attempt to
181 // round the microseconds so no floating point precision is lost and we can perform an accurate seek.
183 float microSeconds = modf(time, &seconds) * 1000000;
185 timeValue.tv_sec = static_cast<glong>(seconds);
186 timeValue.tv_usec = static_cast<glong>(roundf(microSeconds / 10000) * 10000);
187 return GST_TIMEVAL_TO_TIME(timeValue);
190 void MediaPlayerPrivateGStreamer::setAudioStreamProperties(GObject* object)
192 if (g_strcmp0(G_OBJECT_TYPE_NAME(object), "GstPulseSink"))
195 const char* role = m_player->mediaPlayerClient() && m_player->mediaPlayerClient()->mediaPlayerIsVideo()
197 GstStructure* structure = gst_structure_new("stream-properties", "media.role", G_TYPE_STRING, role, NULL);
198 g_object_set(object, "stream-properties", structure, NULL);
199 gst_structure_free(structure);
200 GOwnPtr<gchar> elementName(gst_element_get_name(GST_ELEMENT(object)));
201 LOG_MEDIA_MESSAGE("Set media.role as %s at %s", role, elementName.get());
204 PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivateGStreamer::create(MediaPlayer* player)
206 return adoptPtr(new MediaPlayerPrivateGStreamer(player));
209 void MediaPlayerPrivateGStreamer::registerMediaEngine(MediaEngineRegistrar registrar)
212 registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
215 bool initializeGStreamerAndRegisterWebKitElements()
217 if (!initializeGStreamer())
220 GRefPtr<GstElementFactory> srcFactory = gst_element_factory_find("webkitwebsrc");
222 GST_DEBUG_CATEGORY_INIT(webkit_media_player_debug, "webkitmediaplayer", 0, "WebKit media player");
223 return gst_element_register(0, "webkitwebsrc", GST_RANK_PRIMARY + 100, WEBKIT_TYPE_WEB_SRC);
229 bool MediaPlayerPrivateGStreamer::isAvailable()
231 if (!initializeGStreamerAndRegisterWebKitElements())
234 GRefPtr<GstElementFactory> factory = gst_element_factory_find(gPlaybinName);
238 MediaPlayerPrivateGStreamer::MediaPlayerPrivateGStreamer(MediaPlayer* player)
239 : MediaPlayerPrivateGStreamerBase(player)
242 , m_changingRate(false)
243 , m_endTime(numeric_limits<float>::infinity())
244 , m_isEndReached(false)
245 , m_isStreaming(false)
246 , m_mediaLocations(0)
247 , m_mediaLocationCurrentIndex(0)
248 , m_resetPipeline(false)
251 , m_seekIsPending(false)
252 , m_timeOfOverlappingSeek(-1)
255 , m_errorOccured(false)
257 , m_downloadFinished(false)
258 , m_fillTimer(this, &MediaPlayerPrivateGStreamer::fillTimerFired)
260 , m_bufferingPercentage(0)
261 , m_preload(player->preload())
262 , m_delayingLoad(false)
263 , m_mediaDurationKnown(true)
264 , m_maxTimeLoadedAtLastDidLoadingProgress(0)
265 , m_volumeAndMuteInitialized(false)
268 , m_audioTimerHandler(0)
269 , m_textTimerHandler(0)
270 , m_videoTimerHandler(0)
271 , m_readyTimerHandler(0)
272 , m_webkitAudioSink(0)
274 , m_preservesPitch(false)
275 , m_requestedState(GST_STATE_VOID_PENDING)
276 , m_missingPlugins(false)
280 MediaPlayerPrivateGStreamer::~MediaPlayerPrivateGStreamer()
282 #if ENABLE(VIDEO_TRACK) && defined(GST_API_VERSION_1)
283 for (size_t i = 0; i < m_textTracks.size(); ++i)
284 m_textTracks[i]->disconnect();
286 if (m_fillTimer.isActive())
289 if (m_mediaLocations) {
290 gst_structure_free(m_mediaLocations);
291 m_mediaLocations = 0;
295 g_signal_handlers_disconnect_by_func(G_OBJECT(m_autoAudioSink.get()),
296 reinterpret_cast<gpointer>(setAudioStreamPropertiesCallback), this);
298 if (m_readyTimerHandler)
299 g_source_remove(m_readyTimerHandler);
302 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
304 g_signal_handlers_disconnect_by_func(bus.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateMessageCallback), this);
305 gst_bus_remove_signal_watch(bus.get());
307 g_signal_handlers_disconnect_by_func(m_playBin.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateSourceChangedCallback), this);
308 g_signal_handlers_disconnect_by_func(m_playBin.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateVideoChangedCallback), this);
309 g_signal_handlers_disconnect_by_func(m_playBin.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateAudioChangedCallback), this);
310 #if ENABLE(VIDEO_TRACK) && defined(GST_API_VERSION_1)
311 g_signal_handlers_disconnect_by_func(m_playBin.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateNewTextSampleCallback), this);
312 g_signal_handlers_disconnect_by_func(m_playBin.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateTextChangedCallback), this);
315 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
319 GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink.get(), "sink"));
320 g_signal_handlers_disconnect_by_func(videoSinkPad.get(), reinterpret_cast<gpointer>(mediaPlayerPrivateVideoSinkCapsChangedCallback), this);
322 if (m_videoTimerHandler)
323 g_source_remove(m_videoTimerHandler);
325 if (m_audioTimerHandler)
326 g_source_remove(m_audioTimerHandler);
328 if (m_textTimerHandler)
329 g_source_remove(m_textTimerHandler);
332 void MediaPlayerPrivateGStreamer::load(const String& url)
334 if (!initializeGStreamerAndRegisterWebKitElements())
337 KURL kurl(KURL(), url);
338 String cleanUrl(url);
340 // Clean out everything after file:// url path.
341 if (kurl.isLocalFile())
342 cleanUrl = cleanUrl.substring(0, kurl.pathEnd());
349 m_url = KURL(KURL(), cleanUrl);
350 g_object_set(m_playBin.get(), "uri", cleanUrl.utf8().data(), NULL);
352 INFO_MEDIA_MESSAGE("Load %s", cleanUrl.utf8().data());
354 if (m_preload == MediaPlayer::None) {
355 LOG_MEDIA_MESSAGE("Delaying load.");
356 m_delayingLoad = true;
359 // Reset network and ready states. Those will be set properly once
360 // the pipeline pre-rolled.
361 m_networkState = MediaPlayer::Loading;
362 m_player->networkStateChanged();
363 m_readyState = MediaPlayer::HaveNothing;
364 m_player->readyStateChanged();
365 m_volumeAndMuteInitialized = false;
371 #if ENABLE(MEDIA_SOURCE)
372 void MediaPlayerPrivateGStreamer::load(const String& url, PassRefPtr<MediaSource>)
378 void MediaPlayerPrivateGStreamer::commitLoad()
380 ASSERT(!m_delayingLoad);
381 LOG_MEDIA_MESSAGE("Committing load.");
383 // GStreamer needs to have the pipeline set to a paused state to
384 // start providing anything useful.
385 changePipelineState(GST_STATE_PAUSED);
387 setDownloadBuffering();
391 float MediaPlayerPrivateGStreamer::playbackPosition() const
393 if (m_isEndReached) {
394 // Position queries on a null pipeline return 0. If we're at
395 // the end of the stream the pipeline is null but we want to
396 // report either the seek time or the duration because this is
397 // what the Media element spec expects us to do.
401 return m_mediaDuration;
405 // Position is only available if no async state change is going on and the state is either paused or playing.
406 gint64 position = GST_CLOCK_TIME_NONE;
407 GstQuery* query= gst_query_new_position(GST_FORMAT_TIME);
408 if (gst_element_query(m_playBin.get(), query))
409 gst_query_parse_position(query, 0, &position);
412 if (static_cast<GstClockTime>(position) != GST_CLOCK_TIME_NONE)
413 result = static_cast<double>(position) / GST_SECOND;
414 else if (m_canFallBackToLastFinishedSeekPositon)
417 LOG_MEDIA_MESSAGE("Position %" GST_TIME_FORMAT, GST_TIME_ARGS(position));
419 gst_query_unref(query);
424 bool MediaPlayerPrivateGStreamer::changePipelineState(GstState newState)
428 GstState currentState;
431 gst_element_get_state(m_playBin.get(), ¤tState, &pending, 0);
432 if (currentState == newState || pending == newState) {
433 LOG_MEDIA_MESSAGE("Rejected state change to %s from %s with %s pending", gst_element_state_get_name(newState),
434 gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
438 LOG_MEDIA_MESSAGE("Changing state change to %s from %s with %s pending", gst_element_state_get_name(newState),
439 gst_element_state_get_name(currentState), gst_element_state_get_name(pending));
441 GstStateChangeReturn setStateResult = gst_element_set_state(m_playBin.get(), newState);
442 GstState pausedOrPlaying = newState == GST_STATE_PLAYING ? GST_STATE_PAUSED : GST_STATE_PLAYING;
443 if (currentState != pausedOrPlaying && setStateResult == GST_STATE_CHANGE_FAILURE) {
444 loadingFailed(MediaPlayer::Empty);
448 // Create a timer when entering the READY state so that we can free resources
449 // if we stay for too long on READY.
450 // Also lets remove the timer if we request a state change for any state other than READY.
451 // See also https://bugs.webkit.org/show_bug.cgi?id=117354
452 if (newState == GST_STATE_READY && !m_readyTimerHandler) {
453 m_readyTimerHandler = g_timeout_add_seconds(gReadyStateTimerInterval, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateReadyStateTimeoutCallback), this);
454 } else if (newState != GST_STATE_READY && m_readyTimerHandler) {
455 g_source_remove(m_readyTimerHandler);
456 m_readyTimerHandler = 0;
462 void MediaPlayerPrivateGStreamer::prepareToPlay()
464 m_preload = MediaPlayer::Auto;
465 if (m_delayingLoad) {
466 m_delayingLoad = false;
471 void MediaPlayerPrivateGStreamer::play()
473 if (changePipelineState(GST_STATE_PLAYING)) {
474 m_isEndReached = false;
475 m_delayingLoad = false;
476 m_preload = MediaPlayer::Auto;
477 setDownloadBuffering();
478 LOG_MEDIA_MESSAGE("Play");
482 void MediaPlayerPrivateGStreamer::pause()
484 GstState currentState, pendingState;
485 gst_element_get_state(m_playBin.get(), ¤tState, &pendingState, 0);
486 if (currentState < GST_STATE_PAUSED && pendingState <= GST_STATE_PAUSED)
489 if (changePipelineState(GST_STATE_PAUSED))
490 INFO_MEDIA_MESSAGE("Pause");
493 float MediaPlayerPrivateGStreamer::duration() const
501 // Media duration query failed already, don't attempt new useless queries.
502 if (!m_mediaDurationKnown)
503 return numeric_limits<float>::infinity();
506 return m_mediaDuration;
508 GstFormat timeFormat = GST_FORMAT_TIME;
509 gint64 timeLength = 0;
511 #ifdef GST_API_VERSION_1
512 bool failure = !gst_element_query_duration(m_playBin.get(), timeFormat, &timeLength) || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
514 bool failure = !gst_element_query_duration(m_playBin.get(), &timeFormat, &timeLength) || timeFormat != GST_FORMAT_TIME || static_cast<guint64>(timeLength) == GST_CLOCK_TIME_NONE;
517 LOG_MEDIA_MESSAGE("Time duration query failed for %s", m_url.string().utf8().data());
518 return numeric_limits<float>::infinity();
521 LOG_MEDIA_MESSAGE("Duration: %" GST_TIME_FORMAT, GST_TIME_ARGS(timeLength));
523 m_mediaDuration = static_cast<double>(timeLength) / GST_SECOND;
524 return m_mediaDuration;
525 // FIXME: handle 3.14.9.5 properly
528 float MediaPlayerPrivateGStreamer::currentTime() const
540 // https://bugzilla.gnome.org/show_bug.cgi?id=639941 In GStreamer
541 // 0.10.35 basesink reports wrong duration in case of EOS and
542 // negative playback rate. There's no upstream accepted patch for
543 // this bug yet, hence this temporary workaround.
544 if (m_isEndReached && m_playbackRate < 0)
547 return playbackPosition();
550 void MediaPlayerPrivateGStreamer::seek(float time)
558 INFO_MEDIA_MESSAGE("[Seek] seek attempt to %f secs", time);
560 // Avoid useless seeking.
561 if (time == currentTime())
567 GstClockTime clockTime = toGstClockTime(time);
568 INFO_MEDIA_MESSAGE("[Seek] seeking to %" GST_TIME_FORMAT " (%f)", GST_TIME_ARGS(clockTime), time);
571 m_timeOfOverlappingSeek = time;
572 if (m_seekIsPending) {
579 GstStateChangeReturn getStateResult = gst_element_get_state(m_playBin.get(), &state, 0, 0);
580 if (getStateResult == GST_STATE_CHANGE_FAILURE || getStateResult == GST_STATE_CHANGE_NO_PREROLL) {
581 LOG_MEDIA_MESSAGE("[Seek] cannot seek, current state change is %s", gst_element_state_change_return_get_name(getStateResult));
584 if (getStateResult == GST_STATE_CHANGE_ASYNC || state < GST_STATE_PAUSED || m_isEndReached) {
585 m_seekIsPending = true;
586 if (m_isEndReached) {
587 LOG_MEDIA_MESSAGE("[Seek] reset pipeline");
588 m_resetPipeline = true;
589 changePipelineState(GST_STATE_PAUSED);
593 if (!gst_element_seek(m_playBin.get(), m_player->rate(), GST_FORMAT_TIME, static_cast<GstSeekFlags>(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE),
594 GST_SEEK_TYPE_SET, clockTime, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) {
595 LOG_MEDIA_MESSAGE("[Seek] seeking to %f failed", time);
602 m_isEndReached = false;
605 bool MediaPlayerPrivateGStreamer::paused() const
607 if (m_isEndReached) {
608 LOG_MEDIA_MESSAGE("Ignoring pause at EOS");
613 gst_element_get_state(m_playBin.get(), &state, 0, 0);
614 return state == GST_STATE_PAUSED;
617 bool MediaPlayerPrivateGStreamer::seeking() const
622 void MediaPlayerPrivateGStreamer::videoChanged()
624 if (m_videoTimerHandler)
625 g_source_remove(m_videoTimerHandler);
626 m_videoTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateVideoChangeTimeoutCallback), this);
629 void MediaPlayerPrivateGStreamer::notifyPlayerOfVideo()
631 m_videoTimerHandler = 0;
633 gint videoTracks = 0;
635 g_object_get(m_playBin.get(), "n-video", &videoTracks, NULL);
637 m_hasVideo = videoTracks > 0;
639 m_videoSize = IntSize();
641 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
644 void MediaPlayerPrivateGStreamer::audioChanged()
646 if (m_audioTimerHandler)
647 g_source_remove(m_audioTimerHandler);
648 m_audioTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateAudioChangeTimeoutCallback), this);
651 void MediaPlayerPrivateGStreamer::notifyPlayerOfAudio()
653 m_audioTimerHandler = 0;
655 gint audioTracks = 0;
657 g_object_get(m_playBin.get(), "n-audio", &audioTracks, NULL);
658 m_hasAudio = audioTracks > 0;
659 m_player->mediaPlayerClient()->mediaPlayerEngineUpdated(m_player);
662 #if ENABLE(VIDEO_TRACK) && defined(GST_API_VERSION_1)
663 void MediaPlayerPrivateGStreamer::textChanged()
665 if (m_textTimerHandler)
666 g_source_remove(m_textTimerHandler);
667 m_textTimerHandler = g_timeout_add(0, reinterpret_cast<GSourceFunc>(mediaPlayerPrivateTextChangeTimeoutCallback), this);
670 void MediaPlayerPrivateGStreamer::notifyPlayerOfText()
672 m_textTimerHandler = 0;
676 g_object_get(m_playBin.get(), "n-text", &numTracks, NULL);
678 for (gint i = 0; i < numTracks; ++i) {
680 g_signal_emit_by_name(m_playBin.get(), "get-text-pad", i, &pad, NULL);
683 if (i < static_cast<gint>(m_textTracks.size())) {
684 RefPtr<InbandTextTrackPrivateGStreamer> existingTrack = m_textTracks[i];
685 existingTrack->setIndex(i);
686 if (existingTrack->pad() == pad) {
687 gst_object_unref(pad);
692 RefPtr<InbandTextTrackPrivateGStreamer> track = InbandTextTrackPrivateGStreamer::create(i, adoptGRef(pad));
693 m_textTracks.insert(i, track);
694 m_player->addTextTrack(track.release());
697 while (static_cast<gint>(m_textTracks.size()) > numTracks) {
698 RefPtr<InbandTextTrackPrivateGStreamer> track = m_textTracks.last();
700 m_textTracks.removeLast();
701 m_player->removeTextTrack(track.release());
705 void MediaPlayerPrivateGStreamer::newTextSample()
710 GRefPtr<GstEvent> streamStartEvent = adoptGRef(
711 gst_pad_get_sticky_event(m_textAppSinkPad.get(), GST_EVENT_STREAM_START, 0));
714 g_signal_emit_by_name(m_textAppSink.get(), "pull-sample", &sample, NULL);
717 if (streamStartEvent) {
720 gst_event_parse_stream_start(streamStartEvent.get(), &id);
721 for (size_t i = 0; i < m_textTracks.size(); ++i) {
722 RefPtr<InbandTextTrackPrivateGStreamer> track = m_textTracks[i];
723 if (track->streamId() == id) {
724 track->handleSample(sample);
730 WARN_MEDIA_MESSAGE("Got sample with unknown stream ID.");
732 WARN_MEDIA_MESSAGE("Unable to handle sample with no stream start event.");
733 gst_sample_unref(sample);
737 void MediaPlayerPrivateGStreamer::setRate(float rate)
739 // Avoid useless playback rate update.
740 if (m_playbackRate == rate)
746 gst_element_get_state(m_playBin.get(), &state, &pending, 0);
747 if ((state != GST_STATE_PLAYING && state != GST_STATE_PAUSED)
748 || (pending == GST_STATE_PAUSED))
754 m_playbackRate = rate;
755 m_changingRate = true;
758 changePipelineState(GST_STATE_PAUSED);
762 float currentPosition = static_cast<float>(playbackPosition() * GST_SECOND);
763 GstSeekFlags flags = (GstSeekFlags)(GST_SEEK_FLAG_FLUSH);
767 INFO_MEDIA_MESSAGE("Set Rate to %f", rate);
769 // Mute the sound if the playback rate is too extreme and
770 // audio pitch is not adjusted.
771 mute = (!m_preservesPitch && (rate < 0.8 || rate > 2));
772 start = currentPosition;
773 end = GST_CLOCK_TIME_NONE;
778 // If we are at beginning of media, start from the end to
779 // avoid immediate EOS.
780 if (currentPosition <= 0)
781 end = static_cast<gint64>(duration() * GST_SECOND);
783 end = currentPosition;
786 INFO_MEDIA_MESSAGE("Need to mute audio?: %d", (int) mute);
788 if (!gst_element_seek(m_playBin.get(), rate, GST_FORMAT_TIME, flags,
789 GST_SEEK_TYPE_SET, start,
790 GST_SEEK_TYPE_SET, end))
791 ERROR_MEDIA_MESSAGE("Set rate to %f failed", rate);
793 g_object_set(m_playBin.get(), "mute", mute, NULL);
796 void MediaPlayerPrivateGStreamer::setPreservesPitch(bool preservesPitch)
798 m_preservesPitch = preservesPitch;
801 PassRefPtr<TimeRanges> MediaPlayerPrivateGStreamer::buffered() const
803 RefPtr<TimeRanges> timeRanges = TimeRanges::create();
804 if (m_errorOccured || isLiveStream())
805 return timeRanges.release();
807 #if GST_CHECK_VERSION(0, 10, 31)
808 float mediaDuration(duration());
809 if (!mediaDuration || std::isinf(mediaDuration))
810 return timeRanges.release();
812 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
814 if (!gst_element_query(m_playBin.get(), query)) {
815 gst_query_unref(query);
816 return timeRanges.release();
819 for (guint index = 0; index < gst_query_get_n_buffering_ranges(query); index++) {
820 gint64 rangeStart = 0, rangeStop = 0;
821 if (gst_query_parse_nth_buffering_range(query, index, &rangeStart, &rangeStop))
822 timeRanges->add(static_cast<float>((rangeStart * mediaDuration) / gPercentMax),
823 static_cast<float>((rangeStop * mediaDuration) / gPercentMax));
826 // Fallback to the more general maxTimeLoaded() if no range has
828 if (!timeRanges->length())
829 if (float loaded = maxTimeLoaded())
830 timeRanges->add(0, loaded);
832 gst_query_unref(query);
834 float loaded = maxTimeLoaded();
835 if (!m_errorOccured && !isLiveStream() && loaded > 0)
836 timeRanges->add(0, loaded);
838 return timeRanges.release();
841 gboolean MediaPlayerPrivateGStreamer::handleMessage(GstMessage* message)
844 GOwnPtr<gchar> debug;
845 MediaPlayer::NetworkState error;
846 bool issueError = true;
847 bool attemptNextLocation = false;
848 const GstStructure* structure = gst_message_get_structure(message);
849 GstState requestedState, currentState;
851 m_canFallBackToLastFinishedSeekPositon = false;
854 const gchar* messageTypeName = gst_structure_get_name(structure);
856 // Redirect messages are sent from elements, like qtdemux, to
857 // notify of the new location(s) of the media.
858 if (!g_strcmp0(messageTypeName, "redirect")) {
859 mediaLocationChanged(message);
864 // We ignore state changes from internal elements. They are forwarded to playbin2 anyway.
865 bool messageSourceIsPlaybin = GST_MESSAGE_SRC(message) == reinterpret_cast<GstObject*>(m_playBin.get());
867 LOG_MEDIA_MESSAGE("Message %s received from element %s", GST_MESSAGE_TYPE_NAME(message), GST_MESSAGE_SRC_NAME(message));
868 switch (GST_MESSAGE_TYPE(message)) {
869 case GST_MESSAGE_ERROR:
872 if (m_missingPlugins)
874 gst_message_parse_error(message, &err.outPtr(), &debug.outPtr());
875 ERROR_MEDIA_MESSAGE("Error %d: %s (url=%s)", err->code, err->message, m_url.string().utf8().data());
877 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, "webkit-video.error");
879 error = MediaPlayer::Empty;
880 if (err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND
881 || err->code == GST_STREAM_ERROR_WRONG_TYPE
882 || err->code == GST_STREAM_ERROR_FAILED
883 || err->code == GST_CORE_ERROR_MISSING_PLUGIN
884 || err->code == GST_RESOURCE_ERROR_NOT_FOUND)
885 error = MediaPlayer::FormatError;
886 else if (err->domain == GST_STREAM_ERROR) {
887 // Let the mediaPlayerClient handle the stream error, in
888 // this case the HTMLMediaElement will emit a stalled
890 if (err->code == GST_STREAM_ERROR_TYPE_NOT_FOUND) {
891 ERROR_MEDIA_MESSAGE("Decode error, let the Media element emit a stalled event.");
894 error = MediaPlayer::DecodeError;
895 attemptNextLocation = true;
896 } else if (err->domain == GST_RESOURCE_ERROR)
897 error = MediaPlayer::NetworkError;
899 if (attemptNextLocation)
900 issueError = !loadNextLocation();
902 loadingFailed(error);
904 case GST_MESSAGE_EOS:
907 case GST_MESSAGE_ASYNC_DONE:
908 if (!messageSourceIsPlaybin || m_delayingLoad)
910 asyncStateChangeDone();
912 case GST_MESSAGE_STATE_CHANGED: {
913 if (!messageSourceIsPlaybin || m_delayingLoad)
917 // Construct a filename for the graphviz dot file output.
919 gst_message_parse_state_changed(message, ¤tState, &newState, 0);
920 CString dotFileName = String::format("webkit-video.%s_%s", gst_element_state_get_name(currentState), gst_element_state_get_name(newState)).utf8();
921 GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS(GST_BIN(m_playBin.get()), GST_DEBUG_GRAPH_SHOW_ALL, dotFileName.data());
925 case GST_MESSAGE_BUFFERING:
926 processBufferingStats(message);
928 #ifdef GST_API_VERSION_1
929 case GST_MESSAGE_DURATION_CHANGED:
931 case GST_MESSAGE_DURATION:
933 if (messageSourceIsPlaybin)
936 case GST_MESSAGE_REQUEST_STATE:
937 gst_message_parse_request_state(message, &requestedState);
938 gst_element_get_state(m_playBin.get(), ¤tState, NULL, 250);
939 if (requestedState < currentState) {
940 GOwnPtr<gchar> elementName(gst_element_get_name(GST_ELEMENT(message)));
941 INFO_MEDIA_MESSAGE("Element %s requested state change to %s", elementName.get(),
942 gst_element_state_get_name(requestedState));
943 m_requestedState = requestedState;
944 changePipelineState(requestedState);
947 case GST_MESSAGE_ELEMENT:
948 if (gst_is_missing_plugin_message(message)) {
949 gchar* detail = gst_missing_plugin_message_get_installer_detail(message);
950 gchar* detailArray[2] = {detail, 0};
951 GstInstallPluginsReturn result = gst_install_plugins_async(detailArray, 0, mediaPlayerPrivatePluginInstallerResultFunction, this);
952 m_missingPlugins = result == GST_INSTALL_PLUGINS_STARTED_OK;
957 LOG_MEDIA_MESSAGE("Unhandled GStreamer message type: %s",
958 GST_MESSAGE_TYPE_NAME(message));
964 void MediaPlayerPrivateGStreamer::handlePluginInstallerResult(GstInstallPluginsReturn result)
966 m_missingPlugins = false;
967 if (result == GST_INSTALL_PLUGINS_SUCCESS) {
968 changePipelineState(GST_STATE_READY);
969 changePipelineState(GST_STATE_PAUSED);
973 void MediaPlayerPrivateGStreamer::processBufferingStats(GstMessage* message)
976 const GstStructure *structure = gst_message_get_structure(message);
977 gst_structure_get_int(structure, "buffer-percent", &m_bufferingPercentage);
979 LOG_MEDIA_MESSAGE("[Buffering] Buffering: %d%%.", m_bufferingPercentage);
984 void MediaPlayerPrivateGStreamer::fillTimerFired(Timer<MediaPlayerPrivateGStreamer>*)
986 GstQuery* query = gst_query_new_buffering(GST_FORMAT_PERCENT);
988 if (!gst_element_query(m_playBin.get(), query)) {
989 gst_query_unref(query);
994 gdouble fillStatus = 100.0;
996 gst_query_parse_buffering_range(query, 0, &start, &stop, 0);
997 gst_query_unref(query);
1000 fillStatus = 100.0 * stop / GST_FORMAT_PERCENT_MAX;
1002 LOG_MEDIA_MESSAGE("[Buffering] Download buffer filled up to %f%%", fillStatus);
1004 if (!m_mediaDuration)
1007 // Update maxTimeLoaded only if the media duration is
1008 // available. Otherwise we can't compute it.
1009 if (m_mediaDuration) {
1010 if (fillStatus == 100.0)
1011 m_maxTimeLoaded = m_mediaDuration;
1013 m_maxTimeLoaded = static_cast<float>((fillStatus * m_mediaDuration) / 100.0);
1014 LOG_MEDIA_MESSAGE("[Buffering] Updated maxTimeLoaded: %f", m_maxTimeLoaded);
1017 m_downloadFinished = fillStatus == 100.0;
1018 if (!m_downloadFinished) {
1023 // Media is now fully loaded. It will play even if network
1024 // connection is cut. Buffering is done, remove the fill source
1025 // from the main loop.
1030 float MediaPlayerPrivateGStreamer::maxTimeSeekable() const
1035 LOG_MEDIA_MESSAGE("maxTimeSeekable");
1036 // infinite duration means live stream
1037 if (std::isinf(duration()))
1043 float MediaPlayerPrivateGStreamer::maxTimeLoaded() const
1048 float loaded = m_maxTimeLoaded;
1049 if (m_isEndReached && m_mediaDuration)
1050 loaded = m_mediaDuration;
1051 LOG_MEDIA_MESSAGE("maxTimeLoaded: %f", loaded);
1055 bool MediaPlayerPrivateGStreamer::didLoadingProgress() const
1057 if (!m_playBin || !m_mediaDuration || !totalBytes())
1059 float currentMaxTimeLoaded = maxTimeLoaded();
1060 bool didLoadingProgress = currentMaxTimeLoaded != m_maxTimeLoadedAtLastDidLoadingProgress;
1061 m_maxTimeLoadedAtLastDidLoadingProgress = currentMaxTimeLoaded;
1062 LOG_MEDIA_MESSAGE("didLoadingProgress: %d", didLoadingProgress);
1063 return didLoadingProgress;
1066 unsigned MediaPlayerPrivateGStreamer::totalBytes() const
1071 if (m_totalBytes != -1)
1072 return m_totalBytes;
1077 GstFormat fmt = GST_FORMAT_BYTES;
1079 #ifdef GST_API_VERSION_1
1080 if (gst_element_query_duration(m_source.get(), fmt, &length)) {
1082 if (gst_element_query_duration(m_source.get(), &fmt, &length)) {
1084 INFO_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1085 m_totalBytes = static_cast<unsigned>(length);
1086 m_isStreaming = !length;
1087 return m_totalBytes;
1090 // Fall back to querying the source pads manually.
1091 // See also https://bugzilla.gnome.org/show_bug.cgi?id=638749
1092 GstIterator* iter = gst_element_iterate_src_pads(m_source.get());
1095 #ifdef GST_API_VERSION_1
1096 GValue item = G_VALUE_INIT;
1097 switch (gst_iterator_next(iter, &item)) {
1098 case GST_ITERATOR_OK: {
1099 GstPad* pad = static_cast<GstPad*>(g_value_get_object(&item));
1100 gint64 padLength = 0;
1101 if (gst_pad_query_duration(pad, fmt, &padLength) && padLength > length)
1108 switch (gst_iterator_next(iter, &data)) {
1109 case GST_ITERATOR_OK: {
1110 GRefPtr<GstPad> pad = adoptGRef(GST_PAD_CAST(data));
1111 gint64 padLength = 0;
1112 if (gst_pad_query_duration(pad.get(), &fmt, &padLength) && padLength > length)
1117 case GST_ITERATOR_RESYNC:
1118 gst_iterator_resync(iter);
1120 case GST_ITERATOR_ERROR:
1122 case GST_ITERATOR_DONE:
1127 #ifdef GST_API_VERSION_1
1128 g_value_unset(&item);
1132 gst_iterator_free(iter);
1134 INFO_MEDIA_MESSAGE("totalBytes %" G_GINT64_FORMAT, length);
1135 m_totalBytes = static_cast<unsigned>(length);
1136 m_isStreaming = !length;
1137 return m_totalBytes;
1140 void MediaPlayerPrivateGStreamer::updateAudioSink()
1145 GstElement* sinkPtr = 0;
1147 g_object_get(m_playBin.get(), "audio-sink", &sinkPtr, NULL);
1148 m_webkitAudioSink = adoptGRef(sinkPtr);
1152 GstElement* MediaPlayerPrivateGStreamer::audioSink() const
1154 return m_webkitAudioSink.get();
1157 void MediaPlayerPrivateGStreamer::sourceChanged()
1159 GstElement* srcPtr = 0;
1161 g_object_get(m_playBin.get(), "source", &srcPtr, NULL);
1162 m_source = adoptGRef(srcPtr);
1164 if (WEBKIT_IS_WEB_SRC(m_source.get()))
1165 webKitWebSrcSetMediaPlayer(WEBKIT_WEB_SRC(m_source.get()), m_player);
1168 void MediaPlayerPrivateGStreamer::cancelLoad()
1170 if (m_networkState < MediaPlayer::Loading || m_networkState == MediaPlayer::Loaded)
1174 changePipelineState(GST_STATE_READY);
1177 void MediaPlayerPrivateGStreamer::asyncStateChangeDone()
1179 if (!m_playBin || m_errorOccured)
1183 if (m_seekIsPending)
1186 LOG_MEDIA_MESSAGE("[Seek] seeked to %f", m_seekTime);
1188 if (m_timeOfOverlappingSeek != m_seekTime && m_timeOfOverlappingSeek != -1) {
1189 seek(m_timeOfOverlappingSeek);
1190 m_timeOfOverlappingSeek = -1;
1193 m_timeOfOverlappingSeek = -1;
1195 // The pipeline can still have a pending state. In this case a position query will fail.
1196 // Right now we can use m_seekTime as a fallback.
1197 m_canFallBackToLastFinishedSeekPositon = true;
1204 void MediaPlayerPrivateGStreamer::updateStates()
1212 MediaPlayer::NetworkState oldNetworkState = m_networkState;
1213 MediaPlayer::ReadyState oldReadyState = m_readyState;
1217 GstStateChangeReturn getStateResult = gst_element_get_state(m_playBin.get(), &state, &pending, 250 * GST_NSECOND);
1219 bool shouldUpdatePlaybackState = false;
1220 switch (getStateResult) {
1221 case GST_STATE_CHANGE_SUCCESS: {
1222 LOG_MEDIA_MESSAGE("State: %s, pending: %s", gst_element_state_get_name(state), gst_element_state_get_name(pending));
1224 if (state <= GST_STATE_READY) {
1225 m_resetPipeline = true;
1226 m_mediaDuration = 0;
1228 m_resetPipeline = false;
1232 bool didBuffering = m_buffering;
1234 // Update ready and network states.
1236 case GST_STATE_NULL:
1237 m_readyState = MediaPlayer::HaveNothing;
1238 m_networkState = MediaPlayer::Empty;
1240 case GST_STATE_READY:
1241 // Do not change network/ready states if on EOS and state changed to READY to avoid
1242 // recreating the player on HTMLMediaElement.
1243 if (!m_isEndReached) {
1244 m_readyState = MediaPlayer::HaveMetadata;
1245 m_networkState = MediaPlayer::Empty;
1248 case GST_STATE_PAUSED:
1249 case GST_STATE_PLAYING:
1251 if (m_bufferingPercentage == 100) {
1252 LOG_MEDIA_MESSAGE("[Buffering] Complete.");
1253 m_buffering = false;
1254 m_readyState = MediaPlayer::HaveEnoughData;
1255 m_networkState = m_downloadFinished ? MediaPlayer::Idle : MediaPlayer::Loading;
1257 m_readyState = MediaPlayer::HaveCurrentData;
1258 m_networkState = MediaPlayer::Loading;
1260 } else if (m_downloadFinished) {
1261 m_readyState = MediaPlayer::HaveEnoughData;
1262 m_networkState = MediaPlayer::Loaded;
1264 m_readyState = MediaPlayer::HaveFutureData;
1265 m_networkState = MediaPlayer::Loading;
1270 ASSERT_NOT_REACHED();
1274 // Sync states where needed.
1275 if (state == GST_STATE_PAUSED) {
1276 if (!m_webkitAudioSink)
1279 if (!m_volumeAndMuteInitialized) {
1280 notifyPlayerOfVolumeChange();
1281 notifyPlayerOfMute();
1282 m_volumeAndMuteInitialized = true;
1285 if (didBuffering && !m_buffering && !m_paused) {
1286 LOG_MEDIA_MESSAGE("[Buffering] Restarting playback.");
1287 changePipelineState(GST_STATE_PLAYING);
1289 } else if (state == GST_STATE_PLAYING) {
1292 if (m_buffering && !isLiveStream()) {
1293 LOG_MEDIA_MESSAGE("[Buffering] Pausing stream for buffering.");
1294 changePipelineState(GST_STATE_PAUSED);
1299 if (m_changingRate) {
1300 m_player->rateChanged();
1301 m_changingRate = false;
1304 if (m_requestedState == GST_STATE_PAUSED && state == GST_STATE_PAUSED) {
1305 shouldUpdatePlaybackState = true;
1306 LOG_MEDIA_MESSAGE("Requested state change to %s was completed", gst_element_state_get_name(state));
1311 case GST_STATE_CHANGE_ASYNC:
1312 LOG_MEDIA_MESSAGE("Async: State: %s, pending: %s", gst_element_state_get_name(state), gst_element_state_get_name(pending));
1313 // Change in progress.
1315 case GST_STATE_CHANGE_FAILURE:
1316 LOG_MEDIA_MESSAGE("Failure: State: %s, pending: %s", gst_element_state_get_name(state), gst_element_state_get_name(pending));
1319 case GST_STATE_CHANGE_NO_PREROLL:
1320 LOG_MEDIA_MESSAGE("No preroll: State: %s, pending: %s", gst_element_state_get_name(state), gst_element_state_get_name(pending));
1322 // Live pipelines go in PAUSED without prerolling.
1323 m_isStreaming = true;
1324 setDownloadBuffering();
1326 if (state == GST_STATE_READY)
1327 m_readyState = MediaPlayer::HaveNothing;
1328 else if (state == GST_STATE_PAUSED) {
1329 m_readyState = MediaPlayer::HaveEnoughData;
1331 } else if (state == GST_STATE_PLAYING)
1335 changePipelineState(GST_STATE_PLAYING);
1337 m_networkState = MediaPlayer::Loading;
1340 LOG_MEDIA_MESSAGE("Else : %d", getStateResult);
1344 m_requestedState = GST_STATE_VOID_PENDING;
1346 if (shouldUpdatePlaybackState)
1347 m_player->playbackStateChanged();
1349 if (m_networkState != oldNetworkState) {
1350 LOG_MEDIA_MESSAGE("Network State Changed from %u to %u", oldNetworkState, m_networkState);
1351 m_player->networkStateChanged();
1353 if (m_readyState != oldReadyState) {
1354 LOG_MEDIA_MESSAGE("Ready State Changed from %u to %u", oldReadyState, m_readyState);
1355 m_player->readyStateChanged();
1358 if (m_seekIsPending && getStateResult == GST_STATE_CHANGE_SUCCESS && (state == GST_STATE_PAUSED || state == GST_STATE_PLAYING)) {
1359 LOG_MEDIA_MESSAGE("[Seek] committing pending seek to %f", m_seekTime);
1360 m_seekIsPending = false;
1361 m_seeking = gst_element_seek(m_playBin.get(), m_player->rate(), GST_FORMAT_TIME, static_cast<GstSeekFlags>(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_ACCURATE),
1362 GST_SEEK_TYPE_SET, toGstClockTime(m_seekTime), GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE);
1364 LOG_MEDIA_MESSAGE("[Seek] seeking to %f failed", m_seekTime);
1368 void MediaPlayerPrivateGStreamer::mediaLocationChanged(GstMessage* message)
1370 if (m_mediaLocations)
1371 gst_structure_free(m_mediaLocations);
1373 const GstStructure* structure = gst_message_get_structure(message);
1375 // This structure can contain:
1376 // - both a new-location string and embedded locations structure
1377 // - or only a new-location string.
1378 m_mediaLocations = gst_structure_copy(structure);
1379 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1382 m_mediaLocationCurrentIndex = static_cast<int>(gst_value_list_get_size(locations)) -1;
1388 bool MediaPlayerPrivateGStreamer::loadNextLocation()
1390 if (!m_mediaLocations)
1393 const GValue* locations = gst_structure_get_value(m_mediaLocations, "locations");
1394 const gchar* newLocation = 0;
1397 // Fallback on new-location string.
1398 newLocation = gst_structure_get_string(m_mediaLocations, "new-location");
1404 if (m_mediaLocationCurrentIndex < 0) {
1405 m_mediaLocations = 0;
1409 const GValue* location = gst_value_list_get_value(locations,
1410 m_mediaLocationCurrentIndex);
1411 const GstStructure* structure = gst_value_get_structure(location);
1414 m_mediaLocationCurrentIndex--;
1418 newLocation = gst_structure_get_string(structure, "new-location");
1422 // Found a candidate. new-location is not always an absolute url
1423 // though. We need to take the base of the current url and
1424 // append the value of new-location to it.
1425 KURL baseUrl = gst_uri_is_valid(newLocation) ? KURL() : m_url;
1426 KURL newUrl = KURL(baseUrl, newLocation);
1428 RefPtr<SecurityOrigin> securityOrigin = SecurityOrigin::create(m_url);
1429 if (securityOrigin->canRequest(newUrl)) {
1430 INFO_MEDIA_MESSAGE("New media url: %s", newUrl.string().utf8().data());
1432 // Reset player states.
1433 m_networkState = MediaPlayer::Loading;
1434 m_player->networkStateChanged();
1435 m_readyState = MediaPlayer::HaveNothing;
1436 m_player->readyStateChanged();
1438 // Reset pipeline state.
1439 m_resetPipeline = true;
1440 changePipelineState(GST_STATE_READY);
1443 gst_element_get_state(m_playBin.get(), &state, 0, 0);
1444 if (state <= GST_STATE_READY) {
1445 // Set the new uri and start playing.
1446 g_object_set(m_playBin.get(), "uri", newUrl.string().utf8().data(), NULL);
1448 changePipelineState(GST_STATE_PLAYING);
1452 INFO_MEDIA_MESSAGE("Not allowed to load new media location: %s", newUrl.string().utf8().data());
1454 m_mediaLocationCurrentIndex--;
1458 void MediaPlayerPrivateGStreamer::loadStateChanged()
1463 void MediaPlayerPrivateGStreamer::timeChanged()
1466 m_player->timeChanged();
1469 void MediaPlayerPrivateGStreamer::didEnd()
1471 // Synchronize position and duration values to not confuse the
1472 // HTMLMediaElement. In some cases like reverse playback the
1473 // position is not always reported as 0 for instance.
1474 float now = currentTime();
1475 if (now > 0 && now <= duration() && m_mediaDuration != now) {
1476 m_mediaDurationKnown = true;
1477 m_mediaDuration = now;
1478 m_player->durationChanged();
1481 m_isEndReached = true;
1484 if (!m_player->mediaPlayerClient()->mediaPlayerIsLooping()) {
1486 changePipelineState(GST_STATE_READY);
1487 m_downloadFinished = false;
1491 void MediaPlayerPrivateGStreamer::cacheDuration()
1493 if (m_mediaDuration || !m_mediaDurationKnown)
1496 float newDuration = duration();
1497 if (std::isinf(newDuration)) {
1498 // Only pretend that duration is not available if the the query failed in a stable pipeline state.
1500 if (gst_element_get_state(m_playBin.get(), &state, 0, 0) == GST_STATE_CHANGE_SUCCESS && state > GST_STATE_READY)
1501 m_mediaDurationKnown = false;
1505 m_mediaDuration = newDuration;
1508 void MediaPlayerPrivateGStreamer::durationChanged()
1510 float previousDuration = m_mediaDuration;
1513 // Avoid emiting durationchanged in the case where the previous
1514 // duration was 0 because that case is already handled by the
1515 // HTMLMediaElement.
1516 if (previousDuration && m_mediaDuration != previousDuration)
1517 m_player->durationChanged();
1520 void MediaPlayerPrivateGStreamer::loadingFailed(MediaPlayer::NetworkState error)
1522 m_errorOccured = true;
1523 if (m_networkState != error) {
1524 m_networkState = error;
1525 m_player->networkStateChanged();
1527 if (m_readyState != MediaPlayer::HaveNothing) {
1528 m_readyState = MediaPlayer::HaveNothing;
1529 m_player->readyStateChanged();
1532 // Loading failed, force reset pipeline and remove ready timer.
1533 gst_element_set_state(m_playBin.get(), GST_STATE_NULL);
1534 if (m_readyTimerHandler) {
1535 g_source_remove(m_readyTimerHandler);
1536 m_readyTimerHandler = 0;
1540 static HashSet<String> mimeTypeCache()
1542 initializeGStreamerAndRegisterWebKitElements();
1544 DEFINE_STATIC_LOCAL(HashSet<String>, cache, ());
1545 static bool typeListInitialized = false;
1547 if (typeListInitialized)
1550 const char* mimeTypes[] = {
1552 "application/vnd.apple.mpegurl",
1553 "application/vnd.rn-realmedia",
1554 "application/x-3gp",
1555 "application/x-pn-realaudio",
1576 "audio/x-amr-nb-sh",
1577 "audio/x-amr-wb-sh",
1608 "audio/x-vorbis+ogg",
1612 "audio/x-wavpack-correction",
1639 for (unsigned i = 0; i < (sizeof(mimeTypes) / sizeof(*mimeTypes)); ++i)
1640 cache.add(String(mimeTypes[i]));
1642 typeListInitialized = true;
1646 void MediaPlayerPrivateGStreamer::getSupportedTypes(HashSet<String>& types)
1648 types = mimeTypeCache();
1651 MediaPlayer::SupportsType MediaPlayerPrivateGStreamer::supportsType(const String& type, const String& codecs, const KURL&)
1653 if (type.isNull() || type.isEmpty())
1654 return MediaPlayer::IsNotSupported;
1656 // spec says we should not return "probably" if the codecs string is empty
1657 if (mimeTypeCache().contains(type))
1658 return codecs.isEmpty() ? MediaPlayer::MayBeSupported : MediaPlayer::IsSupported;
1659 return MediaPlayer::IsNotSupported;
1662 void MediaPlayerPrivateGStreamer::setDownloadBuffering()
1668 g_object_get(m_playBin.get(), "flags", &flags, NULL);
1670 // We don't want to stop downloading if we already started it.
1671 if (flags & GST_PLAY_FLAG_DOWNLOAD && m_readyState > MediaPlayer::HaveNothing && !m_resetPipeline)
1674 bool shouldDownload = !isLiveStream() && m_preload == MediaPlayer::Auto;
1675 if (shouldDownload) {
1676 LOG_MEDIA_MESSAGE("Enabling on-disk buffering");
1677 g_object_set(m_playBin.get(), "flags", flags | GST_PLAY_FLAG_DOWNLOAD, NULL);
1678 m_fillTimer.startRepeating(0.2);
1680 LOG_MEDIA_MESSAGE("Disabling on-disk buffering");
1681 g_object_set(m_playBin.get(), "flags", flags & ~GST_PLAY_FLAG_DOWNLOAD, NULL);
1686 void MediaPlayerPrivateGStreamer::setPreload(MediaPlayer::Preload preload)
1688 if (preload == MediaPlayer::Auto && isLiveStream())
1691 m_preload = preload;
1692 setDownloadBuffering();
1694 if (m_delayingLoad && m_preload != MediaPlayer::None) {
1695 m_delayingLoad = false;
1700 void MediaPlayerPrivateGStreamer::createAudioSink()
1702 // Construct audio sink if pitch preserving is enabled.
1703 if (!m_preservesPitch)
1709 GstElement* scale = gst_element_factory_make("scaletempo", 0);
1711 GST_WARNING("Failed to create scaletempo");
1715 GstElement* convert = gst_element_factory_make("audioconvert", 0);
1716 GstElement* resample = gst_element_factory_make("audioresample", 0);
1717 GstElement* sink = gst_element_factory_make("autoaudiosink", 0);
1719 m_autoAudioSink = sink;
1721 g_signal_connect(sink, "child-added", G_CALLBACK(setAudioStreamPropertiesCallback), this);
1723 GstElement* audioSink = gst_bin_new("audio-sink");
1724 gst_bin_add_many(GST_BIN(audioSink), scale, convert, resample, sink, NULL);
1726 if (!gst_element_link_many(scale, convert, resample, sink, NULL)) {
1727 GST_WARNING("Failed to link audio sink elements");
1728 gst_object_unref(audioSink);
1732 GRefPtr<GstPad> pad = adoptGRef(gst_element_get_static_pad(scale, "sink"));
1733 gst_element_add_pad(audioSink, gst_ghost_pad_new("sink", pad.get()));
1735 g_object_set(m_playBin.get(), "audio-sink", audioSink, NULL);
1738 void MediaPlayerPrivateGStreamer::createGSTPlayBin()
1742 // gst_element_factory_make() returns a floating reference so
1743 // we should not adopt.
1744 m_playBin = gst_element_factory_make(gPlaybinName, "play");
1745 setStreamVolumeElement(GST_STREAM_VOLUME(m_playBin.get()));
1747 GRefPtr<GstBus> bus = webkitGstPipelineGetBus(GST_PIPELINE(m_playBin.get()));
1748 gst_bus_add_signal_watch(bus.get());
1749 g_signal_connect(bus.get(), "message", G_CALLBACK(mediaPlayerPrivateMessageCallback), this);
1751 g_object_set(m_playBin.get(), "mute", m_player->muted(), NULL);
1753 g_signal_connect(m_playBin.get(), "notify::source", G_CALLBACK(mediaPlayerPrivateSourceChangedCallback), this);
1754 g_signal_connect(m_playBin.get(), "video-changed", G_CALLBACK(mediaPlayerPrivateVideoChangedCallback), this);
1755 g_signal_connect(m_playBin.get(), "audio-changed", G_CALLBACK(mediaPlayerPrivateAudioChangedCallback), this);
1756 #if ENABLE(VIDEO_TRACK) && defined(GST_API_VERSION_1)
1757 if (webkitGstCheckVersion(1, 1, 2)) {
1758 g_signal_connect(m_playBin.get(), "text-changed", G_CALLBACK(mediaPlayerPrivateTextChangedCallback), this);
1760 GstElement* textCombiner = webkitTextCombinerNew();
1761 ASSERT(textCombiner);
1762 g_object_set(m_playBin.get(), "text-stream-combiner", textCombiner, NULL);
1764 m_textAppSink = webkitTextSinkNew();
1765 ASSERT(m_textAppSink);
1767 m_textAppSinkPad = adoptGRef(gst_element_get_static_pad(m_textAppSink.get(), "sink"));
1768 ASSERT(m_textAppSinkPad);
1770 g_object_set(m_textAppSink.get(), "emit-signals", true, "enable-last-sample", false, "caps", gst_caps_new_empty_simple("text/vtt"), NULL);
1771 g_signal_connect(m_textAppSink.get(), "new-sample", G_CALLBACK(mediaPlayerPrivateNewTextSampleCallback), this);
1773 g_object_set(m_playBin.get(), "text-sink", m_textAppSink.get(), NULL);
1777 GstElement* videoElement = createVideoSink(m_playBin.get());
1779 g_object_set(m_playBin.get(), "video-sink", videoElement, NULL);
1781 GRefPtr<GstPad> videoSinkPad = adoptGRef(gst_element_get_static_pad(m_webkitVideoSink.get(), "sink"));
1783 g_signal_connect(videoSinkPad.get(), "notify::caps", G_CALLBACK(mediaPlayerPrivateVideoSinkCapsChangedCallback), this);
1788 void MediaPlayerPrivateGStreamer::simulateAudioInterruption()
1790 GstMessage* message = gst_message_new_request_state(GST_OBJECT(m_playBin.get()), GST_STATE_PAUSED);
1791 gst_element_post_message(m_playBin.get(), message);
1796 #endif // USE(GSTREAMER)