3 /* note: this requires gstreamer 0.10.x and a big list of plugins. */
4 /* it's currently hardcoded to use a big-endian alsasink as sink. */
5 #include <lib/base/eerror.h>
6 #include <lib/base/object.h>
7 #include <lib/base/ebase.h>
9 #include <lib/service/servicemp3.h>
10 #include <lib/service/service.h>
11 #include <lib/components/file_eraser.h>
12 #include <lib/base/init_num.h>
13 #include <lib/base/init.h>
15 #include <gst/pbutils/missing-plugins.h>
18 #include <lib/gui/esubtitle.h>
20 #ifndef GST_SEEK_FLAG_SKIP
21 #warning Compiling for legacy gstreamer, things will break
22 #define GST_SEEK_FLAG_SKIP 0
23 #define GST_TAG_HOMEPAGE ""
28 eServiceFactoryMP3::eServiceFactoryMP3()
30 ePtr<eServiceCenter> sc;
32 eServiceCenter::getPrivInstance(sc);
35 std::list<std::string> extensions;
36 extensions.push_back("mp2");
37 extensions.push_back("mp3");
38 extensions.push_back("ogg");
39 extensions.push_back("mpg");
40 extensions.push_back("vob");
41 extensions.push_back("wav");
42 extensions.push_back("wave");
43 extensions.push_back("mkv");
44 extensions.push_back("avi");
45 extensions.push_back("divx");
46 extensions.push_back("dat");
47 extensions.push_back("flac");
48 extensions.push_back("mp4");
49 extensions.push_back("mov");
50 extensions.push_back("m4a");
51 extensions.push_back("m2ts");
52 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
55 m_service_info = new eStaticServiceMP3Info();
58 eServiceFactoryMP3::~eServiceFactoryMP3()
60 ePtr<eServiceCenter> sc;
62 eServiceCenter::getPrivInstance(sc);
64 sc->removeServiceFactory(eServiceFactoryMP3::id);
67 DEFINE_REF(eServiceFactoryMP3)
70 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
73 ptr = new eServiceMP3(ref);
77 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
83 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
89 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
95 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
97 DECLARE_REF(eMP3ServiceOfflineOperations);
98 eServiceReference m_ref;
100 eMP3ServiceOfflineOperations(const eServiceReference &ref);
102 RESULT deleteFromDisk(int simulate);
103 RESULT getListOfFilenames(std::list<std::string> &);
107 DEFINE_REF(eMP3ServiceOfflineOperations);
109 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
113 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
119 std::list<std::string> res;
120 if (getListOfFilenames(res))
123 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
125 eDebug("FATAL !! can't get background file eraser");
127 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
129 eDebug("Removing %s...", i->c_str());
131 eraser->erase(i->c_str());
133 ::unlink(i->c_str());
140 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
143 res.push_back(m_ref.path);
147 RESULT eMP3ServiceOfflineOperations::reindex()
153 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
155 ptr = new eMP3ServiceOfflineOperations(ref);
159 // eStaticServiceMP3Info
162 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
163 // about unopened files.
165 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
166 // should have a database backend where ID3-files etc. are cached.
167 // this would allow listing the mp3 database based on certain filters.
169 DEFINE_REF(eStaticServiceMP3Info)
171 eStaticServiceMP3Info::eStaticServiceMP3Info()
175 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
177 if ( ref.name.length() )
181 size_t last = ref.path.rfind('/');
182 if (last != std::string::npos)
183 name = ref.path.substr(last+1);
190 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
197 eServiceMP3::eServiceMP3(eServiceReference ref)
198 :m_ref(ref), m_pump(eApp, 1)
200 m_seekTimeout = eTimer::create(eApp);
201 m_subtitle_sync_timer = eTimer::create(eApp);
203 m_currentAudioStream = 0;
204 m_currentSubtitleStream = 0;
205 m_subtitle_widget = 0;
206 m_currentTrickRatio = 0;
208 m_buffer_size = 1*1024*1024;
209 CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
210 CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
211 CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
212 m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
215 eDebug("eServiceMP3::construct!");
217 const char *filename = m_ref.path.c_str();
218 const char *ext = strrchr(filename, '.');
222 sourceStream sourceinfo;
223 sourceinfo.is_video = FALSE;
224 sourceinfo.audiotype = atUnknown;
225 if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
227 sourceinfo.containertype = ctMPEGPS;
228 sourceinfo.is_video = TRUE;
230 else if ( strcasecmp(ext, ".ts") == 0 )
232 sourceinfo.containertype = ctMPEGTS;
233 sourceinfo.is_video = TRUE;
235 else if ( strcasecmp(ext, ".mkv") == 0 )
237 sourceinfo.containertype = ctMKV;
238 sourceinfo.is_video = TRUE;
240 else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
242 sourceinfo.containertype = ctAVI;
243 sourceinfo.is_video = TRUE;
245 else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0)
247 sourceinfo.containertype = ctMP4;
248 sourceinfo.is_video = TRUE;
250 else if ( strcasecmp(ext, ".m4a") == 0 )
252 sourceinfo.containertype = ctMP4;
253 sourceinfo.audiotype = atAAC;
255 else if ( strcasecmp(ext, ".mp3") == 0 )
256 sourceinfo.audiotype = atMP3;
257 else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
258 sourceinfo.containertype = ctCDA;
259 if ( strcasecmp(ext, ".dat") == 0 )
261 sourceinfo.containertype = ctVCD;
262 sourceinfo.is_video = TRUE;
264 if ( (strncmp(filename, "http://", 7)) == 0 || (strncmp(filename, "udp://", 6)) == 0 || (strncmp(filename, "rtp://", 6)) == 0 || (strncmp(filename, "https://", 8)) == 0 || (strncmp(filename, "mms://", 6)) == 0 || (strncmp(filename, "rtsp://", 7)) == 0 )
265 sourceinfo.is_streaming = TRUE;
269 if ( sourceinfo.is_streaming )
271 uri = g_strdup_printf ("%s", filename);
273 else if ( sourceinfo.containertype == ctCDA )
275 int i_track = atoi(filename+18);
276 uri = g_strdup_printf ("cdda://%i", i_track);
278 else if ( sourceinfo.containertype == ctVCD )
280 int fd = open(filename,O_RDONLY);
282 int ret = read(fd, tmp, 128*1024);
284 if ( ret == -1 ) // this is a "REAL" VCD
285 uri = g_strdup_printf ("vcd://");
287 uri = g_strdup_printf ("file://%s", filename);
291 uri = g_strdup_printf ("file://%s", filename);
293 eDebug("eServiceMP3::playbin2 uri=%s", uri);
295 m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
297 m_error_message = "failed to create GStreamer pipeline!\n";
299 g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
301 int flags = 0x47; // ( == GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_NATIVE_VIDEO | GST_PLAY_FLAG_TEXT )
302 g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
306 GstElement *subsink = gst_element_factory_make("appsink", "subtitle_sink");
308 eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-appsink");
311 g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
312 g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
317 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), gstBusSyncHandler, this);
318 char srt_filename[strlen(filename)+1];
319 strncpy(srt_filename,filename,strlen(filename)-3);
320 srt_filename[strlen(filename)-3]='\0';
321 strcat(srt_filename, "srt");
323 if (stat(srt_filename, &buffer) == 0)
325 std::string suburi = "file://" + (std::string)srt_filename;
326 eDebug("eServiceMP3::subtitle uri: %s",suburi.c_str());
327 g_object_set (G_OBJECT (m_gst_playbin), "suburi", suburi.c_str(), NULL);
330 subs.language_code = std::string("und");
331 m_subtitleStreams.push_back(subs);
335 m_event((iPlayableService*)this, evUser+12);
338 gst_object_unref(GST_OBJECT(m_gst_playbin));
340 eDebug("eServiceMP3::sorry, can't play: %s",m_error_message.c_str());
344 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
345 setBufferSize(m_buffer_size);
348 eServiceMP3::~eServiceMP3()
350 delete m_subtitle_widget;
351 if (m_state == stRunning)
355 gst_tag_list_free(m_stream_tags);
359 gst_object_unref (GST_OBJECT (m_gst_playbin));
360 eDebug("eServiceMP3::destruct!");
364 DEFINE_REF(eServiceMP3);
366 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
368 connection = new eConnection((iPlayableService*)this, m_event.connect(event));
372 RESULT eServiceMP3::start()
374 ASSERT(m_state == stIdle);
379 eDebug("eServiceMP3::starting pipeline");
380 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
382 m_event(this, evStart);
386 RESULT eServiceMP3::stop()
388 ASSERT(m_state != stIdle);
389 if (m_state == stStopped)
391 eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
392 gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
397 RESULT eServiceMP3::setTarget(int target)
402 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
408 RESULT eServiceMP3::setSlowMotion(int ratio)
412 eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
413 return trickSeek(1/(float)ratio);
416 RESULT eServiceMP3::setFastForward(int ratio)
418 eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
419 return trickSeek(ratio);
422 void eServiceMP3::seekTimeoutCB()
425 getPlayPosition(ppos);
427 ppos += 90000*m_currentTrickRatio;
432 m_seekTimeout->stop();
438 m_seekTimeout->stop();
445 RESULT eServiceMP3::pause()
447 if (!m_gst_playbin || m_state != stRunning)
449 GstStateChangeReturn res = gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
450 if (res == GST_STATE_CHANGE_ASYNC)
453 getPlayPosition(ppos);
459 RESULT eServiceMP3::unpause()
461 m_subtitle_pages.clear();
462 if (!m_gst_playbin || m_state != stRunning)
465 GstStateChangeReturn res;
466 res = gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
470 /* iSeekableService */
471 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
477 RESULT eServiceMP3::getLength(pts_t &pts)
481 if (m_state != stRunning)
484 GstFormat fmt = GST_FORMAT_TIME;
487 if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
489 /* len is in nanoseconds. we have 90 000 pts per second. */
495 RESULT eServiceMP3::seekTo(pts_t to)
500 /* convert pts to nanoseconds */
501 gint64 time_nanoseconds = to * 11111LL;
502 if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
503 GST_SEEK_TYPE_SET, time_nanoseconds,
504 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
506 eDebug("eServiceMP3::seekTo failed");
510 m_subtitle_pages.clear();
511 eSingleLocker l(m_subs_to_pull_lock);
517 RESULT eServiceMP3::trickSeek(gdouble ratio)
522 return seekRelative(0, 0);
526 flags = GST_SEEK_FLAG_NONE;
527 flags |= GstSeekFlags (GST_SEEK_FLAG_FLUSH);
528 // flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
529 flags |= GstSeekFlags (GST_SEEK_FLAG_KEY_UNIT);
530 // flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
531 // flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
533 GstFormat fmt = GST_FORMAT_TIME;
535 gst_element_query_duration(m_gst_playbin, &fmt, &len);
536 gst_element_query_position(m_gst_playbin, &fmt, &pos);
540 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
542 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
546 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, GST_SEEK_FLAG_SKIP|GST_SEEK_FLAG_FLUSH, GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_NONE, -1);
549 if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
551 eDebug("eServiceMP3::trickSeek failed");
559 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
565 getPlayPosition(ppos);
566 ppos += to * direction;
574 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
576 GstFormat fmt = GST_FORMAT_TIME;
583 if (m_state != stRunning)
586 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
589 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
594 gchar *name = gst_element_get_name(sink);
595 gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
598 if (use_get_decoder_time)
599 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
601 gst_object_unref(sink);
603 if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
604 eDebug("gst_element_query_position failed in getPlayPosition");
608 /* pos is in nanoseconds. we have 90 000 pts per second. */
613 RESULT eServiceMP3::setTrickmode(int trick)
615 /* trickmode is not yet supported by our dvbmediasinks. */
619 RESULT eServiceMP3::isCurrentlySeekable()
624 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
630 RESULT eServiceMP3::getName(std::string &name)
632 std::string title = m_ref.getName();
636 size_t n = name.rfind('/');
637 if (n != std::string::npos)
638 name = name.substr(n + 1);
646 int eServiceMP3::getInfo(int w)
648 const gchar *tag = 0;
652 case sServiceref: return m_ref;
653 case sVideoHeight: return m_height;
654 case sVideoWidth: return m_width;
655 case sFrameRate: return m_framerate;
656 case sProgressive: return m_progressive;
657 case sAspect: return m_aspect;
661 case sTagTitleSortname:
662 case sTagArtistSortname:
663 case sTagAlbumSortname:
668 case sTagExtendedComment:
671 case sTagDescription:
674 case sTagOrganization:
676 case sTagCopyrightURI:
684 case sTagLanguageCode:
686 case sTagChannelMode:
693 case sTagReferenceLevel:
694 case sTagBeatsPerMinute:
696 case sTagPreviewImage:
698 return resIsPyObject;
699 case sTagTrackNumber:
700 tag = GST_TAG_TRACK_NUMBER;
703 tag = GST_TAG_TRACK_COUNT;
705 case sTagAlbumVolumeNumber:
706 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
708 case sTagAlbumVolumeCount:
709 tag = GST_TAG_ALBUM_VOLUME_COUNT;
712 tag = GST_TAG_BITRATE;
714 case sTagNominalBitrate:
715 tag = GST_TAG_NOMINAL_BITRATE;
717 case sTagMinimumBitrate:
718 tag = GST_TAG_MINIMUM_BITRATE;
720 case sTagMaximumBitrate:
721 tag = GST_TAG_MAXIMUM_BITRATE;
724 tag = GST_TAG_SERIAL;
726 case sTagEncoderVersion:
727 tag = GST_TAG_ENCODER_VERSION;
736 if (!m_stream_tags || !tag)
740 if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
746 std::string eServiceMP3::getInfoString(int w)
748 if ( !m_stream_tags && w < sUser && w > 26 )
750 const gchar *tag = 0;
757 tag = GST_TAG_ARTIST;
762 case sTagTitleSortname:
763 tag = GST_TAG_TITLE_SORTNAME;
765 case sTagArtistSortname:
766 tag = GST_TAG_ARTIST_SORTNAME;
768 case sTagAlbumSortname:
769 tag = GST_TAG_ALBUM_SORTNAME;
773 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
776 g_date_strftime (res, sizeof(res), "%Y-%M-%D", date);
777 return (std::string)res;
781 tag = GST_TAG_COMPOSER;
787 tag = GST_TAG_COMMENT;
789 case sTagExtendedComment:
790 tag = GST_TAG_EXTENDED_COMMENT;
793 tag = GST_TAG_LOCATION;
796 tag = GST_TAG_HOMEPAGE;
798 case sTagDescription:
799 tag = GST_TAG_DESCRIPTION;
802 tag = GST_TAG_VERSION;
807 case sTagOrganization:
808 tag = GST_TAG_ORGANIZATION;
811 tag = GST_TAG_COPYRIGHT;
813 case sTagCopyrightURI:
814 tag = GST_TAG_COPYRIGHT_URI;
817 tag = GST_TAG_CONTACT;
820 tag = GST_TAG_LICENSE;
823 tag = GST_TAG_LICENSE_URI;
829 tag = GST_TAG_AUDIO_CODEC;
832 tag = GST_TAG_VIDEO_CODEC;
835 tag = GST_TAG_ENCODER;
837 case sTagLanguageCode:
838 tag = GST_TAG_LANGUAGE_CODE;
841 tag = GST_TAG_KEYWORDS;
843 case sTagChannelMode:
844 tag = "channel-mode";
847 return m_error_message;
854 if (gst_tag_list_get_string(m_stream_tags, tag, &value))
856 std::string res = value;
863 PyObject *eServiceMP3::getInfoObject(int w)
865 const gchar *tag = 0;
866 bool isBuffer = false;
870 tag = GST_TAG_TRACK_GAIN;
873 tag = GST_TAG_TRACK_PEAK;
876 tag = GST_TAG_ALBUM_GAIN;
879 tag = GST_TAG_ALBUM_PEAK;
881 case sTagReferenceLevel:
882 tag = GST_TAG_REFERENCE_LEVEL;
884 case sTagBeatsPerMinute:
885 tag = GST_TAG_BEATS_PER_MINUTE;
891 case sTagPreviewImage:
892 tag = GST_TAG_PREVIEW_IMAGE;
896 tag = GST_TAG_ATTACHMENT;
903 if ( !tag || !m_stream_tags )
908 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
912 buffer = gst_value_get_buffer (gv_buffer);
913 pyValue = PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
918 gst_tag_list_get_double(m_stream_tags, tag, &value);
919 pyValue = PyFloat_FromDouble(value);
925 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
931 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
937 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
943 int eServiceMP3::getNumberOfTracks()
945 return m_audioStreams.size();
948 int eServiceMP3::getCurrentTrack()
950 return m_currentAudioStream;
953 RESULT eServiceMP3::selectTrack(unsigned int i)
955 int ret = selectAudioStream(i);
958 getPlayPosition(ppos);
964 int eServiceMP3::selectAudioStream(int i)
967 g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
968 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", ¤t_audio, NULL);
969 if ( current_audio == i )
971 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
972 m_currentAudioStream = i;
978 int eServiceMP3::getCurrentChannel()
983 RESULT eServiceMP3::selectChannel(int i)
985 eDebug("eServiceMP3::selectChannel(%i)",i);
989 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
991 if (i >= m_audioStreams.size())
993 info.m_description = m_audioStreams[i].codec;
994 /* if (m_audioStreams[i].type == atMPEG)
995 info.m_description = "MPEG";
996 else if (m_audioStreams[i].type == atMP3)
997 info.m_description = "MP3";
998 else if (m_audioStreams[i].type == atAC3)
999 info.m_description = "AC3";
1000 else if (m_audioStreams[i].type == atAAC)
1001 info.m_description = "AAC";
1002 else if (m_audioStreams[i].type == atDTS)
1003 info.m_description = "DTS";
1004 else if (m_audioStreams[i].type == atPCM)
1005 info.m_description = "PCM";
1006 else if (m_audioStreams[i].type == atOGG)
1007 info.m_description = "OGG";
1008 else if (m_audioStreams[i].type == atFLAC)
1009 info.m_description = "FLAC";
1011 info.m_description = "???";*/
1012 if (info.m_language.empty())
1013 info.m_language = m_audioStreams[i].language_code;
1017 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1024 source = GST_MESSAGE_SRC(msg);
1025 sourceName = gst_object_get_name(source);
1027 if (gst_message_get_structure(msg))
1029 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1030 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1034 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1036 switch (GST_MESSAGE_TYPE (msg))
1038 case GST_MESSAGE_EOS:
1039 m_event((iPlayableService*)this, evEOF);
1041 case GST_MESSAGE_STATE_CHANGED:
1043 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1046 GstState old_state, new_state;
1047 gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1049 if(old_state == new_state)
1052 eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1054 GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1058 case GST_STATE_CHANGE_NULL_TO_READY:
1061 case GST_STATE_CHANGE_READY_TO_PAUSED:
1064 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1067 g_object_set (G_OBJECT (sink), "max-buffers", 2, NULL);
1068 g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);
1069 g_object_set (G_OBJECT (sink), "async", FALSE, NULL);
1070 g_object_set (G_OBJECT (sink), "emit-signals", TRUE, NULL);
1071 gst_object_unref(sink);
1074 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1077 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1080 case GST_STATE_CHANGE_PAUSED_TO_READY:
1083 case GST_STATE_CHANGE_READY_TO_NULL:
1089 case GST_MESSAGE_ERROR:
1093 gst_message_parse_error (msg, &err, &debug);
1095 eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1096 if ( err->domain == GST_STREAM_ERROR )
1098 eDebug("err->code %d", err->code);
1099 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1101 if ( g_strrstr(sourceName, "videosink") )
1102 m_event((iPlayableService*)this, evUser+11);
1103 else if ( g_strrstr(sourceName, "audiosink") )
1104 m_event((iPlayableService*)this, evUser+10);
1110 case GST_MESSAGE_INFO:
1115 gst_message_parse_info (msg, &inf, &debug);
1117 if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1119 if ( g_strrstr(sourceName, "videosink") )
1120 m_event((iPlayableService*)this, evUser+14);
1125 case GST_MESSAGE_TAG:
1127 GstTagList *tags, *result;
1128 gst_message_parse_tag(msg, &tags);
1130 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1134 gst_tag_list_free(m_stream_tags);
1135 m_stream_tags = result;
1138 const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1141 GstBuffer *buf_image;
1142 buf_image = gst_value_get_buffer (gv_image);
1143 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1144 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1146 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1147 m_event((iPlayableService*)this, evUser+13);
1149 gst_tag_list_free(tags);
1150 m_event((iPlayableService*)this, evUpdatedInfo);
1153 case GST_MESSAGE_ASYNC_DONE:
1155 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1159 gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1161 g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1162 g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1163 g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1165 eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1169 m_audioStreams.clear();
1170 m_subtitleStreams.clear();
1172 for (i = 0; i < n_audio; i++)
1175 gchar *g_codec, *g_lang;
1177 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1178 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1181 GstStructure* str = gst_caps_get_structure(caps, 0);
1183 g_type = gst_structure_get_name(str);
1184 eDebug("AUDIO STRUCT=%s", g_type);
1185 audio.type = gstCheckAudioPad(str);
1186 g_codec = g_strdup(g_type);
1187 g_lang = g_strdup_printf ("und");
1188 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1189 if ( tags && gst_is_tag_list(tags) )
1191 gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1192 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1193 gst_tag_list_free(tags);
1195 audio.language_code = std::string(g_lang);
1196 audio.codec = std::string(g_codec);
1197 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1198 m_audioStreams.push_back(audio);
1201 gst_caps_unref(caps);
1204 for (i = 0; i < n_text; i++)
1209 // g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1210 // GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1211 // GstStructure* str = gst_caps_get_structure(caps, 0);
1212 // g_type = gst_structure_get_name(str);
1213 // g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1214 subtitleStream subs;
1215 subs.type = stPlainText;
1216 g_lang = g_strdup_printf ("und");
1217 if ( tags && gst_is_tag_list(tags) )
1218 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1219 subs.language_code = std::string(g_lang);
1220 eDebug("eServiceMP3::subtitle stream=%i language=%s"/* type=%s*/, i, g_lang/*, g_type*/);
1221 m_subtitleStreams.push_back(subs);
1225 m_event((iPlayableService*)this, evUpdatedEventInfo);
1227 case GST_MESSAGE_ELEMENT:
1229 if ( gst_is_missing_plugin_message(msg) )
1231 gchar *description = gst_missing_plugin_message_get_description(msg);
1234 m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1235 g_free(description);
1236 m_event((iPlayableService*)this, evUser+12);
1239 else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1241 const gchar *eventname = gst_structure_get_name(msgstruct);
1244 if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1246 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1247 gst_structure_get_int (msgstruct, "width", &m_width);
1248 gst_structure_get_int (msgstruct, "height", &m_height);
1249 if (strstr(eventname, "Changed"))
1250 m_event((iPlayableService*)this, evVideoSizeChanged);
1252 else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1254 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1255 if (strstr(eventname, "Changed"))
1256 m_event((iPlayableService*)this, evVideoFramerateChanged);
1258 else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1260 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1261 if (strstr(eventname, "Changed"))
1262 m_event((iPlayableService*)this, evVideoProgressiveChanged);
1268 case GST_MESSAGE_BUFFERING:
1270 GstBufferingMode mode;
1271 gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1272 gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1273 m_event((iPlayableService*)this, evBuffering);
1278 g_free (sourceName);
1281 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1283 eServiceMP3 *_this = (eServiceMP3*)user_data;
1284 _this->m_pump.send(1);
1286 return GST_BUS_PASS;
1289 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1294 if ( gst_structure_has_name (structure, "audio/mpeg"))
1296 gint mpegversion, layer = -1;
1297 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1300 switch (mpegversion) {
1303 gst_structure_get_int (structure, "layer", &layer);
1319 else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1321 else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1323 else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1329 void eServiceMP3::gstPoll(const int &msg)
1331 /* ok, we have a serious problem here. gstBusSyncHandler sends
1332 us the wakup signal, but likely before it was posted.
1333 the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1335 I need to understand the API a bit more to make this work
1339 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1340 GstMessage *message;
1342 while ((message = gst_bus_pop (bus)))
1344 gstBusCall(bus, message);
1345 gst_message_unref (message);
1352 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1354 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1356 eServiceMP3 *_this = (eServiceMP3*)user_data;
1357 eSingleLocker l(_this->m_subs_to_pull_lock);
1358 ++_this->m_subs_to_pull;
1359 _this->m_pump.send(2);
1362 void eServiceMP3::pullSubtitle()
1365 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1368 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1372 eSingleLocker l(m_subs_to_pull_lock);
1375 g_signal_emit_by_name (sink, "pull-buffer", &buffer);
1378 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1379 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1380 size_t len = GST_BUFFER_SIZE(buffer);
1381 unsigned char line[len+1];
1382 memcpy(line, GST_BUFFER_DATA(buffer), len);
1384 eDebug("got new subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1385 ePangoSubtitlePage page;
1386 gRGB rgbcol(0xD0,0xD0,0xD0);
1387 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1388 page.show_pts = buf_pos / 11111L;
1389 page.m_timeout = duration_ns / 1000000;
1390 m_subtitle_pages.push_back(page);
1392 gst_buffer_unref(buffer);
1395 gst_object_unref(sink);
1398 eDebug("no subtitle sink!");
1401 void eServiceMP3::pushSubtitles()
1403 ePangoSubtitlePage page;
1405 while ( !m_subtitle_pages.empty() )
1407 getPlayPosition(running_pts);
1408 page = m_subtitle_pages.front();
1409 gint64 diff_ms = ( page.show_pts - running_pts ) / 90;
1410 eDebug("eServiceMP3::pushSubtitles show_pts = %lld running_pts = %lld diff = %lld", page.show_pts, running_pts, diff_ms);
1413 GstFormat fmt = GST_FORMAT_TIME;
1415 if (gst_element_query_position(m_gst_playbin, &fmt, &now) != -1)
1418 diff_ms = abs((now - running_pts) / 90);
1419 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1420 if (diff_ms > 100000)
1422 eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1423 m_subtitle_sync_timer->start(1000, true);
1428 eDebug("query position for decoder/pipeline check failed!");
1429 eDebug("subtitle to late... drop");
1430 m_subtitle_pages.pop_front();
1432 else if ( diff_ms > 20 )
1434 // eDebug("start recheck timer");
1435 m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1438 else // immediate show
1440 if (m_subtitle_widget)
1441 m_subtitle_widget->setPage(page);
1442 m_subtitle_pages.pop_front();
1445 if (m_subtitle_pages.empty())
1449 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1452 int tuplesize = PyTuple_Size(tuple);
1456 if (!PyTuple_Check(tuple))
1460 entry = PyTuple_GET_ITEM(tuple, 1);
1461 if (!PyInt_Check(entry))
1463 pid = PyInt_AsLong(entry);
1464 entry = PyTuple_GET_ITEM(tuple, 2);
1465 if (!PyInt_Check(entry))
1467 type = PyInt_AsLong(entry);
1469 if (m_currentSubtitleStream != pid)
1471 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1472 m_currentSubtitleStream = pid;
1473 eSingleLocker l(m_subs_to_pull_lock);
1475 m_subtitle_pages.clear();
1478 m_subtitle_widget = 0;
1479 m_subtitle_widget = new eSubtitleWidget(parent);
1480 m_subtitle_widget->resize(parent->size()); /* full size */
1482 g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1484 eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1490 eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1491 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1495 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1497 eDebug("eServiceMP3::disableSubtitles");
1498 m_subtitle_pages.clear();
1499 delete m_subtitle_widget;
1500 m_subtitle_widget = 0;
1504 PyObject *eServiceMP3::getCachedSubtitle()
1506 // eDebug("eServiceMP3::getCachedSubtitle");
1510 PyObject *eServiceMP3::getSubtitleList()
1512 eDebug("eServiceMP3::getSubtitleList");
1514 ePyObject l = PyList_New(0);
1515 int stream_count[sizeof(subtype_t)];
1516 for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1517 stream_count[i] = 0;
1519 for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1521 subtype_t type = IterSubtitleStream->type;
1522 ePyObject tuple = PyTuple_New(5);
1523 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1524 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1525 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1526 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1527 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1528 PyList_Append(l, tuple);
1530 stream_count[type]++;
1535 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1541 PyObject *eServiceMP3::getBufferCharge()
1543 ePyObject tuple = PyTuple_New(5);
1544 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1545 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1546 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1547 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1548 PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1552 int eServiceMP3::setBufferSize(int size)
1554 m_buffer_size = size;
1555 g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1561 #warning gstreamer not available, not building media player