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> &);
106 DEFINE_REF(eMP3ServiceOfflineOperations);
108 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
112 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
118 std::list<std::string> res;
119 if (getListOfFilenames(res))
122 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
124 eDebug("FATAL !! can't get background file eraser");
126 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
128 eDebug("Removing %s...", i->c_str());
130 eraser->erase(i->c_str());
132 ::unlink(i->c_str());
139 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
142 res.push_back(m_ref.path);
147 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
149 ptr = new eMP3ServiceOfflineOperations(ref);
153 // eStaticServiceMP3Info
156 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
157 // about unopened files.
159 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
160 // should have a database backend where ID3-files etc. are cached.
161 // this would allow listing the mp3 database based on certain filters.
163 DEFINE_REF(eStaticServiceMP3Info)
165 eStaticServiceMP3Info::eStaticServiceMP3Info()
169 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
171 if ( ref.name.length() )
175 size_t last = ref.path.rfind('/');
176 if (last != std::string::npos)
177 name = ref.path.substr(last+1);
184 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
191 eServiceMP3::eServiceMP3(eServiceReference ref)
192 :m_ref(ref), m_pump(eApp, 1)
194 m_seekTimeout = eTimer::create(eApp);
195 m_subtitle_sync_timer = eTimer::create(eApp);
197 m_currentAudioStream = 0;
198 m_currentSubtitleStream = 0;
199 m_subtitle_widget = 0;
200 m_currentTrickRatio = 0;
202 m_buffer_size = 1*1024*1024;
203 CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
204 CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
205 CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
206 m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
209 eDebug("eServiceMP3::construct!");
211 const char *filename = m_ref.path.c_str();
212 const char *ext = strrchr(filename, '.');
216 sourceStream sourceinfo;
217 sourceinfo.is_video = FALSE;
218 sourceinfo.audiotype = atUnknown;
219 if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
221 sourceinfo.containertype = ctMPEGPS;
222 sourceinfo.is_video = TRUE;
224 else if ( strcasecmp(ext, ".ts") == 0 )
226 sourceinfo.containertype = ctMPEGTS;
227 sourceinfo.is_video = TRUE;
229 else if ( strcasecmp(ext, ".mkv") == 0 )
231 sourceinfo.containertype = ctMKV;
232 sourceinfo.is_video = TRUE;
234 else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
236 sourceinfo.containertype = ctAVI;
237 sourceinfo.is_video = TRUE;
239 else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0)
241 sourceinfo.containertype = ctMP4;
242 sourceinfo.is_video = TRUE;
244 else if ( strcasecmp(ext, ".m4a") == 0 )
246 sourceinfo.containertype = ctMP4;
247 sourceinfo.audiotype = atAAC;
249 else if ( strcasecmp(ext, ".mp3") == 0 )
250 sourceinfo.audiotype = atMP3;
251 else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
252 sourceinfo.containertype = ctCDA;
253 if ( strcasecmp(ext, ".dat") == 0 )
255 sourceinfo.containertype = ctVCD;
256 sourceinfo.is_video = TRUE;
258 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 )
259 sourceinfo.is_streaming = TRUE;
263 if ( sourceinfo.is_streaming )
265 uri = g_strdup_printf ("%s", filename);
267 else if ( sourceinfo.containertype == ctCDA )
269 int i_track = atoi(filename+18);
270 uri = g_strdup_printf ("cdda://%i", i_track);
272 else if ( sourceinfo.containertype == ctVCD )
274 int fd = open(filename,O_RDONLY);
276 int ret = read(fd, tmp, 128*1024);
278 if ( ret == -1 ) // this is a "REAL" VCD
279 uri = g_strdup_printf ("vcd://");
281 uri = g_strdup_printf ("file://%s", filename);
285 uri = g_strdup_printf ("file://%s", filename);
287 eDebug("eServiceMP3::playbin2 uri=%s", uri);
289 m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
291 m_error_message = "failed to create GStreamer pipeline!\n";
293 g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
295 int flags = 0x47; // ( == GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_NATIVE_VIDEO | GST_PLAY_FLAG_TEXT )
296 g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
300 GstElement *subsink = gst_element_factory_make("appsink", "subtitle_sink");
302 eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-appsink");
305 g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
306 g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
311 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), gstBusSyncHandler, this);
312 char srt_filename[strlen(filename)+1];
313 strncpy(srt_filename,filename,strlen(filename)-3);
314 srt_filename[strlen(filename)-3]='\0';
315 strcat(srt_filename, "srt");
317 if (stat(srt_filename, &buffer) == 0)
319 std::string suburi = "file://" + (std::string)srt_filename;
320 eDebug("eServiceMP3::subtitle uri: %s",suburi.c_str());
321 g_object_set (G_OBJECT (m_gst_playbin), "suburi", suburi.c_str(), NULL);
324 subs.language_code = std::string("und");
325 m_subtitleStreams.push_back(subs);
329 m_event((iPlayableService*)this, evUser+12);
332 gst_object_unref(GST_OBJECT(m_gst_playbin));
334 eDebug("eServiceMP3::sorry, can't play: %s",m_error_message.c_str());
338 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
339 setBufferSize(m_buffer_size);
342 eServiceMP3::~eServiceMP3()
344 delete m_subtitle_widget;
345 if (m_state == stRunning)
349 gst_tag_list_free(m_stream_tags);
353 gst_object_unref (GST_OBJECT (m_gst_playbin));
354 eDebug("eServiceMP3::destruct!");
358 DEFINE_REF(eServiceMP3);
360 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
362 connection = new eConnection((iPlayableService*)this, m_event.connect(event));
366 RESULT eServiceMP3::start()
368 ASSERT(m_state == stIdle);
373 eDebug("eServiceMP3::starting pipeline");
374 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
376 m_event(this, evStart);
380 RESULT eServiceMP3::stop()
382 ASSERT(m_state != stIdle);
383 if (m_state == stStopped)
385 eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
386 gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
391 RESULT eServiceMP3::setTarget(int target)
396 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
402 RESULT eServiceMP3::setSlowMotion(int ratio)
406 eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
407 return trickSeek(1/(float)ratio);
410 RESULT eServiceMP3::setFastForward(int ratio)
412 eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
413 return trickSeek(ratio);
416 void eServiceMP3::seekTimeoutCB()
419 getPlayPosition(ppos);
421 ppos += 90000*m_currentTrickRatio;
426 m_seekTimeout->stop();
432 m_seekTimeout->stop();
439 RESULT eServiceMP3::pause()
441 if (!m_gst_playbin || m_state != stRunning)
443 GstStateChangeReturn res = gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
444 if (res == GST_STATE_CHANGE_ASYNC)
447 getPlayPosition(ppos);
453 RESULT eServiceMP3::unpause()
455 m_subtitle_pages.clear();
456 if (!m_gst_playbin || m_state != stRunning)
459 GstStateChangeReturn res;
460 res = gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
464 /* iSeekableService */
465 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
471 RESULT eServiceMP3::getLength(pts_t &pts)
475 if (m_state != stRunning)
478 GstFormat fmt = GST_FORMAT_TIME;
481 if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
483 /* len is in nanoseconds. we have 90 000 pts per second. */
489 RESULT eServiceMP3::seekTo(pts_t to)
494 /* convert pts to nanoseconds */
495 gint64 time_nanoseconds = to * 11111LL;
496 if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
497 GST_SEEK_TYPE_SET, time_nanoseconds,
498 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
500 eDebug("eServiceMP3::seekTo failed");
504 m_subtitle_pages.clear();
505 eSingleLocker l(m_subs_to_pull_lock);
511 RESULT eServiceMP3::trickSeek(gdouble ratio)
516 return seekRelative(0, 0);
520 flags = GST_SEEK_FLAG_NONE;
521 flags |= GstSeekFlags (GST_SEEK_FLAG_FLUSH);
522 // flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
523 flags |= GstSeekFlags (GST_SEEK_FLAG_KEY_UNIT);
524 // flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
525 // flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
527 GstFormat fmt = GST_FORMAT_TIME;
529 gst_element_query_duration(m_gst_playbin, &fmt, &len);
530 gst_element_query_position(m_gst_playbin, &fmt, &pos);
534 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
536 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
540 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);
543 if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
545 eDebug("eServiceMP3::trickSeek failed");
553 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
559 getPlayPosition(ppos);
560 ppos += to * direction;
568 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
570 GstFormat fmt = GST_FORMAT_TIME;
577 if (m_state != stRunning)
580 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
583 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
588 gchar *name = gst_element_get_name(sink);
589 gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
592 if (use_get_decoder_time)
593 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
595 gst_object_unref(sink);
597 if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
598 eDebug("gst_element_query_position failed in getPlayPosition");
602 /* pos is in nanoseconds. we have 90 000 pts per second. */
607 RESULT eServiceMP3::setTrickmode(int trick)
609 /* trickmode is not yet supported by our dvbmediasinks. */
613 RESULT eServiceMP3::isCurrentlySeekable()
618 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
624 RESULT eServiceMP3::getName(std::string &name)
626 std::string title = m_ref.getName();
630 size_t n = name.rfind('/');
631 if (n != std::string::npos)
632 name = name.substr(n + 1);
640 int eServiceMP3::getInfo(int w)
642 const gchar *tag = 0;
646 case sServiceref: return m_ref;
647 case sVideoHeight: return m_height;
648 case sVideoWidth: return m_width;
649 case sFrameRate: return m_framerate;
650 case sProgressive: return m_progressive;
651 case sAspect: return m_aspect;
655 case sTagTitleSortname:
656 case sTagArtistSortname:
657 case sTagAlbumSortname:
662 case sTagExtendedComment:
665 case sTagDescription:
668 case sTagOrganization:
670 case sTagCopyrightURI:
678 case sTagLanguageCode:
680 case sTagChannelMode:
687 case sTagReferenceLevel:
688 case sTagBeatsPerMinute:
690 case sTagPreviewImage:
692 return resIsPyObject;
693 case sTagTrackNumber:
694 tag = GST_TAG_TRACK_NUMBER;
697 tag = GST_TAG_TRACK_COUNT;
699 case sTagAlbumVolumeNumber:
700 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
702 case sTagAlbumVolumeCount:
703 tag = GST_TAG_ALBUM_VOLUME_COUNT;
706 tag = GST_TAG_BITRATE;
708 case sTagNominalBitrate:
709 tag = GST_TAG_NOMINAL_BITRATE;
711 case sTagMinimumBitrate:
712 tag = GST_TAG_MINIMUM_BITRATE;
714 case sTagMaximumBitrate:
715 tag = GST_TAG_MAXIMUM_BITRATE;
718 tag = GST_TAG_SERIAL;
720 case sTagEncoderVersion:
721 tag = GST_TAG_ENCODER_VERSION;
730 if (!m_stream_tags || !tag)
734 if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
740 std::string eServiceMP3::getInfoString(int w)
742 if ( !m_stream_tags && w < sUser && w > 26 )
744 const gchar *tag = 0;
751 tag = GST_TAG_ARTIST;
756 case sTagTitleSortname:
757 tag = GST_TAG_TITLE_SORTNAME;
759 case sTagArtistSortname:
760 tag = GST_TAG_ARTIST_SORTNAME;
762 case sTagAlbumSortname:
763 tag = GST_TAG_ALBUM_SORTNAME;
767 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
770 g_date_strftime (res, sizeof(res), "%Y-%M-%D", date);
771 return (std::string)res;
775 tag = GST_TAG_COMPOSER;
781 tag = GST_TAG_COMMENT;
783 case sTagExtendedComment:
784 tag = GST_TAG_EXTENDED_COMMENT;
787 tag = GST_TAG_LOCATION;
790 tag = GST_TAG_HOMEPAGE;
792 case sTagDescription:
793 tag = GST_TAG_DESCRIPTION;
796 tag = GST_TAG_VERSION;
801 case sTagOrganization:
802 tag = GST_TAG_ORGANIZATION;
805 tag = GST_TAG_COPYRIGHT;
807 case sTagCopyrightURI:
808 tag = GST_TAG_COPYRIGHT_URI;
811 tag = GST_TAG_CONTACT;
814 tag = GST_TAG_LICENSE;
817 tag = GST_TAG_LICENSE_URI;
823 tag = GST_TAG_AUDIO_CODEC;
826 tag = GST_TAG_VIDEO_CODEC;
829 tag = GST_TAG_ENCODER;
831 case sTagLanguageCode:
832 tag = GST_TAG_LANGUAGE_CODE;
835 tag = GST_TAG_KEYWORDS;
837 case sTagChannelMode:
838 tag = "channel-mode";
841 return m_error_message;
848 if (gst_tag_list_get_string(m_stream_tags, tag, &value))
850 std::string res = value;
857 PyObject *eServiceMP3::getInfoObject(int w)
859 const gchar *tag = 0;
860 bool isBuffer = false;
864 tag = GST_TAG_TRACK_GAIN;
867 tag = GST_TAG_TRACK_PEAK;
870 tag = GST_TAG_ALBUM_GAIN;
873 tag = GST_TAG_ALBUM_PEAK;
875 case sTagReferenceLevel:
876 tag = GST_TAG_REFERENCE_LEVEL;
878 case sTagBeatsPerMinute:
879 tag = GST_TAG_BEATS_PER_MINUTE;
885 case sTagPreviewImage:
886 tag = GST_TAG_PREVIEW_IMAGE;
890 tag = GST_TAG_ATTACHMENT;
897 if ( !tag || !m_stream_tags )
902 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
906 buffer = gst_value_get_buffer (gv_buffer);
907 pyValue = PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
912 gst_tag_list_get_double(m_stream_tags, tag, &value);
913 pyValue = PyFloat_FromDouble(value);
919 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
925 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
931 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
937 int eServiceMP3::getNumberOfTracks()
939 return m_audioStreams.size();
942 int eServiceMP3::getCurrentTrack()
944 return m_currentAudioStream;
947 RESULT eServiceMP3::selectTrack(unsigned int i)
949 int ret = selectAudioStream(i);
952 getPlayPosition(ppos);
958 int eServiceMP3::selectAudioStream(int i)
961 g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
962 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", ¤t_audio, NULL);
963 if ( current_audio == i )
965 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
966 m_currentAudioStream = i;
972 int eServiceMP3::getCurrentChannel()
977 RESULT eServiceMP3::selectChannel(int i)
979 eDebug("eServiceMP3::selectChannel(%i)",i);
983 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
985 if (i >= m_audioStreams.size())
987 info.m_description = m_audioStreams[i].codec;
988 /* if (m_audioStreams[i].type == atMPEG)
989 info.m_description = "MPEG";
990 else if (m_audioStreams[i].type == atMP3)
991 info.m_description = "MP3";
992 else if (m_audioStreams[i].type == atAC3)
993 info.m_description = "AC3";
994 else if (m_audioStreams[i].type == atAAC)
995 info.m_description = "AAC";
996 else if (m_audioStreams[i].type == atDTS)
997 info.m_description = "DTS";
998 else if (m_audioStreams[i].type == atPCM)
999 info.m_description = "PCM";
1000 else if (m_audioStreams[i].type == atOGG)
1001 info.m_description = "OGG";
1002 else if (m_audioStreams[i].type == atFLAC)
1003 info.m_description = "FLAC";
1005 info.m_description = "???";*/
1006 if (info.m_language.empty())
1007 info.m_language = m_audioStreams[i].language_code;
1011 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1018 source = GST_MESSAGE_SRC(msg);
1019 sourceName = gst_object_get_name(source);
1021 if (gst_message_get_structure(msg))
1023 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1024 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1028 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1030 switch (GST_MESSAGE_TYPE (msg))
1032 case GST_MESSAGE_EOS:
1033 m_event((iPlayableService*)this, evEOF);
1035 case GST_MESSAGE_STATE_CHANGED:
1037 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1040 GstState old_state, new_state;
1041 gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1043 if(old_state == new_state)
1046 eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1048 GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1052 case GST_STATE_CHANGE_NULL_TO_READY:
1055 case GST_STATE_CHANGE_READY_TO_PAUSED:
1058 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1061 g_object_set (G_OBJECT (sink), "max-buffers", 2, NULL);
1062 g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);
1063 g_object_set (G_OBJECT (sink), "async", FALSE, NULL);
1064 g_object_set (G_OBJECT (sink), "emit-signals", TRUE, NULL);
1065 gst_object_unref(sink);
1068 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1071 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1074 case GST_STATE_CHANGE_PAUSED_TO_READY:
1077 case GST_STATE_CHANGE_READY_TO_NULL:
1083 case GST_MESSAGE_ERROR:
1087 gst_message_parse_error (msg, &err, &debug);
1089 eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1090 if ( err->domain == GST_STREAM_ERROR )
1092 eDebug("err->code %d", err->code);
1093 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1095 if ( g_strrstr(sourceName, "videosink") )
1096 m_event((iPlayableService*)this, evUser+11);
1097 else if ( g_strrstr(sourceName, "audiosink") )
1098 m_event((iPlayableService*)this, evUser+10);
1104 case GST_MESSAGE_INFO:
1109 gst_message_parse_info (msg, &inf, &debug);
1111 if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1113 if ( g_strrstr(sourceName, "videosink") )
1114 m_event((iPlayableService*)this, evUser+14);
1119 case GST_MESSAGE_TAG:
1121 GstTagList *tags, *result;
1122 gst_message_parse_tag(msg, &tags);
1124 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1128 gst_tag_list_free(m_stream_tags);
1129 m_stream_tags = result;
1132 const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1135 GstBuffer *buf_image;
1136 buf_image = gst_value_get_buffer (gv_image);
1137 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1138 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1140 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1141 m_event((iPlayableService*)this, evUser+13);
1143 gst_tag_list_free(tags);
1144 m_event((iPlayableService*)this, evUpdatedInfo);
1147 case GST_MESSAGE_ASYNC_DONE:
1149 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1153 gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1155 g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1156 g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1157 g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1159 eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1163 m_audioStreams.clear();
1164 m_subtitleStreams.clear();
1166 for (i = 0; i < n_audio; i++)
1169 gchar *g_codec, *g_lang;
1171 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1172 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1175 GstStructure* str = gst_caps_get_structure(caps, 0);
1177 g_type = gst_structure_get_name(str);
1178 eDebug("AUDIO STRUCT=%s", g_type);
1179 audio.type = gstCheckAudioPad(str);
1180 g_codec = g_strdup(g_type);
1181 g_lang = g_strdup_printf ("und");
1182 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1183 if ( tags && gst_is_tag_list(tags) )
1185 gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1186 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1187 gst_tag_list_free(tags);
1189 audio.language_code = std::string(g_lang);
1190 audio.codec = std::string(g_codec);
1191 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1192 m_audioStreams.push_back(audio);
1195 gst_caps_unref(caps);
1198 for (i = 0; i < n_text; i++)
1203 // g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1204 // GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1205 // GstStructure* str = gst_caps_get_structure(caps, 0);
1206 // g_type = gst_structure_get_name(str);
1207 // g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1208 subtitleStream subs;
1209 subs.type = stPlainText;
1210 g_lang = g_strdup_printf ("und");
1211 if ( tags && gst_is_tag_list(tags) )
1212 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1213 subs.language_code = std::string(g_lang);
1214 eDebug("eServiceMP3::subtitle stream=%i language=%s"/* type=%s*/, i, g_lang/*, g_type*/);
1215 m_subtitleStreams.push_back(subs);
1219 m_event((iPlayableService*)this, evUpdatedEventInfo);
1221 case GST_MESSAGE_ELEMENT:
1223 if ( gst_is_missing_plugin_message(msg) )
1225 gchar *description = gst_missing_plugin_message_get_description(msg);
1228 m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1229 g_free(description);
1230 m_event((iPlayableService*)this, evUser+12);
1233 else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1235 const gchar *eventname = gst_structure_get_name(msgstruct);
1238 if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1240 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1241 gst_structure_get_int (msgstruct, "width", &m_width);
1242 gst_structure_get_int (msgstruct, "height", &m_height);
1243 if (strstr(eventname, "Changed"))
1244 m_event((iPlayableService*)this, evVideoSizeChanged);
1246 else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1248 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1249 if (strstr(eventname, "Changed"))
1250 m_event((iPlayableService*)this, evVideoFramerateChanged);
1252 else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1254 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1255 if (strstr(eventname, "Changed"))
1256 m_event((iPlayableService*)this, evVideoProgressiveChanged);
1262 case GST_MESSAGE_BUFFERING:
1264 GstBufferingMode mode;
1265 gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1266 gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1267 m_event((iPlayableService*)this, evBuffering);
1272 g_free (sourceName);
1275 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1277 eServiceMP3 *_this = (eServiceMP3*)user_data;
1278 _this->m_pump.send(1);
1280 return GST_BUS_PASS;
1283 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1288 if ( gst_structure_has_name (structure, "audio/mpeg"))
1290 gint mpegversion, layer = -1;
1291 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1294 switch (mpegversion) {
1297 gst_structure_get_int (structure, "layer", &layer);
1313 else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1315 else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1317 else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1323 void eServiceMP3::gstPoll(const int &msg)
1325 /* ok, we have a serious problem here. gstBusSyncHandler sends
1326 us the wakup signal, but likely before it was posted.
1327 the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1329 I need to understand the API a bit more to make this work
1333 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1334 GstMessage *message;
1336 while ((message = gst_bus_pop (bus)))
1338 gstBusCall(bus, message);
1339 gst_message_unref (message);
1346 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1348 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1350 eServiceMP3 *_this = (eServiceMP3*)user_data;
1351 eSingleLocker l(_this->m_subs_to_pull_lock);
1352 ++_this->m_subs_to_pull;
1353 _this->m_pump.send(2);
1356 void eServiceMP3::pullSubtitle()
1359 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1362 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1366 eSingleLocker l(m_subs_to_pull_lock);
1369 g_signal_emit_by_name (sink, "pull-buffer", &buffer);
1372 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1373 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1374 size_t len = GST_BUFFER_SIZE(buffer);
1375 unsigned char line[len+1];
1376 memcpy(line, GST_BUFFER_DATA(buffer), len);
1378 eDebug("got new subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1379 ePangoSubtitlePage page;
1380 gRGB rgbcol(0xD0,0xD0,0xD0);
1381 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1382 page.show_pts = buf_pos / 11111L;
1383 page.m_timeout = duration_ns / 1000000;
1384 m_subtitle_pages.push_back(page);
1386 gst_buffer_unref(buffer);
1389 gst_object_unref(sink);
1392 eDebug("no subtitle sink!");
1395 void eServiceMP3::pushSubtitles()
1397 ePangoSubtitlePage page;
1399 while ( !m_subtitle_pages.empty() )
1401 getPlayPosition(running_pts);
1402 page = m_subtitle_pages.front();
1403 gint64 diff_ms = ( page.show_pts - running_pts ) / 90;
1404 eDebug("eServiceMP3::pushSubtitles show_pts = %lld running_pts = %lld diff = %lld", page.show_pts, running_pts, diff_ms);
1407 GstFormat fmt = GST_FORMAT_TIME;
1409 if (gst_element_query_position(m_gst_playbin, &fmt, &now) != -1)
1412 diff_ms = abs((now - running_pts) / 90);
1413 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1414 if (diff_ms > 100000)
1416 eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1417 m_subtitle_sync_timer->start(1000, true);
1422 eDebug("query position for decoder/pipeline check failed!");
1423 eDebug("subtitle to late... drop");
1424 m_subtitle_pages.pop_front();
1426 else if ( diff_ms > 20 )
1428 // eDebug("start recheck timer");
1429 m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1432 else // immediate show
1434 if (m_subtitle_widget)
1435 m_subtitle_widget->setPage(page);
1436 m_subtitle_pages.pop_front();
1439 if (m_subtitle_pages.empty())
1443 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1446 int tuplesize = PyTuple_Size(tuple);
1450 if (!PyTuple_Check(tuple))
1454 entry = PyTuple_GET_ITEM(tuple, 1);
1455 if (!PyInt_Check(entry))
1457 pid = PyInt_AsLong(entry);
1458 entry = PyTuple_GET_ITEM(tuple, 2);
1459 if (!PyInt_Check(entry))
1461 type = PyInt_AsLong(entry);
1463 if (m_currentSubtitleStream != pid)
1465 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1466 m_currentSubtitleStream = pid;
1467 eSingleLocker l(m_subs_to_pull_lock);
1469 m_subtitle_pages.clear();
1472 m_subtitle_widget = 0;
1473 m_subtitle_widget = new eSubtitleWidget(parent);
1474 m_subtitle_widget->resize(parent->size()); /* full size */
1476 g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1478 eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1484 eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1485 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1489 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1491 eDebug("eServiceMP3::disableSubtitles");
1492 m_subtitle_pages.clear();
1493 delete m_subtitle_widget;
1494 m_subtitle_widget = 0;
1498 PyObject *eServiceMP3::getCachedSubtitle()
1500 // eDebug("eServiceMP3::getCachedSubtitle");
1504 PyObject *eServiceMP3::getSubtitleList()
1506 eDebug("eServiceMP3::getSubtitleList");
1508 ePyObject l = PyList_New(0);
1509 int stream_count[sizeof(subtype_t)];
1510 for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1511 stream_count[i] = 0;
1513 for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1515 subtype_t type = IterSubtitleStream->type;
1516 ePyObject tuple = PyTuple_New(5);
1517 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1518 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1519 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1520 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1521 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1522 PyList_Append(l, tuple);
1524 stream_count[type]++;
1529 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1535 PyObject *eServiceMP3::getBufferCharge()
1537 ePyObject tuple = PyTuple_New(5);
1538 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1539 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1540 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1541 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1542 PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1546 int eServiceMP3::setBufferSize(int size)
1548 m_buffer_size = size;
1549 g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1555 #warning gstreamer not available, not building media player