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>
22 eServiceFactoryMP3::eServiceFactoryMP3()
24 ePtr<eServiceCenter> sc;
26 eServiceCenter::getPrivInstance(sc);
29 std::list<std::string> extensions;
30 extensions.push_back("mp2");
31 extensions.push_back("mp3");
32 extensions.push_back("ogg");
33 extensions.push_back("mpg");
34 extensions.push_back("vob");
35 extensions.push_back("wav");
36 extensions.push_back("wave");
37 extensions.push_back("mkv");
38 extensions.push_back("avi");
39 extensions.push_back("divx");
40 extensions.push_back("dat");
41 extensions.push_back("flac");
42 extensions.push_back("mp4");
43 extensions.push_back("mov");
44 extensions.push_back("m4a");
45 extensions.push_back("m2ts");
46 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
49 m_service_info = new eStaticServiceMP3Info();
52 eServiceFactoryMP3::~eServiceFactoryMP3()
54 ePtr<eServiceCenter> sc;
56 eServiceCenter::getPrivInstance(sc);
58 sc->removeServiceFactory(eServiceFactoryMP3::id);
61 DEFINE_REF(eServiceFactoryMP3)
64 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
67 ptr = new eServiceMP3(ref);
71 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
77 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
83 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
89 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
91 DECLARE_REF(eMP3ServiceOfflineOperations);
92 eServiceReference m_ref;
94 eMP3ServiceOfflineOperations(const eServiceReference &ref);
96 RESULT deleteFromDisk(int simulate);
97 RESULT getListOfFilenames(std::list<std::string> &);
101 DEFINE_REF(eMP3ServiceOfflineOperations);
103 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
107 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
113 std::list<std::string> res;
114 if (getListOfFilenames(res))
117 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
119 eDebug("FATAL !! can't get background file eraser");
121 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
123 eDebug("Removing %s...", i->c_str());
125 eraser->erase(i->c_str());
127 ::unlink(i->c_str());
134 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
137 res.push_back(m_ref.path);
141 RESULT eMP3ServiceOfflineOperations::reindex()
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 = -1;
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 m_subs_to_pull_handler_id = 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 setBufferSize(m_buffer_size);
341 eServiceMP3::~eServiceMP3()
343 // disconnect subtitle callback
345 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
348 g_signal_handler_disconnect (sink, m_subs_to_pull_handler_id);
349 gst_object_unref(sink);
352 delete m_subtitle_widget;
354 // disconnect sync handler callback
355 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), NULL, NULL);
357 if (m_state == stRunning)
361 gst_tag_list_free(m_stream_tags);
365 gst_object_unref (GST_OBJECT (m_gst_playbin));
366 eDebug("eServiceMP3::destruct!");
370 DEFINE_REF(eServiceMP3);
372 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
374 connection = new eConnection((iPlayableService*)this, m_event.connect(event));
378 RESULT eServiceMP3::start()
380 ASSERT(m_state == stIdle);
385 eDebug("eServiceMP3::starting pipeline");
386 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
389 m_event(this, evStart);
394 RESULT eServiceMP3::stop()
396 ASSERT(m_state != stIdle);
398 if (m_state == stStopped)
401 eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
402 gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
408 RESULT eServiceMP3::setTarget(int target)
413 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
419 RESULT eServiceMP3::setSlowMotion(int ratio)
423 eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
424 return trickSeek(1/(float)ratio);
427 RESULT eServiceMP3::setFastForward(int ratio)
429 eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
430 return trickSeek(ratio);
433 void eServiceMP3::seekTimeoutCB()
436 getPlayPosition(ppos);
438 ppos += 90000*m_currentTrickRatio;
443 m_seekTimeout->stop();
449 m_seekTimeout->stop();
456 RESULT eServiceMP3::pause()
458 if (!m_gst_playbin || m_state != stRunning)
461 gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
466 RESULT eServiceMP3::unpause()
468 if (!m_gst_playbin || m_state != stRunning)
471 gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
476 /* iSeekableService */
477 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
483 RESULT eServiceMP3::getLength(pts_t &pts)
488 if (m_state != stRunning)
491 GstFormat fmt = GST_FORMAT_TIME;
494 if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
496 /* len is in nanoseconds. we have 90 000 pts per second. */
502 RESULT eServiceMP3::seekToImpl(pts_t to)
504 /* convert pts to nanoseconds */
505 gint64 time_nanoseconds = to * 11111LL;
506 if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
507 GST_SEEK_TYPE_SET, time_nanoseconds,
508 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
510 eDebug("eServiceMP3::seekTo failed");
517 RESULT eServiceMP3::seekTo(pts_t to)
522 eSingleLocker l(m_subs_to_pull_lock); // this is needed to dont handle incomming subtitles during seek!
523 if (!(ret = seekToImpl(to)))
525 m_subtitle_pages.clear();
534 RESULT eServiceMP3::trickSeek(gdouble ratio)
539 return seekRelative(0, 0);
543 flags = GST_SEEK_FLAG_NONE;
544 flags |= GST_SEEK_FLAG_FLUSH;
545 // flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
546 flags |= GST_SEEK_FLAG_KEY_UNIT;
547 // flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
548 // flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
550 GstFormat fmt = GST_FORMAT_TIME;
552 gst_element_query_duration(m_gst_playbin, &fmt, &len);
553 gst_element_query_position(m_gst_playbin, &fmt, &pos);
557 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
559 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
563 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_SKIP|GST_SEEK_FLAG_FLUSH), GST_SEEK_TYPE_NONE, -1, GST_SEEK_TYPE_NONE, -1);
566 if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
568 eDebug("eServiceMP3::trickSeek failed");
576 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
582 getPlayPosition(ppos);
583 ppos += to * direction;
591 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
593 GstFormat fmt = GST_FORMAT_TIME;
600 if (m_state != stRunning)
603 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
606 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
611 gchar *name = gst_element_get_name(sink);
612 gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
615 if (use_get_decoder_time)
616 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
618 gst_object_unref(sink);
620 if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
621 eDebug("gst_element_query_position failed in getPlayPosition");
625 /* pos is in nanoseconds. we have 90 000 pts per second. */
630 RESULT eServiceMP3::setTrickmode(int trick)
632 /* trickmode is not yet supported by our dvbmediasinks. */
636 RESULT eServiceMP3::isCurrentlySeekable()
641 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
647 RESULT eServiceMP3::getName(std::string &name)
649 std::string title = m_ref.getName();
653 size_t n = name.rfind('/');
654 if (n != std::string::npos)
655 name = name.substr(n + 1);
663 int eServiceMP3::getInfo(int w)
665 const gchar *tag = 0;
669 case sServiceref: return m_ref;
670 case sVideoHeight: return m_height;
671 case sVideoWidth: return m_width;
672 case sFrameRate: return m_framerate;
673 case sProgressive: return m_progressive;
674 case sAspect: return m_aspect;
678 case sTagTitleSortname:
679 case sTagArtistSortname:
680 case sTagAlbumSortname:
685 case sTagExtendedComment:
688 case sTagDescription:
691 case sTagOrganization:
693 case sTagCopyrightURI:
701 case sTagLanguageCode:
703 case sTagChannelMode:
710 case sTagReferenceLevel:
711 case sTagBeatsPerMinute:
713 case sTagPreviewImage:
715 return resIsPyObject;
716 case sTagTrackNumber:
717 tag = GST_TAG_TRACK_NUMBER;
720 tag = GST_TAG_TRACK_COUNT;
722 case sTagAlbumVolumeNumber:
723 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
725 case sTagAlbumVolumeCount:
726 tag = GST_TAG_ALBUM_VOLUME_COUNT;
729 tag = GST_TAG_BITRATE;
731 case sTagNominalBitrate:
732 tag = GST_TAG_NOMINAL_BITRATE;
734 case sTagMinimumBitrate:
735 tag = GST_TAG_MINIMUM_BITRATE;
737 case sTagMaximumBitrate:
738 tag = GST_TAG_MAXIMUM_BITRATE;
741 tag = GST_TAG_SERIAL;
743 case sTagEncoderVersion:
744 tag = GST_TAG_ENCODER_VERSION;
753 if (!m_stream_tags || !tag)
757 if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
763 std::string eServiceMP3::getInfoString(int w)
765 if ( !m_stream_tags && w < sUser && w > 26 )
767 const gchar *tag = 0;
774 tag = GST_TAG_ARTIST;
779 case sTagTitleSortname:
780 tag = GST_TAG_TITLE_SORTNAME;
782 case sTagArtistSortname:
783 tag = GST_TAG_ARTIST_SORTNAME;
785 case sTagAlbumSortname:
786 tag = GST_TAG_ALBUM_SORTNAME;
790 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
793 g_date_strftime (res, sizeof(res), "%Y-%M-%D", date);
794 return (std::string)res;
798 tag = GST_TAG_COMPOSER;
804 tag = GST_TAG_COMMENT;
806 case sTagExtendedComment:
807 tag = GST_TAG_EXTENDED_COMMENT;
810 tag = GST_TAG_LOCATION;
813 tag = GST_TAG_HOMEPAGE;
815 case sTagDescription:
816 tag = GST_TAG_DESCRIPTION;
819 tag = GST_TAG_VERSION;
824 case sTagOrganization:
825 tag = GST_TAG_ORGANIZATION;
828 tag = GST_TAG_COPYRIGHT;
830 case sTagCopyrightURI:
831 tag = GST_TAG_COPYRIGHT_URI;
834 tag = GST_TAG_CONTACT;
837 tag = GST_TAG_LICENSE;
840 tag = GST_TAG_LICENSE_URI;
846 tag = GST_TAG_AUDIO_CODEC;
849 tag = GST_TAG_VIDEO_CODEC;
852 tag = GST_TAG_ENCODER;
854 case sTagLanguageCode:
855 tag = GST_TAG_LANGUAGE_CODE;
858 tag = GST_TAG_KEYWORDS;
860 case sTagChannelMode:
861 tag = "channel-mode";
864 return m_error_message;
871 if (gst_tag_list_get_string(m_stream_tags, tag, &value))
873 std::string res = value;
880 PyObject *eServiceMP3::getInfoObject(int w)
882 const gchar *tag = 0;
883 bool isBuffer = false;
887 tag = GST_TAG_TRACK_GAIN;
890 tag = GST_TAG_TRACK_PEAK;
893 tag = GST_TAG_ALBUM_GAIN;
896 tag = GST_TAG_ALBUM_PEAK;
898 case sTagReferenceLevel:
899 tag = GST_TAG_REFERENCE_LEVEL;
901 case sTagBeatsPerMinute:
902 tag = GST_TAG_BEATS_PER_MINUTE;
908 case sTagPreviewImage:
909 tag = GST_TAG_PREVIEW_IMAGE;
913 tag = GST_TAG_ATTACHMENT;
922 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
926 buffer = gst_value_get_buffer (gv_buffer);
927 return PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
933 gst_tag_list_get_double(m_stream_tags, tag, &value);
934 return PyFloat_FromDouble(value);
940 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
946 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
952 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
958 int eServiceMP3::getNumberOfTracks()
960 return m_audioStreams.size();
963 int eServiceMP3::getCurrentTrack()
965 if (m_currentAudioStream == -1)
966 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL);
967 return m_currentAudioStream;
970 RESULT eServiceMP3::selectTrack(unsigned int i)
973 getPlayPosition(ppos);
978 int ret = selectAudioStream(i);
987 int eServiceMP3::selectAudioStream(int i)
990 g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
991 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", ¤t_audio, NULL);
992 if ( current_audio == i )
994 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
995 m_currentAudioStream = i;
1001 int eServiceMP3::getCurrentChannel()
1006 RESULT eServiceMP3::selectChannel(int i)
1008 eDebug("eServiceMP3::selectChannel(%i)",i);
1012 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
1014 if (i >= m_audioStreams.size())
1016 info.m_description = m_audioStreams[i].codec;
1017 /* if (m_audioStreams[i].type == atMPEG)
1018 info.m_description = "MPEG";
1019 else if (m_audioStreams[i].type == atMP3)
1020 info.m_description = "MP3";
1021 else if (m_audioStreams[i].type == atAC3)
1022 info.m_description = "AC3";
1023 else if (m_audioStreams[i].type == atAAC)
1024 info.m_description = "AAC";
1025 else if (m_audioStreams[i].type == atDTS)
1026 info.m_description = "DTS";
1027 else if (m_audioStreams[i].type == atPCM)
1028 info.m_description = "PCM";
1029 else if (m_audioStreams[i].type == atOGG)
1030 info.m_description = "OGG";
1031 else if (m_audioStreams[i].type == atFLAC)
1032 info.m_description = "FLAC";
1034 info.m_description = "???";*/
1035 if (info.m_language.empty())
1036 info.m_language = m_audioStreams[i].language_code;
1040 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1047 source = GST_MESSAGE_SRC(msg);
1048 sourceName = gst_object_get_name(source);
1050 if (gst_message_get_structure(msg))
1052 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1053 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1057 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1059 switch (GST_MESSAGE_TYPE (msg))
1061 case GST_MESSAGE_EOS:
1062 m_event((iPlayableService*)this, evEOF);
1064 case GST_MESSAGE_STATE_CHANGED:
1066 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1069 GstState old_state, new_state;
1070 gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1072 if(old_state == new_state)
1075 eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1077 GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1081 case GST_STATE_CHANGE_NULL_TO_READY:
1084 case GST_STATE_CHANGE_READY_TO_PAUSED:
1087 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1090 g_object_set (G_OBJECT (sink), "max-buffers", 2, NULL);
1091 g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);
1092 g_object_set (G_OBJECT (sink), "async", FALSE, NULL);
1093 g_object_set (G_OBJECT (sink), "emit-signals", TRUE, NULL);
1094 gst_object_unref(sink);
1097 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1100 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1103 case GST_STATE_CHANGE_PAUSED_TO_READY:
1106 case GST_STATE_CHANGE_READY_TO_NULL:
1112 case GST_MESSAGE_ERROR:
1116 gst_message_parse_error (msg, &err, &debug);
1118 eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1119 if ( err->domain == GST_STREAM_ERROR )
1121 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1123 if ( g_strrstr(sourceName, "videosink") )
1124 m_event((iPlayableService*)this, evUser+11);
1125 else if ( g_strrstr(sourceName, "audiosink") )
1126 m_event((iPlayableService*)this, evUser+10);
1132 case GST_MESSAGE_INFO:
1137 gst_message_parse_info (msg, &inf, &debug);
1139 if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1141 if ( g_strrstr(sourceName, "videosink") )
1142 m_event((iPlayableService*)this, evUser+14);
1147 case GST_MESSAGE_TAG:
1149 GstTagList *tags, *result;
1150 gst_message_parse_tag(msg, &tags);
1152 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1156 gst_tag_list_free(m_stream_tags);
1157 m_stream_tags = result;
1160 const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1163 GstBuffer *buf_image;
1164 buf_image = gst_value_get_buffer (gv_image);
1165 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1166 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1168 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1169 m_event((iPlayableService*)this, evUser+13);
1171 gst_tag_list_free(tags);
1172 m_event((iPlayableService*)this, evUpdatedInfo);
1175 case GST_MESSAGE_ASYNC_DONE:
1177 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1181 gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1183 g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1184 g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1185 g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1187 eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1189 if ( n_video + n_audio <= 0 )
1194 m_audioStreams.clear();
1195 m_subtitleStreams.clear();
1197 for (i = 0; i < n_audio; i++)
1200 gchar *g_codec, *g_lang;
1202 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1203 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1206 GstStructure* str = gst_caps_get_structure(caps, 0);
1207 const gchar *g_type = gst_structure_get_name(str);
1208 eDebug("AUDIO STRUCT=%s", g_type);
1209 audio.type = gstCheckAudioPad(str);
1210 g_codec = g_strdup(g_type);
1211 g_lang = g_strdup_printf ("und");
1212 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1213 if ( tags && gst_is_tag_list(tags) )
1215 gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1216 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1217 gst_tag_list_free(tags);
1219 audio.language_code = std::string(g_lang);
1220 audio.codec = std::string(g_codec);
1221 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1222 m_audioStreams.push_back(audio);
1225 gst_caps_unref(caps);
1228 for (i = 0; i < n_text; i++)
1233 // g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1234 // GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1235 // GstStructure* str = gst_caps_get_structure(caps, 0);
1236 // g_type = gst_structure_get_name(str);
1237 // g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1238 subtitleStream subs;
1239 subs.type = stPlainText;
1240 g_lang = g_strdup_printf ("und");
1241 if ( tags && gst_is_tag_list(tags) )
1242 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1243 subs.language_code = std::string(g_lang);
1244 eDebug("eServiceMP3::subtitle stream=%i language=%s"/* type=%s*/, i, g_lang/*, g_type*/);
1245 m_subtitleStreams.push_back(subs);
1249 m_event((iPlayableService*)this, evUpdatedEventInfo);
1251 case GST_MESSAGE_ELEMENT:
1253 if ( gst_is_missing_plugin_message(msg) )
1255 gchar *description = gst_missing_plugin_message_get_description(msg);
1258 m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1259 g_free(description);
1260 m_event((iPlayableService*)this, evUser+12);
1263 else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1265 const gchar *eventname = gst_structure_get_name(msgstruct);
1268 if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1270 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1271 gst_structure_get_int (msgstruct, "width", &m_width);
1272 gst_structure_get_int (msgstruct, "height", &m_height);
1273 if (strstr(eventname, "Changed"))
1274 m_event((iPlayableService*)this, evVideoSizeChanged);
1276 else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1278 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1279 if (strstr(eventname, "Changed"))
1280 m_event((iPlayableService*)this, evVideoFramerateChanged);
1282 else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1284 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1285 if (strstr(eventname, "Changed"))
1286 m_event((iPlayableService*)this, evVideoProgressiveChanged);
1292 case GST_MESSAGE_BUFFERING:
1294 GstBufferingMode mode;
1295 gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1296 gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1297 m_event((iPlayableService*)this, evBuffering);
1302 g_free (sourceName);
1305 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1307 eServiceMP3 *_this = (eServiceMP3*)user_data;
1308 _this->m_pump.send(1);
1310 return GST_BUS_PASS;
1313 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1318 if ( gst_structure_has_name (structure, "audio/mpeg"))
1320 gint mpegversion, layer = -1;
1321 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1324 switch (mpegversion) {
1327 gst_structure_get_int (structure, "layer", &layer);
1343 else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1345 else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1347 else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1353 void eServiceMP3::gstPoll(const int &msg)
1355 /* ok, we have a serious problem here. gstBusSyncHandler sends
1356 us the wakup signal, but likely before it was posted.
1357 the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1359 I need to understand the API a bit more to make this work
1363 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1364 GstMessage *message;
1366 while ((message = gst_bus_pop (bus)))
1368 gstBusCall(bus, message);
1369 gst_message_unref (message);
1376 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1378 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1380 eServiceMP3 *_this = (eServiceMP3*)user_data;
1381 eSingleLocker l(_this->m_subs_to_pull_lock);
1382 ++_this->m_subs_to_pull;
1383 _this->m_pump.send(2);
1386 void eServiceMP3::pullSubtitle()
1389 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1392 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1396 eSingleLocker l(m_subs_to_pull_lock);
1398 g_signal_emit_by_name (sink, "pull-buffer", &buffer);
1402 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1403 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1404 size_t len = GST_BUFFER_SIZE(buffer);
1405 unsigned char line[len+1];
1406 memcpy(line, GST_BUFFER_DATA(buffer), len);
1408 eDebug("got new subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1409 ePangoSubtitlePage page;
1410 gRGB rgbcol(0xD0,0xD0,0xD0);
1411 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1412 page.show_pts = buf_pos / 11111L;
1413 page.m_timeout = duration_ns / 1000000;
1414 m_subtitle_pages.push_back(page);
1416 gst_buffer_unref(buffer);
1419 gst_object_unref(sink);
1422 eDebug("no subtitle sink!");
1425 void eServiceMP3::pushSubtitles()
1427 ePangoSubtitlePage page;
1429 while ( !m_subtitle_pages.empty() )
1431 getPlayPosition(running_pts);
1432 page = m_subtitle_pages.front();
1433 gint64 diff_ms = ( page.show_pts - running_pts ) / 90;
1434 eDebug("eServiceMP3::pushSubtitles show_pts = %lld running_pts = %lld diff = %lld", page.show_pts, running_pts, diff_ms);
1437 GstFormat fmt = GST_FORMAT_TIME;
1439 if (gst_element_query_position(m_gst_playbin, &fmt, &now) != -1)
1442 diff_ms = abs((now - running_pts) / 90);
1443 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1444 if (diff_ms > 100000)
1446 eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1447 m_subtitle_sync_timer->start(1000, true);
1452 eDebug("query position for decoder/pipeline check failed!");
1453 eDebug("subtitle to late... drop");
1454 m_subtitle_pages.pop_front();
1456 else if ( diff_ms > 20 )
1458 // eDebug("start recheck timer");
1459 m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1462 else // immediate show
1464 if (m_subtitle_widget)
1465 m_subtitle_widget->setPage(page);
1466 m_subtitle_pages.pop_front();
1469 if (m_subtitle_pages.empty())
1473 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1476 int tuplesize = PyTuple_Size(tuple);
1480 if (!PyTuple_Check(tuple))
1484 entry = PyTuple_GET_ITEM(tuple, 1);
1485 if (!PyInt_Check(entry))
1487 pid = PyInt_AsLong(entry);
1488 entry = PyTuple_GET_ITEM(tuple, 2);
1489 if (!PyInt_Check(entry))
1491 type = PyInt_AsLong(entry);
1493 if (m_currentSubtitleStream != pid)
1495 eSingleLocker l(m_subs_to_pull_lock);
1496 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1497 m_currentSubtitleStream = pid;
1499 m_subtitle_pages.clear();
1502 m_subtitle_widget = 0;
1503 m_subtitle_widget = new eSubtitleWidget(parent);
1504 m_subtitle_widget->resize(parent->size()); /* full size */
1506 g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1508 eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1513 eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1514 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1518 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1520 eDebug("eServiceMP3::disableSubtitles");
1521 m_subtitle_pages.clear();
1522 delete m_subtitle_widget;
1523 m_subtitle_widget = 0;
1527 PyObject *eServiceMP3::getCachedSubtitle()
1529 // eDebug("eServiceMP3::getCachedSubtitle");
1533 PyObject *eServiceMP3::getSubtitleList()
1535 eDebug("eServiceMP3::getSubtitleList");
1537 ePyObject l = PyList_New(0);
1538 int stream_count[sizeof(subtype_t)];
1539 for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1540 stream_count[i] = 0;
1542 for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1544 subtype_t type = IterSubtitleStream->type;
1545 ePyObject tuple = PyTuple_New(5);
1546 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1547 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1548 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1549 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1550 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1551 PyList_Append(l, tuple);
1553 stream_count[type]++;
1558 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1564 PyObject *eServiceMP3::getBufferCharge()
1566 ePyObject tuple = PyTuple_New(5);
1567 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1568 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1569 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1570 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1571 PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1575 int eServiceMP3::setBufferSize(int size)
1577 m_buffer_size = size;
1578 g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1584 #warning gstreamer not available, not building media player