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/ebase.h>
6 #include <lib/base/eerror.h>
7 #include <lib/base/init_num.h>
8 #include <lib/base/init.h>
9 #include <lib/base/nconfig.h>
10 #include <lib/base/object.h>
11 #include <lib/dvb/decoder.h>
12 #include <lib/components/file_eraser.h>
13 #include <lib/gui/esubtitle.h>
14 #include <lib/service/servicemp3.h>
15 #include <lib/service/service.h>
20 #include <gst/pbutils/missing-plugins.h>
25 eServiceFactoryMP3::eServiceFactoryMP3()
27 ePtr<eServiceCenter> sc;
29 eServiceCenter::getPrivInstance(sc);
32 std::list<std::string> extensions;
33 extensions.push_back("mp2");
34 extensions.push_back("mp3");
35 extensions.push_back("ogg");
36 extensions.push_back("mpg");
37 extensions.push_back("vob");
38 extensions.push_back("wav");
39 extensions.push_back("wave");
40 extensions.push_back("m4v");
41 extensions.push_back("mkv");
42 extensions.push_back("avi");
43 extensions.push_back("divx");
44 extensions.push_back("dat");
45 extensions.push_back("flac");
46 extensions.push_back("mp4");
47 extensions.push_back("mov");
48 extensions.push_back("m4a");
49 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
52 m_service_info = new eStaticServiceMP3Info();
55 eServiceFactoryMP3::~eServiceFactoryMP3()
57 ePtr<eServiceCenter> sc;
59 eServiceCenter::getPrivInstance(sc);
61 sc->removeServiceFactory(eServiceFactoryMP3::id);
64 DEFINE_REF(eServiceFactoryMP3)
67 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
70 ptr = new eServiceMP3(ref);
74 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
80 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
86 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
92 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
94 DECLARE_REF(eMP3ServiceOfflineOperations);
95 eServiceReference m_ref;
97 eMP3ServiceOfflineOperations(const eServiceReference &ref);
99 RESULT deleteFromDisk(int simulate);
100 RESULT getListOfFilenames(std::list<std::string> &);
104 DEFINE_REF(eMP3ServiceOfflineOperations);
106 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
110 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
116 std::list<std::string> res;
117 if (getListOfFilenames(res))
120 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
122 eDebug("FATAL !! can't get background file eraser");
124 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
126 eDebug("Removing %s...", i->c_str());
128 eraser->erase(i->c_str());
130 ::unlink(i->c_str());
137 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
140 res.push_back(m_ref.path);
144 RESULT eMP3ServiceOfflineOperations::reindex()
150 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
152 ptr = new eMP3ServiceOfflineOperations(ref);
156 // eStaticServiceMP3Info
159 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
160 // about unopened files.
162 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
163 // should have a database backend where ID3-files etc. are cached.
164 // this would allow listing the mp3 database based on certain filters.
166 DEFINE_REF(eStaticServiceMP3Info)
168 eStaticServiceMP3Info::eStaticServiceMP3Info()
172 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
174 if ( ref.name.length() )
178 size_t last = ref.path.rfind('/');
179 if (last != std::string::npos)
180 name = ref.path.substr(last+1);
187 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
192 int eStaticServiceMP3Info::getInfo(const eServiceReference &ref, int w)
196 case iServiceInformation::sTimeCreate:
199 if(stat(ref.path.c_str(), &s) == 0)
203 return iServiceInformation::resNA;
207 return iServiceInformation::resNA;
212 int eServiceMP3::ac3_delay,
213 eServiceMP3::pcm_delay;
215 eServiceMP3::eServiceMP3(eServiceReference ref)
216 :m_ref(ref), m_pump(eApp, 1)
218 m_seekTimeout = eTimer::create(eApp);
219 m_subtitle_sync_timer = eTimer::create(eApp);
221 m_currentAudioStream = -1;
222 m_currentSubtitleStream = 0;
223 m_subtitle_widget = 0;
224 m_currentTrickRatio = 0;
226 m_buffer_size = 1*1024*1024;
227 CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
228 CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
229 CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
230 m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
233 eDebug("eServiceMP3::construct!");
235 const char *filename = m_ref.path.c_str();
236 const char *ext = strrchr(filename, '.');
240 sourceStream sourceinfo;
241 sourceinfo.is_video = FALSE;
242 sourceinfo.audiotype = atUnknown;
243 if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
245 sourceinfo.containertype = ctMPEGPS;
246 sourceinfo.is_video = TRUE;
248 else if ( strcasecmp(ext, ".ts") == 0 )
250 sourceinfo.containertype = ctMPEGTS;
251 sourceinfo.is_video = TRUE;
253 else if ( strcasecmp(ext, ".mkv") == 0 )
255 sourceinfo.containertype = ctMKV;
256 sourceinfo.is_video = TRUE;
258 else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
260 sourceinfo.containertype = ctAVI;
261 sourceinfo.is_video = TRUE;
263 else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0 || strcasecmp(ext, ".m4v") == 0)
265 sourceinfo.containertype = ctMP4;
266 sourceinfo.is_video = TRUE;
268 else if ( strcasecmp(ext, ".m4a") == 0 )
270 sourceinfo.containertype = ctMP4;
271 sourceinfo.audiotype = atAAC;
273 else if ( strcasecmp(ext, ".mp3") == 0 )
274 sourceinfo.audiotype = atMP3;
275 else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
276 sourceinfo.containertype = ctCDA;
277 if ( strcasecmp(ext, ".dat") == 0 )
279 sourceinfo.containertype = ctVCD;
280 sourceinfo.is_video = TRUE;
282 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 )
283 sourceinfo.is_streaming = TRUE;
287 if ( sourceinfo.is_streaming )
289 uri = g_strdup_printf ("%s", filename);
291 std::string config_str;
292 if( ePythonConfigQuery::getConfigValue("config.mediaplayer.useAlternateUserAgent", config_str) == 0 )
294 if ( config_str == "True" )
295 ePythonConfigQuery::getConfigValue("config.mediaplayer.alternateUserAgent", m_useragent);
297 if ( m_useragent.length() == 0 )
298 m_useragent = "Dream Multimedia Dreambox Enigma2 Mediaplayer";
300 else if ( sourceinfo.containertype == ctCDA )
302 int i_track = atoi(filename+18);
303 uri = g_strdup_printf ("cdda://%i", i_track);
305 else if ( sourceinfo.containertype == ctVCD )
307 int fd = open(filename,O_RDONLY);
309 int ret = read(fd, tmp, 128*1024);
311 if ( ret == -1 ) // this is a "REAL" VCD
312 uri = g_strdup_printf ("vcd://");
314 uri = g_filename_to_uri(filename, NULL, NULL);
318 uri = g_filename_to_uri(filename, NULL, NULL);
320 eDebug("eServiceMP3::playbin2 uri=%s", uri);
322 m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
324 m_error_message = "failed to create GStreamer pipeline!\n";
326 g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
328 int flags = 0x47; // ( == GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_NATIVE_VIDEO | GST_PLAY_FLAG_TEXT )
329 g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
333 GstElement *subsink = gst_element_factory_make("appsink", "subtitle_sink");
335 eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-appsink");
338 m_subs_to_pull_handler_id = g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
339 g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
344 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), gstBusSyncHandler, this);
345 char srt_filename[strlen(filename)+1];
346 strncpy(srt_filename,filename,strlen(filename)-3);
347 srt_filename[strlen(filename)-3]='\0';
348 strcat(srt_filename, "srt");
350 if (stat(srt_filename, &buffer) == 0)
352 eDebug("eServiceMP3::subtitle uri: %s", g_filename_to_uri(srt_filename, NULL, NULL));
353 g_object_set (G_OBJECT (m_gst_playbin), "suburi", g_filename_to_uri(srt_filename, NULL, NULL), NULL);
356 subs.language_code = std::string("und");
357 m_subtitleStreams.push_back(subs);
359 if ( sourceinfo.is_streaming )
361 g_signal_connect (G_OBJECT (m_gst_playbin), "notify::source", G_CALLBACK (gstHTTPSourceSetAgent), this);
365 m_event((iPlayableService*)this, evUser+12);
368 gst_object_unref(GST_OBJECT(m_gst_playbin));
370 eDebug("eServiceMP3::sorry, can't play: %s",m_error_message.c_str());
374 setBufferSize(m_buffer_size);
377 eServiceMP3::~eServiceMP3()
379 // disconnect subtitle callback
381 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
384 g_signal_handler_disconnect (sink, m_subs_to_pull_handler_id);
385 gst_object_unref(sink);
388 delete m_subtitle_widget;
390 // disconnect sync handler callback
391 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), NULL, NULL);
393 if (m_state == stRunning)
397 gst_tag_list_free(m_stream_tags);
401 gst_object_unref (GST_OBJECT (m_gst_playbin));
402 eDebug("eServiceMP3::destruct!");
406 DEFINE_REF(eServiceMP3);
408 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
410 connection = new eConnection((iPlayableService*)this, m_event.connect(event));
414 RESULT eServiceMP3::start()
416 ASSERT(m_state == stIdle);
421 eDebug("eServiceMP3::starting pipeline");
422 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
425 m_event(this, evStart);
430 RESULT eServiceMP3::stop()
432 ASSERT(m_state != stIdle);
434 if (m_state == stStopped)
437 eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
438 gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
444 RESULT eServiceMP3::setTarget(int target)
449 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
455 RESULT eServiceMP3::setSlowMotion(int ratio)
459 eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
460 return trickSeek(1/(float)ratio);
463 RESULT eServiceMP3::setFastForward(int ratio)
465 eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
466 return trickSeek(ratio);
469 void eServiceMP3::seekTimeoutCB()
472 getPlayPosition(ppos);
474 ppos += 90000*m_currentTrickRatio;
479 m_seekTimeout->stop();
485 m_seekTimeout->stop();
492 RESULT eServiceMP3::pause()
494 if (!m_gst_playbin || m_state != stRunning)
497 gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
502 RESULT eServiceMP3::unpause()
504 if (!m_gst_playbin || m_state != stRunning)
507 gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
512 /* iSeekableService */
513 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
519 RESULT eServiceMP3::getLength(pts_t &pts)
524 if (m_state != stRunning)
527 GstFormat fmt = GST_FORMAT_TIME;
530 if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
532 /* len is in nanoseconds. we have 90 000 pts per second. */
538 RESULT eServiceMP3::seekToImpl(pts_t to)
540 /* convert pts to nanoseconds */
541 gint64 time_nanoseconds = to * 11111LL;
542 if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
543 GST_SEEK_TYPE_SET, time_nanoseconds,
544 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
546 eDebug("eServiceMP3::seekTo failed");
553 RESULT eServiceMP3::seekTo(pts_t to)
558 eSingleLocker l(m_subs_to_pull_lock); // this is needed to dont handle incomming subtitles during seek!
559 if (!(ret = seekToImpl(to)))
561 m_subtitle_pages.clear();
570 RESULT eServiceMP3::trickSeek(gdouble ratio)
575 return seekRelative(0, 0);
579 flags = GST_SEEK_FLAG_NONE;
580 flags |= GST_SEEK_FLAG_FLUSH;
581 // flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
582 flags |= GST_SEEK_FLAG_KEY_UNIT;
583 // flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
584 // flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
586 GstFormat fmt = GST_FORMAT_TIME;
588 gst_element_query_duration(m_gst_playbin, &fmt, &len);
589 gst_element_query_position(m_gst_playbin, &fmt, &pos);
593 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
595 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
599 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);
602 if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
604 eDebug("eServiceMP3::trickSeek failed");
612 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
618 getPlayPosition(ppos);
619 ppos += to * direction;
627 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
629 GstFormat fmt = GST_FORMAT_TIME;
636 if (m_state != stRunning)
639 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
642 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
647 gchar *name = gst_element_get_name(sink);
648 gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
651 if (use_get_decoder_time)
652 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
654 gst_object_unref(sink);
656 if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
657 eDebug("gst_element_query_position failed in getPlayPosition");
661 /* pos is in nanoseconds. we have 90 000 pts per second. */
666 RESULT eServiceMP3::setTrickmode(int trick)
668 /* trickmode is not yet supported by our dvbmediasinks. */
672 RESULT eServiceMP3::isCurrentlySeekable()
674 int ret = 3; // seeking and fast/slow winding possible
679 if (m_state != stRunning)
682 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
684 // disable fast winding yet when a dvbvideosink or dvbaudiosink is used
685 // for this we must do some changes on different places.. (gstreamer.. our sinks.. enigma2)
687 ret &= ~2; // only seeking possible
688 gst_object_unref(sink);
691 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
693 ret &= ~2; // only seeking possible
694 gst_object_unref(sink);
701 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
707 RESULT eServiceMP3::getName(std::string &name)
709 std::string title = m_ref.getName();
713 size_t n = name.rfind('/');
714 if (n != std::string::npos)
715 name = name.substr(n + 1);
722 int eServiceMP3::getInfo(int w)
724 const gchar *tag = 0;
728 case sServiceref: return m_ref;
729 case sVideoHeight: return m_height;
730 case sVideoWidth: return m_width;
731 case sFrameRate: return m_framerate;
732 case sProgressive: return m_progressive;
733 case sAspect: return m_aspect;
737 case sTagTitleSortname:
738 case sTagArtistSortname:
739 case sTagAlbumSortname:
744 case sTagExtendedComment:
747 case sTagDescription:
750 case sTagOrganization:
752 case sTagCopyrightURI:
760 case sTagLanguageCode:
762 case sTagChannelMode:
769 case sTagReferenceLevel:
770 case sTagBeatsPerMinute:
772 case sTagPreviewImage:
774 return resIsPyObject;
775 case sTagTrackNumber:
776 tag = GST_TAG_TRACK_NUMBER;
779 tag = GST_TAG_TRACK_COUNT;
781 case sTagAlbumVolumeNumber:
782 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
784 case sTagAlbumVolumeCount:
785 tag = GST_TAG_ALBUM_VOLUME_COUNT;
788 tag = GST_TAG_BITRATE;
790 case sTagNominalBitrate:
791 tag = GST_TAG_NOMINAL_BITRATE;
793 case sTagMinimumBitrate:
794 tag = GST_TAG_MINIMUM_BITRATE;
796 case sTagMaximumBitrate:
797 tag = GST_TAG_MAXIMUM_BITRATE;
800 tag = GST_TAG_SERIAL;
802 case sTagEncoderVersion:
803 tag = GST_TAG_ENCODER_VERSION;
812 if (!m_stream_tags || !tag)
816 if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
822 std::string eServiceMP3::getInfoString(int w)
824 if ( !m_stream_tags && w < sUser && w > 26 )
826 const gchar *tag = 0;
833 tag = GST_TAG_ARTIST;
838 case sTagTitleSortname:
839 tag = GST_TAG_TITLE_SORTNAME;
841 case sTagArtistSortname:
842 tag = GST_TAG_ARTIST_SORTNAME;
844 case sTagAlbumSortname:
845 tag = GST_TAG_ALBUM_SORTNAME;
849 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
852 g_date_strftime (res, sizeof(res), "%Y-%M-%D", date);
853 return (std::string)res;
857 tag = GST_TAG_COMPOSER;
863 tag = GST_TAG_COMMENT;
865 case sTagExtendedComment:
866 tag = GST_TAG_EXTENDED_COMMENT;
869 tag = GST_TAG_LOCATION;
872 tag = GST_TAG_HOMEPAGE;
874 case sTagDescription:
875 tag = GST_TAG_DESCRIPTION;
878 tag = GST_TAG_VERSION;
883 case sTagOrganization:
884 tag = GST_TAG_ORGANIZATION;
887 tag = GST_TAG_COPYRIGHT;
889 case sTagCopyrightURI:
890 tag = GST_TAG_COPYRIGHT_URI;
893 tag = GST_TAG_CONTACT;
896 tag = GST_TAG_LICENSE;
899 tag = GST_TAG_LICENSE_URI;
905 tag = GST_TAG_AUDIO_CODEC;
908 tag = GST_TAG_VIDEO_CODEC;
911 tag = GST_TAG_ENCODER;
913 case sTagLanguageCode:
914 tag = GST_TAG_LANGUAGE_CODE;
917 tag = GST_TAG_KEYWORDS;
919 case sTagChannelMode:
920 tag = "channel-mode";
923 return m_error_message;
930 if (gst_tag_list_get_string(m_stream_tags, tag, &value))
932 std::string res = value;
939 PyObject *eServiceMP3::getInfoObject(int w)
941 const gchar *tag = 0;
942 bool isBuffer = false;
946 tag = GST_TAG_TRACK_GAIN;
949 tag = GST_TAG_TRACK_PEAK;
952 tag = GST_TAG_ALBUM_GAIN;
955 tag = GST_TAG_ALBUM_PEAK;
957 case sTagReferenceLevel:
958 tag = GST_TAG_REFERENCE_LEVEL;
960 case sTagBeatsPerMinute:
961 tag = GST_TAG_BEATS_PER_MINUTE;
967 case sTagPreviewImage:
968 tag = GST_TAG_PREVIEW_IMAGE;
972 tag = GST_TAG_ATTACHMENT;
981 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
985 buffer = gst_value_get_buffer (gv_buffer);
986 return PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
992 gst_tag_list_get_double(m_stream_tags, tag, &value);
993 return PyFloat_FromDouble(value);
999 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
1005 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
1011 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
1017 RESULT eServiceMP3::audioDelay(ePtr<iAudioDelay> &ptr)
1023 int eServiceMP3::getNumberOfTracks()
1025 return m_audioStreams.size();
1028 int eServiceMP3::getCurrentTrack()
1030 if (m_currentAudioStream == -1)
1031 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL);
1032 return m_currentAudioStream;
1035 RESULT eServiceMP3::selectTrack(unsigned int i)
1038 getPlayPosition(ppos);
1043 int ret = selectAudioStream(i);
1052 int eServiceMP3::selectAudioStream(int i)
1055 g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
1056 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", ¤t_audio, NULL);
1057 if ( current_audio == i )
1059 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
1060 m_currentAudioStream = i;
1066 int eServiceMP3::getCurrentChannel()
1071 RESULT eServiceMP3::selectChannel(int i)
1073 eDebug("eServiceMP3::selectChannel(%i)",i);
1077 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
1079 if (i >= m_audioStreams.size())
1081 info.m_description = m_audioStreams[i].codec;
1082 /* if (m_audioStreams[i].type == atMPEG)
1083 info.m_description = "MPEG";
1084 else if (m_audioStreams[i].type == atMP3)
1085 info.m_description = "MP3";
1086 else if (m_audioStreams[i].type == atAC3)
1087 info.m_description = "AC3";
1088 else if (m_audioStreams[i].type == atAAC)
1089 info.m_description = "AAC";
1090 else if (m_audioStreams[i].type == atDTS)
1091 info.m_description = "DTS";
1092 else if (m_audioStreams[i].type == atPCM)
1093 info.m_description = "PCM";
1094 else if (m_audioStreams[i].type == atOGG)
1095 info.m_description = "OGG";
1096 else if (m_audioStreams[i].type == atFLAC)
1097 info.m_description = "FLAC";
1099 info.m_description = "???";*/
1100 if (info.m_language.empty())
1101 info.m_language = m_audioStreams[i].language_code;
1105 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1112 source = GST_MESSAGE_SRC(msg);
1113 sourceName = gst_object_get_name(source);
1115 if (gst_message_get_structure(msg))
1117 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1118 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1122 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1124 switch (GST_MESSAGE_TYPE (msg))
1126 case GST_MESSAGE_EOS:
1127 m_event((iPlayableService*)this, evEOF);
1129 case GST_MESSAGE_STATE_CHANGED:
1131 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1134 GstState old_state, new_state;
1135 gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1137 if(old_state == new_state)
1140 eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1142 GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1146 case GST_STATE_CHANGE_NULL_TO_READY:
1149 case GST_STATE_CHANGE_READY_TO_PAUSED:
1152 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1155 g_object_set (G_OBJECT (sink), "max-buffers", 2, NULL);
1156 g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);
1157 g_object_set (G_OBJECT (sink), "async", FALSE, NULL);
1158 g_object_set (G_OBJECT (sink), "emit-signals", TRUE, NULL);
1159 gst_object_unref(sink);
1161 setAC3Delay(ac3_delay);
1162 setPCMDelay(pcm_delay);
1164 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1167 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1170 case GST_STATE_CHANGE_PAUSED_TO_READY:
1173 case GST_STATE_CHANGE_READY_TO_NULL:
1179 case GST_MESSAGE_ERROR:
1183 gst_message_parse_error (msg, &err, &debug);
1185 eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1186 if ( err->domain == GST_STREAM_ERROR )
1188 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1190 if ( g_strrstr(sourceName, "videosink") )
1191 m_event((iPlayableService*)this, evUser+11);
1192 else if ( g_strrstr(sourceName, "audiosink") )
1193 m_event((iPlayableService*)this, evUser+10);
1199 case GST_MESSAGE_INFO:
1204 gst_message_parse_info (msg, &inf, &debug);
1206 if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1208 if ( g_strrstr(sourceName, "videosink") )
1209 m_event((iPlayableService*)this, evUser+14);
1214 case GST_MESSAGE_TAG:
1216 GstTagList *tags, *result;
1217 gst_message_parse_tag(msg, &tags);
1219 result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1223 gst_tag_list_free(m_stream_tags);
1224 m_stream_tags = result;
1227 const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1230 GstBuffer *buf_image;
1231 buf_image = gst_value_get_buffer (gv_image);
1232 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1233 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1235 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1236 m_event((iPlayableService*)this, evUser+13);
1238 gst_tag_list_free(tags);
1239 m_event((iPlayableService*)this, evUpdatedInfo);
1242 case GST_MESSAGE_ASYNC_DONE:
1244 if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1248 gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1250 g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1251 g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1252 g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1254 eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1256 if ( n_video + n_audio <= 0 )
1261 m_audioStreams.clear();
1262 m_subtitleStreams.clear();
1264 for (i = 0; i < n_audio; i++)
1267 gchar *g_codec, *g_lang;
1269 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1270 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1273 GstStructure* str = gst_caps_get_structure(caps, 0);
1274 const gchar *g_type = gst_structure_get_name(str);
1275 eDebug("AUDIO STRUCT=%s", g_type);
1276 audio.type = gstCheckAudioPad(str);
1277 g_codec = g_strdup(g_type);
1278 g_lang = g_strdup_printf ("und");
1279 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1280 if ( tags && gst_is_tag_list(tags) )
1282 gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1283 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1284 gst_tag_list_free(tags);
1286 audio.language_code = std::string(g_lang);
1287 audio.codec = std::string(g_codec);
1288 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1289 m_audioStreams.push_back(audio);
1292 gst_caps_unref(caps);
1295 for (i = 0; i < n_text; i++)
1300 // g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1301 // GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1302 // GstStructure* str = gst_caps_get_structure(caps, 0);
1303 // g_type = gst_structure_get_name(str);
1304 // g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1305 subtitleStream subs;
1306 subs.type = stPlainText;
1307 g_lang = g_strdup_printf ("und");
1308 if ( tags && gst_is_tag_list(tags) )
1309 gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1310 subs.language_code = std::string(g_lang);
1311 eDebug("eServiceMP3::subtitle stream=%i language=%s"/* type=%s*/, i, g_lang/*, g_type*/);
1312 m_subtitleStreams.push_back(subs);
1316 m_event((iPlayableService*)this, evUpdatedEventInfo);
1318 case GST_MESSAGE_ELEMENT:
1320 if ( gst_is_missing_plugin_message(msg) )
1322 gchar *description = gst_missing_plugin_message_get_description(msg);
1325 m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1326 g_free(description);
1327 m_event((iPlayableService*)this, evUser+12);
1330 else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1332 const gchar *eventname = gst_structure_get_name(msgstruct);
1335 if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1337 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1338 gst_structure_get_int (msgstruct, "width", &m_width);
1339 gst_structure_get_int (msgstruct, "height", &m_height);
1340 if (strstr(eventname, "Changed"))
1341 m_event((iPlayableService*)this, evVideoSizeChanged);
1343 else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1345 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1346 if (strstr(eventname, "Changed"))
1347 m_event((iPlayableService*)this, evVideoFramerateChanged);
1349 else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1351 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1352 if (strstr(eventname, "Changed"))
1353 m_event((iPlayableService*)this, evVideoProgressiveChanged);
1359 case GST_MESSAGE_BUFFERING:
1361 GstBufferingMode mode;
1362 gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1363 gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1364 m_event((iPlayableService*)this, evBuffering);
1369 g_free (sourceName);
1372 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1374 eServiceMP3 *_this = (eServiceMP3*)user_data;
1375 _this->m_pump.send(1);
1377 return GST_BUS_PASS;
1380 void eServiceMP3::gstHTTPSourceSetAgent(GObject *object, GParamSpec *unused, gpointer user_data)
1382 eServiceMP3 *_this = (eServiceMP3*)user_data;
1384 g_object_get(_this->m_gst_playbin, "source", &source, NULL);
1385 g_object_set (G_OBJECT (source), "user-agent", _this->m_useragent.c_str(), NULL);
1386 gst_object_unref(source);
1389 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1394 if ( gst_structure_has_name (structure, "audio/mpeg"))
1396 gint mpegversion, layer = -1;
1397 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1400 switch (mpegversion) {
1403 gst_structure_get_int (structure, "layer", &layer);
1419 else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1421 else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1423 else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1429 void eServiceMP3::gstPoll(const int &msg)
1431 /* ok, we have a serious problem here. gstBusSyncHandler sends
1432 us the wakup signal, but likely before it was posted.
1433 the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1435 I need to understand the API a bit more to make this work
1439 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1440 GstMessage *message;
1442 while ((message = gst_bus_pop (bus)))
1444 gstBusCall(bus, message);
1445 gst_message_unref (message);
1452 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1454 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1456 eServiceMP3 *_this = (eServiceMP3*)user_data;
1457 eSingleLocker l(_this->m_subs_to_pull_lock);
1458 ++_this->m_subs_to_pull;
1459 _this->m_pump.send(2);
1462 void eServiceMP3::pullSubtitle()
1465 g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1468 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1472 eSingleLocker l(m_subs_to_pull_lock);
1474 g_signal_emit_by_name (sink, "pull-buffer", &buffer);
1478 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1479 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1480 size_t len = GST_BUFFER_SIZE(buffer);
1481 unsigned char line[len+1];
1482 memcpy(line, GST_BUFFER_DATA(buffer), len);
1484 eDebug("got new subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1485 ePangoSubtitlePage page;
1486 gRGB rgbcol(0xD0,0xD0,0xD0);
1487 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1488 page.show_pts = buf_pos / 11111L;
1489 page.m_timeout = duration_ns / 1000000;
1490 m_subtitle_pages.push_back(page);
1492 gst_buffer_unref(buffer);
1495 gst_object_unref(sink);
1498 eDebug("no subtitle sink!");
1501 void eServiceMP3::pushSubtitles()
1503 ePangoSubtitlePage page;
1505 while ( !m_subtitle_pages.empty() )
1507 getPlayPosition(running_pts);
1508 page = m_subtitle_pages.front();
1509 gint64 diff_ms = ( page.show_pts - running_pts ) / 90;
1510 eDebug("eServiceMP3::pushSubtitles show_pts = %lld running_pts = %lld diff = %lld", page.show_pts, running_pts, diff_ms);
1513 GstFormat fmt = GST_FORMAT_TIME;
1515 if (gst_element_query_position(m_gst_playbin, &fmt, &now) != -1)
1518 diff_ms = abs((now - running_pts) / 90);
1519 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1520 if (diff_ms > 100000)
1522 eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1523 m_subtitle_sync_timer->start(1000, true);
1528 eDebug("query position for decoder/pipeline check failed!");
1529 eDebug("subtitle to late... drop");
1530 m_subtitle_pages.pop_front();
1532 else if ( diff_ms > 20 )
1534 // eDebug("start recheck timer");
1535 m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1538 else // immediate show
1540 if (m_subtitle_widget)
1541 m_subtitle_widget->setPage(page);
1542 m_subtitle_pages.pop_front();
1545 if (m_subtitle_pages.empty())
1549 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1552 int tuplesize = PyTuple_Size(tuple);
1556 if (!PyTuple_Check(tuple))
1560 entry = PyTuple_GET_ITEM(tuple, 1);
1561 if (!PyInt_Check(entry))
1563 pid = PyInt_AsLong(entry);
1564 entry = PyTuple_GET_ITEM(tuple, 2);
1565 if (!PyInt_Check(entry))
1567 type = PyInt_AsLong(entry);
1569 if (m_currentSubtitleStream != pid)
1571 eSingleLocker l(m_subs_to_pull_lock);
1572 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1573 m_currentSubtitleStream = pid;
1575 m_subtitle_pages.clear();
1578 m_subtitle_widget = 0;
1579 m_subtitle_widget = new eSubtitleWidget(parent);
1580 m_subtitle_widget->resize(parent->size()); /* full size */
1582 g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1584 eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1589 eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1590 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1594 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1596 eDebug("eServiceMP3::disableSubtitles");
1597 m_subtitle_pages.clear();
1598 delete m_subtitle_widget;
1599 m_subtitle_widget = 0;
1603 PyObject *eServiceMP3::getCachedSubtitle()
1605 // eDebug("eServiceMP3::getCachedSubtitle");
1609 PyObject *eServiceMP3::getSubtitleList()
1611 eDebug("eServiceMP3::getSubtitleList");
1613 ePyObject l = PyList_New(0);
1614 int stream_count[sizeof(subtype_t)];
1615 for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1616 stream_count[i] = 0;
1618 for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1620 subtype_t type = IterSubtitleStream->type;
1621 ePyObject tuple = PyTuple_New(5);
1622 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1623 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1624 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1625 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1626 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1627 PyList_Append(l, tuple);
1629 stream_count[type]++;
1634 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1640 PyObject *eServiceMP3::getBufferCharge()
1642 ePyObject tuple = PyTuple_New(5);
1643 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1644 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1645 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1646 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1647 PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1651 int eServiceMP3::setBufferSize(int size)
1653 m_buffer_size = size;
1654 g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1658 int eServiceMP3::getAC3Delay()
1663 int eServiceMP3::getPCMDelay()
1668 void eServiceMP3::setAC3Delay(int delay)
1671 if (!m_gst_playbin || m_state != stRunning)
1676 int config_delay_int = delay;
1677 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1681 std::string config_delay;
1682 if(ePythonConfigQuery::getConfigValue("config.av.generalAC3delay", config_delay) == 0)
1683 config_delay_int += atoi(config_delay.c_str());
1684 gst_object_unref(sink);
1688 eDebug("dont apply ac3 delay when no video is running!");
1689 config_delay_int = 0;
1692 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1696 gchar *name = gst_element_get_name(sink);
1697 if (strstr(name, "dvbaudiosink"))
1698 eTSMPEGDecoder::setHwAC3Delay(config_delay_int);
1700 gst_object_unref(sink);
1705 void eServiceMP3::setPCMDelay(int delay)
1708 if (!m_gst_playbin || m_state != stRunning)
1713 int config_delay_int = delay;
1714 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1718 std::string config_delay;
1719 if(ePythonConfigQuery::getConfigValue("config.av.generalPCMdelay", config_delay) == 0)
1720 config_delay_int += atoi(config_delay.c_str());
1721 gst_object_unref(sink);
1725 eDebug("dont apply pcm delay when no video is running!");
1726 config_delay_int = 0;
1729 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1733 gchar *name = gst_element_get_name(sink);
1734 if (strstr(name, "dvbaudiosink"))
1735 eTSMPEGDecoder::setHwPCMDelay(config_delay_int);
1738 // this is realy untested..and not used yet
1739 gint64 offset = config_delay_int;
1740 offset *= 1000000; // milli to nano
1741 g_object_set (G_OBJECT (m_gst_playbin), "ts-offset", offset, NULL);
1744 gst_object_unref(sink);
1750 #warning gstreamer not available, not building media player