use newer eDVBServicePMTHandler::tuneExt call, add a virtual createDataSource functio...
[enigma2.git] / lib / service / servicemp3.cpp
1 #ifdef HAVE_GSTREAMER
2
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>
16
17 #include <string>
18
19 #include <gst/gst.h>
20 #include <gst/pbutils/missing-plugins.h>
21 #include <sys/stat.h>
22
23 #define HTTP_TIMEOUT 10
24
25 // eServiceFactoryMP3
26
27 eServiceFactoryMP3::eServiceFactoryMP3()
28 {
29         ePtr<eServiceCenter> sc;
30         
31         eServiceCenter::getPrivInstance(sc);
32         if (sc)
33         {
34                 std::list<std::string> extensions;
35                 extensions.push_back("mp2");
36                 extensions.push_back("mp3");
37                 extensions.push_back("ogg");
38                 extensions.push_back("mpg");
39                 extensions.push_back("vob");
40                 extensions.push_back("wav");
41                 extensions.push_back("wave");
42                 extensions.push_back("m4v");
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                 sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
52         }
53
54         m_service_info = new eStaticServiceMP3Info();
55 }
56
57 eServiceFactoryMP3::~eServiceFactoryMP3()
58 {
59         ePtr<eServiceCenter> sc;
60         
61         eServiceCenter::getPrivInstance(sc);
62         if (sc)
63                 sc->removeServiceFactory(eServiceFactoryMP3::id);
64 }
65
66 DEFINE_REF(eServiceFactoryMP3)
67
68         // iServiceHandler
69 RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
70 {
71                 // check resources...
72         ptr = new eServiceMP3(ref);
73         return 0;
74 }
75
76 RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
77 {
78         ptr=0;
79         return -1;
80 }
81
82 RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
83 {
84         ptr=0;
85         return -1;
86 }
87
88 RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
89 {
90         ptr = m_service_info;
91         return 0;
92 }
93
94 class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
95 {
96         DECLARE_REF(eMP3ServiceOfflineOperations);
97         eServiceReference m_ref;
98 public:
99         eMP3ServiceOfflineOperations(const eServiceReference &ref);
100         
101         RESULT deleteFromDisk(int simulate);
102         RESULT getListOfFilenames(std::list<std::string> &);
103         RESULT reindex();
104 };
105
106 DEFINE_REF(eMP3ServiceOfflineOperations);
107
108 eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
109 {
110 }
111
112 RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
113 {
114         if (simulate)
115                 return 0;
116         else
117         {
118                 std::list<std::string> res;
119                 if (getListOfFilenames(res))
120                         return -1;
121                 
122                 eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
123                 if (!eraser)
124                         eDebug("FATAL !! can't get background file eraser");
125                 
126                 for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
127                 {
128                         eDebug("Removing %s...", i->c_str());
129                         if (eraser)
130                                 eraser->erase(i->c_str());
131                         else
132                                 ::unlink(i->c_str());
133                 }
134                 
135                 return 0;
136         }
137 }
138
139 RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
140 {
141         res.clear();
142         res.push_back(m_ref.path);
143         return 0;
144 }
145
146 RESULT eMP3ServiceOfflineOperations::reindex()
147 {
148         return -1;
149 }
150
151
152 RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
153 {
154         ptr = new eMP3ServiceOfflineOperations(ref);
155         return 0;
156 }
157
158 // eStaticServiceMP3Info
159
160
161 // eStaticServiceMP3Info is seperated from eServiceMP3 to give information
162 // about unopened files.
163
164 // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
165 // should have a database backend where ID3-files etc. are cached.
166 // this would allow listing the mp3 database based on certain filters.
167
168 DEFINE_REF(eStaticServiceMP3Info)
169
170 eStaticServiceMP3Info::eStaticServiceMP3Info()
171 {
172 }
173
174 RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
175 {
176         if ( ref.name.length() )
177                 name = ref.name;
178         else
179         {
180                 size_t last = ref.path.rfind('/');
181                 if (last != std::string::npos)
182                         name = ref.path.substr(last+1);
183                 else
184                         name = ref.path;
185         }
186         return 0;
187 }
188
189 int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
190 {
191         return -1;
192 }
193
194 int eStaticServiceMP3Info::getInfo(const eServiceReference &ref, int w)
195 {
196         switch (w)
197         {
198         case iServiceInformation::sTimeCreate:
199         {
200                 struct stat s;
201                 if(stat(ref.path.c_str(), &s) == 0)
202                 {
203                   return s.st_mtime;
204                 }
205                 return iServiceInformation::resNA;
206         }
207         default: break;
208         }
209         return iServiceInformation::resNA;
210 }
211  
212
213 // eServiceMP3
214 int eServiceMP3::ac3_delay,
215     eServiceMP3::pcm_delay;
216
217 eServiceMP3::eServiceMP3(eServiceReference ref)
218         :m_ref(ref), m_pump(eApp, 1)
219 {
220         m_seekTimeout = eTimer::create(eApp);
221         m_subtitle_sync_timer = eTimer::create(eApp);
222         m_streamingsrc_timeout = 0;
223         m_stream_tags = 0;
224         m_currentAudioStream = -1;
225         m_currentSubtitleStream = 0;
226         m_subtitle_widget = 0;
227         m_currentTrickRatio = 0;
228         m_subs_to_pull = 0;
229         m_buffer_size = 1*1024*1024;
230         CONNECT(m_seekTimeout->timeout, eServiceMP3::seekTimeoutCB);
231         CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
232         CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
233         m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
234
235         m_state = stIdle;
236         eDebug("eServiceMP3::construct!");
237
238         const char *filename = m_ref.path.c_str();
239         const char *ext = strrchr(filename, '.');
240         if (!ext)
241                 ext = filename;
242
243         m_sourceinfo.is_video = FALSE;
244         m_sourceinfo.audiotype = atUnknown;
245         if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
246         {
247                 m_sourceinfo.containertype = ctMPEGPS;
248                 m_sourceinfo.is_video = TRUE;
249         }
250         else if ( strcasecmp(ext, ".ts") == 0 )
251         {
252                 m_sourceinfo.containertype = ctMPEGTS;
253                 m_sourceinfo.is_video = TRUE;
254         }
255         else if ( strcasecmp(ext, ".mkv") == 0 )
256         {
257                 m_sourceinfo.containertype = ctMKV;
258                 m_sourceinfo.is_video = TRUE;
259         }
260         else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
261         {
262                 m_sourceinfo.containertype = ctAVI;
263                 m_sourceinfo.is_video = TRUE;
264         }
265         else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0 || strcasecmp(ext, ".m4v") == 0)
266         {
267                 m_sourceinfo.containertype = ctMP4;
268                 m_sourceinfo.is_video = TRUE;
269         }
270         else if ( strcasecmp(ext, ".m4a") == 0 )
271         {
272                 m_sourceinfo.containertype = ctMP4;
273                 m_sourceinfo.audiotype = atAAC;
274         }
275         else if ( strcasecmp(ext, ".mp3") == 0 )
276                 m_sourceinfo.audiotype = atMP3;
277         else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
278                 m_sourceinfo.containertype = ctCDA;
279         if ( strcasecmp(ext, ".dat") == 0 )
280         {
281                 m_sourceinfo.containertype = ctVCD;
282                 m_sourceinfo.is_video = TRUE;
283         }
284         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 || (strncmp(filename, "rtspt://", 7)) == 0 )
285                 m_sourceinfo.is_streaming = TRUE;
286
287         gchar *uri;
288
289         if ( m_sourceinfo.is_streaming )
290         {
291                 uri = g_strdup_printf ("%s", filename);
292                 m_streamingsrc_timeout = eTimer::create(eApp);;
293                 CONNECT(m_streamingsrc_timeout->timeout, eServiceMP3::sourceTimeout);
294
295                 std::string config_str;
296                 if( ePythonConfigQuery::getConfigValue("config.mediaplayer.useAlternateUserAgent", config_str) == 0 )
297                 {
298                         if ( config_str == "True" )
299                                 ePythonConfigQuery::getConfigValue("config.mediaplayer.alternateUserAgent", m_useragent);
300                 }
301                 if ( m_useragent.length() == 0 )
302                         m_useragent = "Dream Multimedia Dreambox Enigma2 Mediaplayer";
303         }
304         else if ( m_sourceinfo.containertype == ctCDA )
305         {
306                 int i_track = atoi(filename+18);
307                 uri = g_strdup_printf ("cdda://%i", i_track);
308         }
309         else if ( m_sourceinfo.containertype == ctVCD )
310         {
311                 int fd = open(filename,O_RDONLY);
312                 char tmp[128*1024];
313                 int ret = read(fd, tmp, 128*1024);
314                 close(fd);
315                 if ( ret == -1 ) // this is a "REAL" VCD
316                         uri = g_strdup_printf ("vcd://");
317                 else
318                         uri = g_filename_to_uri(filename, NULL, NULL);
319         }
320         else
321
322                 uri = g_filename_to_uri(filename, NULL, NULL);
323
324         eDebug("eServiceMP3::playbin2 uri=%s", uri);
325
326         m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
327         if (!m_gst_playbin)
328                 m_error_message = "failed to create GStreamer pipeline!\n";
329
330         g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
331
332         int flags = 0x47; // ( == GST_PLAY_FLAG_VIDEO | GST_PLAY_FLAG_AUDIO | GST_PLAY_FLAG_NATIVE_VIDEO | GST_PLAY_FLAG_TEXT )
333         g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
334
335         g_free(uri);
336
337         GstElement *subsink = gst_element_factory_make("appsink", "subtitle_sink");
338         if (!subsink)
339                 eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-appsink");
340         else
341         {
342                 m_subs_to_pull_handler_id = g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
343                 g_object_set (G_OBJECT (subsink), "caps", gst_caps_from_string("text/plain; text/x-plain; text/x-pango-markup"), NULL);
344                 g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
345         }
346
347         if ( m_gst_playbin )
348         {
349                 gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), gstBusSyncHandler, this);
350                 char srt_filename[strlen(filename)+1];
351                 strncpy(srt_filename,filename,strlen(filename)-3);
352                 srt_filename[strlen(filename)-3]='\0';
353                 strcat(srt_filename, "srt");
354                 struct stat buffer;
355                 if (stat(srt_filename, &buffer) == 0)
356                 {
357                         eDebug("eServiceMP3::subtitle uri: %s", g_filename_to_uri(srt_filename, NULL, NULL));
358                         g_object_set (G_OBJECT (m_gst_playbin), "suburi", g_filename_to_uri(srt_filename, NULL, NULL), NULL);
359                         subtitleStream subs;
360                         subs.type = stSRT;
361                         subs.language_code = std::string("und");
362                         m_subtitleStreams.push_back(subs);
363                 }
364                 if ( m_sourceinfo.is_streaming )
365                 {
366                         g_signal_connect (G_OBJECT (m_gst_playbin), "notify::source", G_CALLBACK (gstHTTPSourceSetAgent), this);
367                 }
368         } else
369         {
370                 m_event((iPlayableService*)this, evUser+12);
371
372                 if (m_gst_playbin)
373                         gst_object_unref(GST_OBJECT(m_gst_playbin));
374
375                 eDebug("eServiceMP3::sorry, can't play: %s",m_error_message.c_str());
376                 m_gst_playbin = 0;
377         }
378
379         setBufferSize(m_buffer_size);
380 }
381
382 eServiceMP3::~eServiceMP3()
383 {
384         // disconnect subtitle callback
385         GstElement *sink;
386         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
387         if (sink)
388         {
389                 g_signal_handler_disconnect (sink, m_subs_to_pull_handler_id);
390                 gst_object_unref(sink);
391         }
392
393         delete m_subtitle_widget;
394
395         // disconnect sync handler callback
396         gst_bus_set_sync_handler(gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin)), NULL, NULL);
397
398         if (m_state == stRunning)
399                 stop();
400
401         if (m_stream_tags)
402                 gst_tag_list_free(m_stream_tags);
403         
404         if (m_gst_playbin)
405         {
406                 gst_object_unref (GST_OBJECT (m_gst_playbin));
407                 eDebug("eServiceMP3::destruct!");
408         }
409 }
410
411 DEFINE_REF(eServiceMP3);
412
413 RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
414 {
415         connection = new eConnection((iPlayableService*)this, m_event.connect(event));
416         return 0;
417 }
418
419 RESULT eServiceMP3::start()
420 {
421         ASSERT(m_state == stIdle);
422
423         m_state = stRunning;
424         if (m_gst_playbin)
425         {
426                 eDebug("eServiceMP3::starting pipeline");
427                 gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
428         }
429
430         m_event(this, evStart);
431
432         return 0;
433 }
434
435 void eServiceMP3::sourceTimeout()
436 {
437         eDebug("eServiceMP3::http source timeout! issuing eof...");
438         m_event((iPlayableService*)this, evEOF);
439 }
440
441 RESULT eServiceMP3::stop()
442 {
443         ASSERT(m_state != stIdle);
444
445         if (m_state == stStopped)
446                 return -1;
447
448         eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
449         gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
450         m_state = stStopped;
451
452         return 0;
453 }
454
455 RESULT eServiceMP3::setTarget(int target)
456 {
457         return -1;
458 }
459
460 RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
461 {
462         ptr=this;
463         return 0;
464 }
465
466 RESULT eServiceMP3::setSlowMotion(int ratio)
467 {
468         if (!ratio)
469                 return 0;
470         eDebug("eServiceMP3::setSlowMotion ratio=%f",1/(float)ratio);
471         return trickSeek(1/(float)ratio);
472 }
473
474 RESULT eServiceMP3::setFastForward(int ratio)
475 {
476         eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
477         return trickSeek(ratio);
478 }
479
480 void eServiceMP3::seekTimeoutCB()
481 {
482         pts_t ppos, len;
483         getPlayPosition(ppos);
484         getLength(len);
485         ppos += 90000*m_currentTrickRatio;
486         
487         if (ppos < 0)
488         {
489                 ppos = 0;
490                 m_seekTimeout->stop();
491         }
492         if (ppos > len)
493         {
494                 ppos = 0;
495                 stop();
496                 m_seekTimeout->stop();
497                 return;
498         }
499         seekTo(ppos);
500 }
501
502                 // iPausableService
503 RESULT eServiceMP3::pause()
504 {
505         if (!m_gst_playbin || m_state != stRunning)
506                 return -1;
507
508         gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
509
510         return 0;
511 }
512
513 RESULT eServiceMP3::unpause()
514 {
515         if (!m_gst_playbin || m_state != stRunning)
516                 return -1;
517
518         gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
519
520         return 0;
521 }
522
523         /* iSeekableService */
524 RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
525 {
526         ptr = this;
527         return 0;
528 }
529
530 RESULT eServiceMP3::getLength(pts_t &pts)
531 {
532         if (!m_gst_playbin)
533                 return -1;
534
535         if (m_state != stRunning)
536                 return -1;
537
538         GstFormat fmt = GST_FORMAT_TIME;
539         gint64 len;
540         
541         if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
542                 return -1;
543                 /* len is in nanoseconds. we have 90 000 pts per second. */
544         
545         pts = len / 11111;
546         return 0;
547 }
548
549 RESULT eServiceMP3::seekToImpl(pts_t to)
550 {
551                 /* convert pts to nanoseconds */
552         gint64 time_nanoseconds = to * 11111LL;
553         if (!gst_element_seek (m_gst_playbin, 1.0, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH,
554                 GST_SEEK_TYPE_SET, time_nanoseconds,
555                 GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
556         {
557                 eDebug("eServiceMP3::seekTo failed");
558                 return -1;
559         }
560
561         return 0;
562 }
563
564 RESULT eServiceMP3::seekTo(pts_t to)
565 {
566         RESULT ret = -1;
567
568         if (m_gst_playbin) {
569                 eSingleLocker l(m_subs_to_pull_lock); // this is needed to dont handle incomming subtitles during seek!
570                 if (!(ret = seekToImpl(to)))
571                 {
572                         m_subtitle_pages.clear();
573                         m_subs_to_pull = 0;
574                 }
575         }
576
577         return ret;
578 }
579
580
581 RESULT eServiceMP3::trickSeek(gdouble ratio)
582 {
583         if (!m_gst_playbin)
584                 return -1;
585         if (!ratio)
586                 return seekRelative(0, 0);
587
588         GstEvent *s_event;
589         int flags;
590         flags = GST_SEEK_FLAG_NONE;
591         flags |= GST_SEEK_FLAG_FLUSH;
592 //      flags |= GstSeekFlags (GST_SEEK_FLAG_ACCURATE);
593         flags |= GST_SEEK_FLAG_KEY_UNIT;
594 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SEGMENT);
595 //      flags |= GstSeekFlags (GST_SEEK_FLAG_SKIP);
596
597         GstFormat fmt = GST_FORMAT_TIME;
598         gint64 pos, len;
599         gst_element_query_duration(m_gst_playbin, &fmt, &len);
600         gst_element_query_position(m_gst_playbin, &fmt, &pos);
601
602         if ( ratio >= 0 )
603         {
604                 s_event = gst_event_new_seek (ratio, GST_FORMAT_TIME, (GstSeekFlags)flags, GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, len);
605
606                 eDebug("eServiceMP3::trickSeek with rate %lf to %" GST_TIME_FORMAT " ", ratio, GST_TIME_ARGS (pos));
607         }
608         else
609         {
610                 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);
611         }
612
613         if (!gst_element_send_event ( GST_ELEMENT (m_gst_playbin), s_event))
614         {
615                 eDebug("eServiceMP3::trickSeek failed");
616                 return -1;
617         }
618
619         return 0;
620 }
621
622
623 RESULT eServiceMP3::seekRelative(int direction, pts_t to)
624 {
625         if (!m_gst_playbin)
626                 return -1;
627
628         pts_t ppos;
629         getPlayPosition(ppos);
630         ppos += to * direction;
631         if (ppos < 0)
632                 ppos = 0;
633         seekTo(ppos);
634         
635         return 0;
636 }
637
638 RESULT eServiceMP3::getPlayPosition(pts_t &pts)
639 {
640         GstFormat fmt = GST_FORMAT_TIME;
641         gint64 pos;
642         GstElement *sink;
643         pts = 0;
644
645         if (!m_gst_playbin)
646                 return -1;
647         if (m_state != stRunning)
648                 return -1;
649
650         g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
651
652         if (!sink)
653                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
654
655         if (!sink)
656                 return -1;
657
658         gchar *name = gst_element_get_name(sink);
659         gboolean use_get_decoder_time = strstr(name, "dvbaudiosink") || strstr(name, "dvbvideosink");
660         g_free(name);
661
662         if (use_get_decoder_time)
663                 g_signal_emit_by_name(sink, "get-decoder-time", &pos);
664
665         gst_object_unref(sink);
666
667         if (!use_get_decoder_time && !gst_element_query_position(m_gst_playbin, &fmt, &pos)) {
668                 eDebug("gst_element_query_position failed in getPlayPosition");
669                 return -1;
670         }
671
672         /* pos is in nanoseconds. we have 90 000 pts per second. */
673         pts = pos / 11111;
674         return 0;
675 }
676
677 RESULT eServiceMP3::setTrickmode(int trick)
678 {
679                 /* trickmode is not yet supported by our dvbmediasinks. */
680         return -1;
681 }
682
683 RESULT eServiceMP3::isCurrentlySeekable()
684 {
685         int ret = 3; // seeking and fast/slow winding possible
686         GstElement *sink;
687
688         if (!m_gst_playbin)
689                 return 0;
690         if (m_state != stRunning)
691                 return 0;
692
693         g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
694
695         // disable fast winding yet when a dvbvideosink or dvbaudiosink is used
696         // for this we must do some changes on different places.. (gstreamer.. our sinks.. enigma2)
697         if (sink) {
698                 ret &= ~2; // only seeking possible
699                 gst_object_unref(sink);
700         }
701         else {
702                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
703                 if (sink) {
704                         ret &= ~2; // only seeking possible
705                         gst_object_unref(sink);
706                 }
707         }
708
709         return ret;
710 }
711
712 RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
713 {
714         i = this;
715         return 0;
716 }
717
718 RESULT eServiceMP3::getName(std::string &name)
719 {
720         std::string title = m_ref.getName();
721         if (title.empty())
722         {
723                 name = m_ref.path;
724                 size_t n = name.rfind('/');
725                 if (n != std::string::npos)
726                         name = name.substr(n + 1);
727         }
728         else
729                 name = title;
730         return 0;
731 }
732
733 int eServiceMP3::getInfo(int w)
734 {
735         const gchar *tag = 0;
736
737         switch (w)
738         {
739         case sServiceref: return m_ref;
740         case sVideoHeight: return m_height;
741         case sVideoWidth: return m_width;
742         case sFrameRate: return m_framerate;
743         case sProgressive: return m_progressive;
744         case sAspect: return m_aspect;
745         case sTagTitle:
746         case sTagArtist:
747         case sTagAlbum:
748         case sTagTitleSortname:
749         case sTagArtistSortname:
750         case sTagAlbumSortname:
751         case sTagDate:
752         case sTagComposer:
753         case sTagGenre:
754         case sTagComment:
755         case sTagExtendedComment:
756         case sTagLocation:
757         case sTagHomepage:
758         case sTagDescription:
759         case sTagVersion:
760         case sTagISRC:
761         case sTagOrganization:
762         case sTagCopyright:
763         case sTagCopyrightURI:
764         case sTagContact:
765         case sTagLicense:
766         case sTagLicenseURI:
767         case sTagCodec:
768         case sTagAudioCodec:
769         case sTagVideoCodec:
770         case sTagEncoder:
771         case sTagLanguageCode:
772         case sTagKeywords:
773         case sTagChannelMode:
774         case sUser+12:
775                 return resIsString;
776         case sTagTrackGain:
777         case sTagTrackPeak:
778         case sTagAlbumGain:
779         case sTagAlbumPeak:
780         case sTagReferenceLevel:
781         case sTagBeatsPerMinute:
782         case sTagImage:
783         case sTagPreviewImage:
784         case sTagAttachment:
785                 return resIsPyObject;
786         case sTagTrackNumber:
787                 tag = GST_TAG_TRACK_NUMBER;
788                 break;
789         case sTagTrackCount:
790                 tag = GST_TAG_TRACK_COUNT;
791                 break;
792         case sTagAlbumVolumeNumber:
793                 tag = GST_TAG_ALBUM_VOLUME_NUMBER;
794                 break;
795         case sTagAlbumVolumeCount:
796                 tag = GST_TAG_ALBUM_VOLUME_COUNT;
797                 break;
798         case sTagBitrate:
799                 tag = GST_TAG_BITRATE;
800                 break;
801         case sTagNominalBitrate:
802                 tag = GST_TAG_NOMINAL_BITRATE;
803                 break;
804         case sTagMinimumBitrate:
805                 tag = GST_TAG_MINIMUM_BITRATE;
806                 break;
807         case sTagMaximumBitrate:
808                 tag = GST_TAG_MAXIMUM_BITRATE;
809                 break;
810         case sTagSerial:
811                 tag = GST_TAG_SERIAL;
812                 break;
813         case sTagEncoderVersion:
814                 tag = GST_TAG_ENCODER_VERSION;
815                 break;
816         case sTagCRC:
817                 tag = "has-crc";
818                 break;
819         default:
820                 return resNA;
821         }
822
823         if (!m_stream_tags || !tag)
824                 return 0;
825         
826         guint value;
827         if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
828                 return (int) value;
829
830         return 0;
831 }
832
833 std::string eServiceMP3::getInfoString(int w)
834 {
835         if ( !m_stream_tags && w < sUser && w > 26 )
836                 return "";
837         const gchar *tag = 0;
838         switch (w)
839         {
840         case sTagTitle:
841                 tag = GST_TAG_TITLE;
842                 break;
843         case sTagArtist:
844                 tag = GST_TAG_ARTIST;
845                 break;
846         case sTagAlbum:
847                 tag = GST_TAG_ALBUM;
848                 break;
849         case sTagTitleSortname:
850                 tag = GST_TAG_TITLE_SORTNAME;
851                 break;
852         case sTagArtistSortname:
853                 tag = GST_TAG_ARTIST_SORTNAME;
854                 break;
855         case sTagAlbumSortname:
856                 tag = GST_TAG_ALBUM_SORTNAME;
857                 break;
858         case sTagDate:
859                 GDate *date;
860                 if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
861                 {
862                         gchar res[5];
863                         g_date_strftime (res, sizeof(res), "%Y-%M-%D", date); 
864                         return (std::string)res;
865                 }
866                 break;
867         case sTagComposer:
868                 tag = GST_TAG_COMPOSER;
869                 break;
870         case sTagGenre:
871                 tag = GST_TAG_GENRE;
872                 break;
873         case sTagComment:
874                 tag = GST_TAG_COMMENT;
875                 break;
876         case sTagExtendedComment:
877                 tag = GST_TAG_EXTENDED_COMMENT;
878                 break;
879         case sTagLocation:
880                 tag = GST_TAG_LOCATION;
881                 break;
882         case sTagHomepage:
883                 tag = GST_TAG_HOMEPAGE;
884                 break;
885         case sTagDescription:
886                 tag = GST_TAG_DESCRIPTION;
887                 break;
888         case sTagVersion:
889                 tag = GST_TAG_VERSION;
890                 break;
891         case sTagISRC:
892                 tag = GST_TAG_ISRC;
893                 break;
894         case sTagOrganization:
895                 tag = GST_TAG_ORGANIZATION;
896                 break;
897         case sTagCopyright:
898                 tag = GST_TAG_COPYRIGHT;
899                 break;
900         case sTagCopyrightURI:
901                 tag = GST_TAG_COPYRIGHT_URI;
902                 break;
903         case sTagContact:
904                 tag = GST_TAG_CONTACT;
905                 break;
906         case sTagLicense:
907                 tag = GST_TAG_LICENSE;
908                 break;
909         case sTagLicenseURI:
910                 tag = GST_TAG_LICENSE_URI;
911                 break;
912         case sTagCodec:
913                 tag = GST_TAG_CODEC;
914                 break;
915         case sTagAudioCodec:
916                 tag = GST_TAG_AUDIO_CODEC;
917                 break;
918         case sTagVideoCodec:
919                 tag = GST_TAG_VIDEO_CODEC;
920                 break;
921         case sTagEncoder:
922                 tag = GST_TAG_ENCODER;
923                 break;
924         case sTagLanguageCode:
925                 tag = GST_TAG_LANGUAGE_CODE;
926                 break;
927         case sTagKeywords:
928                 tag = GST_TAG_KEYWORDS;
929                 break;
930         case sTagChannelMode:
931                 tag = "channel-mode";
932                 break;
933         case sUser+12:
934                 return m_error_message;
935         default:
936                 return "";
937         }
938         if ( !tag )
939                 return "";
940         gchar *value;
941         if (gst_tag_list_get_string(m_stream_tags, tag, &value))
942         {
943                 std::string res = value;
944                 g_free(value);
945                 return res;
946         }
947         return "";
948 }
949
950 PyObject *eServiceMP3::getInfoObject(int w)
951 {
952         const gchar *tag = 0;
953         bool isBuffer = false;
954         switch (w)
955         {
956                 case sTagTrackGain:
957                         tag = GST_TAG_TRACK_GAIN;
958                         break;
959                 case sTagTrackPeak:
960                         tag = GST_TAG_TRACK_PEAK;
961                         break;
962                 case sTagAlbumGain:
963                         tag = GST_TAG_ALBUM_GAIN;
964                         break;
965                 case sTagAlbumPeak:
966                         tag = GST_TAG_ALBUM_PEAK;
967                         break;
968                 case sTagReferenceLevel:
969                         tag = GST_TAG_REFERENCE_LEVEL;
970                         break;
971                 case sTagBeatsPerMinute:
972                         tag = GST_TAG_BEATS_PER_MINUTE;
973                         break;
974                 case sTagImage:
975                         tag = GST_TAG_IMAGE;
976                         isBuffer = true;
977                         break;
978                 case sTagPreviewImage:
979                         tag = GST_TAG_PREVIEW_IMAGE;
980                         isBuffer = true;
981                         break;
982                 case sTagAttachment:
983                         tag = GST_TAG_ATTACHMENT;
984                         isBuffer = true;
985                         break;
986                 default:
987                         break;
988         }
989
990         if ( isBuffer )
991         {
992                 const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
993                 if ( gv_buffer )
994                 {
995                         GstBuffer *buffer;
996                         buffer = gst_value_get_buffer (gv_buffer);
997                         return PyBuffer_FromMemory(GST_BUFFER_DATA(buffer), GST_BUFFER_SIZE(buffer));
998                 }
999         }
1000         else
1001         {
1002                 gdouble value = 0.0;
1003                 gst_tag_list_get_double(m_stream_tags, tag, &value);
1004                 return PyFloat_FromDouble(value);
1005         }
1006
1007         return 0;
1008 }
1009
1010 RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
1011 {
1012         ptr = this;
1013         return 0;
1014 }
1015
1016 RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
1017 {
1018         ptr = this;
1019         return 0;
1020 }
1021
1022 RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
1023 {
1024         ptr = this;
1025         return 0;
1026 }
1027
1028 RESULT eServiceMP3::audioDelay(ePtr<iAudioDelay> &ptr)
1029 {
1030         ptr = this;
1031         return 0;
1032 }
1033
1034 int eServiceMP3::getNumberOfTracks()
1035 {
1036         return m_audioStreams.size();
1037 }
1038
1039 int eServiceMP3::getCurrentTrack()
1040 {
1041         if (m_currentAudioStream == -1)
1042                 g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL);
1043         return m_currentAudioStream;
1044 }
1045
1046 RESULT eServiceMP3::selectTrack(unsigned int i)
1047 {
1048         pts_t ppos;
1049         getPlayPosition(ppos);
1050         ppos -= 90000;
1051         if (ppos < 0)
1052                 ppos = 0;
1053
1054         int ret = selectAudioStream(i);
1055         if (!ret) {
1056                 /* flush */
1057                 seekTo(ppos);
1058         }
1059
1060         return ret;
1061 }
1062
1063 int eServiceMP3::selectAudioStream(int i)
1064 {
1065         int current_audio;
1066         g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
1067         g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &current_audio, NULL);
1068         if ( current_audio == i )
1069         {
1070                 eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
1071                 m_currentAudioStream = i;
1072                 return 0;
1073         }
1074         return -1;
1075 }
1076
1077 int eServiceMP3::getCurrentChannel()
1078 {
1079         return STEREO;
1080 }
1081
1082 RESULT eServiceMP3::selectChannel(int i)
1083 {
1084         eDebug("eServiceMP3::selectChannel(%i)",i);
1085         return 0;
1086 }
1087
1088 RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
1089 {
1090         if (i >= m_audioStreams.size())
1091                 return -2;
1092                 info.m_description = m_audioStreams[i].codec;
1093 /*      if (m_audioStreams[i].type == atMPEG)
1094                 info.m_description = "MPEG";
1095         else if (m_audioStreams[i].type == atMP3)
1096                 info.m_description = "MP3";
1097         else if (m_audioStreams[i].type == atAC3)
1098                 info.m_description = "AC3";
1099         else if (m_audioStreams[i].type == atAAC)
1100                 info.m_description = "AAC";
1101         else if (m_audioStreams[i].type == atDTS)
1102                 info.m_description = "DTS";
1103         else if (m_audioStreams[i].type == atPCM)
1104                 info.m_description = "PCM";
1105         else if (m_audioStreams[i].type == atOGG)
1106                 info.m_description = "OGG";
1107         else if (m_audioStreams[i].type == atFLAC)
1108                 info.m_description = "FLAC";
1109         else
1110                 info.m_description = "???";*/
1111         if (info.m_language.empty())
1112                 info.m_language = m_audioStreams[i].language_code;
1113         return 0;
1114 }
1115
1116 void eServiceMP3::gstBusCall(GstBus *bus, GstMessage *msg)
1117 {
1118         if (!msg)
1119                 return;
1120         gchar *sourceName;
1121         GstObject *source;
1122
1123         source = GST_MESSAGE_SRC(msg);
1124         sourceName = gst_object_get_name(source);
1125 #if 0
1126         if (gst_message_get_structure(msg))
1127         {
1128                 gchar *string = gst_structure_to_string(gst_message_get_structure(msg));
1129                 eDebug("eServiceMP3::gst_message from %s: %s", sourceName, string);
1130                 g_free(string);
1131         }
1132         else
1133                 eDebug("eServiceMP3::gst_message from %s: %s (without structure)", sourceName, GST_MESSAGE_TYPE_NAME(msg));
1134 #endif
1135         switch (GST_MESSAGE_TYPE (msg))
1136         {
1137                 case GST_MESSAGE_EOS:
1138                         m_event((iPlayableService*)this, evEOF);
1139                         break;
1140                 case GST_MESSAGE_STATE_CHANGED:
1141                 {
1142                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1143                                 break;
1144
1145                         GstState old_state, new_state;
1146                         gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
1147                 
1148                         if(old_state == new_state)
1149                                 break;
1150         
1151                         eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
1152         
1153                         GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
1154         
1155                         switch(transition)
1156                         {
1157                                 case GST_STATE_CHANGE_NULL_TO_READY:
1158                                 {
1159                                 }       break;
1160                                 case GST_STATE_CHANGE_READY_TO_PAUSED:
1161                                 {
1162                                         GstElement *sink;
1163                                         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1164                                         if (sink)
1165                                         {
1166                                                 g_object_set (G_OBJECT (sink), "max-buffers", 2, NULL);
1167                                                 g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);
1168                                                 g_object_set (G_OBJECT (sink), "async", FALSE, NULL);
1169                                                 g_object_set (G_OBJECT (sink), "emit-signals", TRUE, NULL);
1170                                                 gst_object_unref(sink);
1171                                         }
1172                                         setAC3Delay(ac3_delay);
1173                                         setPCMDelay(pcm_delay);
1174                                 }       break;
1175                                 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1176                                 {
1177                                         if ( m_sourceinfo.is_streaming && m_streamingsrc_timeout )
1178                                                 m_streamingsrc_timeout->stop();
1179                                 }       break;
1180                                 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1181                                 {
1182                                 }       break;
1183                                 case GST_STATE_CHANGE_PAUSED_TO_READY:
1184                                 {
1185                                 }       break;
1186                                 case GST_STATE_CHANGE_READY_TO_NULL:
1187                                 {
1188                                 }       break;
1189                         }
1190                         break;
1191                 }
1192                 case GST_MESSAGE_ERROR:
1193                 {
1194                         gchar *debug;
1195                         GError *err;
1196                         gst_message_parse_error (msg, &err, &debug);
1197                         g_free (debug);
1198                         eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
1199                         if ( err->domain == GST_STREAM_ERROR )
1200                         {
1201                                 if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
1202                                 {
1203                                         if ( g_strrstr(sourceName, "videosink") )
1204                                                 m_event((iPlayableService*)this, evUser+11);
1205                                         else if ( g_strrstr(sourceName, "audiosink") )
1206                                                 m_event((iPlayableService*)this, evUser+10);
1207                                 }
1208                         }
1209                         g_error_free(err);
1210                         break;
1211                 }
1212                 case GST_MESSAGE_INFO:
1213                 {
1214                         gchar *debug;
1215                         GError *inf;
1216         
1217                         gst_message_parse_info (msg, &inf, &debug);
1218                         g_free (debug);
1219                         if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
1220                         {
1221                                 if ( g_strrstr(sourceName, "videosink") )
1222                                         m_event((iPlayableService*)this, evUser+14);
1223                         }
1224                         g_error_free(inf);
1225                         break;
1226                 }
1227                 case GST_MESSAGE_TAG:
1228                 {
1229                         GstTagList *tags, *result;
1230                         gst_message_parse_tag(msg, &tags);
1231         
1232                         result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
1233                         if (result)
1234                         {
1235                                 if (m_stream_tags)
1236                                         gst_tag_list_free(m_stream_tags);
1237                                 m_stream_tags = result;
1238                         }
1239         
1240                         const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
1241                         if ( gv_image )
1242                         {
1243                                 GstBuffer *buf_image;
1244                                 buf_image = gst_value_get_buffer (gv_image);
1245                                 int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
1246                                 int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
1247                                 close(fd);
1248                                 eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
1249                                 m_event((iPlayableService*)this, evUser+13);
1250                         }
1251                         gst_tag_list_free(tags);
1252                         m_event((iPlayableService*)this, evUpdatedInfo);
1253                         break;
1254                 }
1255                 case GST_MESSAGE_ASYNC_DONE:
1256                 {
1257                         if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
1258                                 break;
1259
1260                         GstTagList *tags;
1261                         gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;
1262
1263                         g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
1264                         g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
1265                         g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
1266
1267                         eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
1268
1269                         if ( n_video + n_audio <= 0 )
1270                                 stop();
1271
1272                         active_idx = 0;
1273
1274                         m_audioStreams.clear();
1275                         m_subtitleStreams.clear();
1276
1277                         for (i = 0; i < n_audio; i++)
1278                         {
1279                                 audioStream audio;
1280                                 gchar *g_codec, *g_lang;
1281                                 GstPad* pad = 0;
1282                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
1283                                 GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1284                                 if (!caps)
1285                                         continue;
1286                                 GstStructure* str = gst_caps_get_structure(caps, 0);
1287                                 const gchar *g_type = gst_structure_get_name(str);
1288                                 eDebug("AUDIO STRUCT=%s", g_type);
1289                                 audio.type = gstCheckAudioPad(str);
1290                                 g_codec = g_strdup(g_type);
1291                                 g_lang = g_strdup_printf ("und");
1292                                 g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
1293                                 if ( tags && gst_is_tag_list(tags) )
1294                                 {
1295                                         gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
1296                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1297                                         gst_tag_list_free(tags);
1298                                 }
1299                                 audio.language_code = std::string(g_lang);
1300                                 audio.codec = std::string(g_codec);
1301                                 eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
1302                                 m_audioStreams.push_back(audio);
1303                                 g_free (g_lang);
1304                                 g_free (g_codec);
1305                                 gst_caps_unref(caps);
1306                         }
1307
1308                         for (i = 0; i < n_text; i++)
1309                         {       
1310                                 gchar *g_lang;
1311 //                              gchar *g_type;
1312 //                              GstPad* pad = 0;
1313 //                              g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
1314 //                              GstCaps* caps = gst_pad_get_negotiated_caps(pad);
1315 //                              GstStructure* str = gst_caps_get_structure(caps, 0);
1316 //                              g_type = gst_structure_get_name(str);
1317 //                              g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
1318                                 subtitleStream subs;
1319                                 subs.type = stPlainText;
1320                                 g_lang = g_strdup_printf ("und");
1321                                 if ( tags && gst_is_tag_list(tags) )
1322                                         gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
1323                                 subs.language_code = std::string(g_lang);
1324                                 eDebug("eServiceMP3::subtitle stream=%i language=%s"/* type=%s*/, i, g_lang/*, g_type*/);
1325                                 m_subtitleStreams.push_back(subs);
1326                                 g_free (g_lang);
1327 //                              g_free (g_type);
1328                         }
1329                         m_event((iPlayableService*)this, evUpdatedEventInfo);
1330                         break;
1331                 }
1332                 case GST_MESSAGE_ELEMENT:
1333                 {
1334                         if ( gst_is_missing_plugin_message(msg) )
1335                         {
1336                                 gchar *description = gst_missing_plugin_message_get_description(msg);
1337                                 if ( description )
1338                                 {
1339                                         m_error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
1340                                         g_free(description);
1341                                         m_event((iPlayableService*)this, evUser+12);
1342                                 }
1343                         }
1344                         else if (const GstStructure *msgstruct = gst_message_get_structure(msg))
1345                         {
1346                                 const gchar *eventname = gst_structure_get_name(msgstruct);
1347                                 if ( eventname )
1348                                 {
1349                                         if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
1350                                         {
1351                                                 gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
1352                                                 gst_structure_get_int (msgstruct, "width", &m_width);
1353                                                 gst_structure_get_int (msgstruct, "height", &m_height);
1354                                                 if (strstr(eventname, "Changed"))
1355                                                         m_event((iPlayableService*)this, evVideoSizeChanged);
1356                                         }
1357                                         else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
1358                                         {
1359                                                 gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
1360                                                 if (strstr(eventname, "Changed"))
1361                                                         m_event((iPlayableService*)this, evVideoFramerateChanged);
1362                                         }
1363                                         else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
1364                                         {
1365                                                 gst_structure_get_int (msgstruct, "progressive", &m_progressive);
1366                                                 if (strstr(eventname, "Changed"))
1367                                                         m_event((iPlayableService*)this, evVideoProgressiveChanged);
1368                                         }
1369                                 }
1370                         }
1371                         break;
1372                 }
1373                 case GST_MESSAGE_BUFFERING:
1374                 {
1375                         GstBufferingMode mode;
1376                         gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
1377                         gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
1378                         m_event((iPlayableService*)this, evBuffering);
1379                         break;
1380                 }
1381                 case GST_MESSAGE_STREAM_STATUS:
1382                 {
1383                         GstStreamStatusType type;
1384                         GstElement *owner;
1385                         gst_message_parse_stream_status (msg, &type, &owner);
1386                         if ( type == GST_STREAM_STATUS_TYPE_CREATE && m_sourceinfo.is_streaming )
1387                         {
1388                                 if ( GST_IS_PAD(source) )
1389                                         owner = gst_pad_get_parent_element(GST_PAD(source));
1390                                 else if ( GST_IS_ELEMENT(source) )
1391                                         owner = GST_ELEMENT(source);
1392                                 else
1393                                         owner = 0;
1394                                 if ( owner )
1395                                 {
1396                                         GstElementFactory *factory = gst_element_get_factory(GST_ELEMENT(owner));
1397                                         const gchar *name = gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory));
1398                                         if (!strcmp(name, "souphttpsrc"))
1399                                         {
1400                                                 m_streamingsrc_timeout->start(HTTP_TIMEOUT*1000, true);
1401                                                 g_object_set (G_OBJECT (owner), "timeout", HTTP_TIMEOUT, NULL);
1402                                                 eDebug("eServiceMP3::GST_STREAM_STATUS_TYPE_CREATE -> setting timeout on %s to %is", name, HTTP_TIMEOUT);
1403                                         }
1404                                         
1405                                 }
1406                                 if ( GST_IS_PAD(source) )
1407                                         gst_object_unref(owner);
1408                         }
1409                         break;
1410                 }
1411                 default:
1412                         break;
1413         }
1414         g_free (sourceName);
1415 }
1416
1417 GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
1418 {
1419         eServiceMP3 *_this = (eServiceMP3*)user_data;
1420         _this->m_pump.send(1);
1421                 /* wake */
1422         return GST_BUS_PASS;
1423 }
1424
1425 void eServiceMP3::gstHTTPSourceSetAgent(GObject *object, GParamSpec *unused, gpointer user_data)
1426 {
1427         eServiceMP3 *_this = (eServiceMP3*)user_data;
1428         GstElement *source;
1429         g_object_get(_this->m_gst_playbin, "source", &source, NULL);
1430         g_object_set (G_OBJECT (source), "user-agent", _this->m_useragent.c_str(), NULL);
1431         gst_object_unref(source);
1432 }
1433
1434 audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
1435 {
1436         if (!structure)
1437                 return atUnknown;
1438
1439         if ( gst_structure_has_name (structure, "audio/mpeg"))
1440         {
1441                 gint mpegversion, layer = -1;
1442                 if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
1443                         return atUnknown;
1444
1445                 switch (mpegversion) {
1446                         case 1:
1447                                 {
1448                                         gst_structure_get_int (structure, "layer", &layer);
1449                                         if ( layer == 3 )
1450                                                 return atMP3;
1451                                         else
1452                                                 return atMPEG;
1453                                         break;
1454                                 }
1455                         case 2:
1456                                 return atAAC;
1457                         case 4:
1458                                 return atAAC;
1459                         default:
1460                                 return atUnknown;
1461                 }
1462         }
1463
1464         else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
1465                 return atAC3;
1466         else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
1467                 return atDTS;
1468         else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
1469                 return atPCM;
1470
1471         return atUnknown;
1472 }
1473
1474 void eServiceMP3::gstPoll(const int &msg)
1475 {
1476                 /* ok, we have a serious problem here. gstBusSyncHandler sends 
1477                    us the wakup signal, but likely before it was posted.
1478                    the usleep, an EVIL HACK (DON'T DO THAT!!!) works around this.
1479                    
1480                    I need to understand the API a bit more to make this work 
1481                    proplerly. */
1482         if (msg == 1)
1483         {
1484                 GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (m_gst_playbin));
1485                 GstMessage *message;
1486                 usleep(1);
1487                 while ((message = gst_bus_pop (bus)))
1488                 {
1489                         gstBusCall(bus, message);
1490                         gst_message_unref (message);
1491                 }
1492         }
1493         else
1494                 pullSubtitle();
1495 }
1496
1497 eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
1498
1499 void eServiceMP3::gstCBsubtitleAvail(GstElement *appsink, gpointer user_data)
1500 {
1501         eServiceMP3 *_this = (eServiceMP3*)user_data;
1502         eSingleLocker l(_this->m_subs_to_pull_lock);
1503         ++_this->m_subs_to_pull;
1504         _this->m_pump.send(2);
1505 }
1506
1507 void eServiceMP3::pullSubtitle()
1508 {
1509         GstElement *sink;
1510         g_object_get (G_OBJECT (m_gst_playbin), "text-sink", &sink, NULL);
1511         if (sink)
1512         {
1513                 while (m_subs_to_pull && m_subtitle_pages.size() < 2)
1514                 {
1515                         GstBuffer *buffer;
1516                         {
1517                                 eSingleLocker l(m_subs_to_pull_lock);
1518                                 --m_subs_to_pull;
1519                                 g_signal_emit_by_name (sink, "pull-buffer", &buffer);
1520                         }
1521                         if (buffer)
1522                         {
1523                                 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
1524                                 gint64 duration_ns = GST_BUFFER_DURATION(buffer);
1525                                 size_t len = GST_BUFFER_SIZE(buffer);
1526                                 unsigned char line[len+1];
1527                                 memcpy(line, GST_BUFFER_DATA(buffer), len);
1528                                 line[len] = 0;
1529                                 eDebug("got new subtitle @ buf_pos = %lld ns (in pts=%lld): '%s' ", buf_pos, buf_pos/11111, line);
1530                                 ePangoSubtitlePage page;
1531                                 gRGB rgbcol(0xD0,0xD0,0xD0);
1532                                 page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, (const char*)line));
1533                                 page.show_pts = buf_pos / 11111L;
1534                                 page.m_timeout = duration_ns / 1000000;
1535                                 m_subtitle_pages.push_back(page);
1536                                 pushSubtitles();
1537                                 gst_buffer_unref(buffer);
1538                         }
1539                 }
1540                 gst_object_unref(sink);
1541         }
1542         else
1543                 eDebug("no subtitle sink!");
1544 }
1545
1546 void eServiceMP3::pushSubtitles()
1547 {
1548         ePangoSubtitlePage page;
1549         pts_t running_pts;
1550         while ( !m_subtitle_pages.empty() )
1551         {
1552                 getPlayPosition(running_pts);
1553                 page = m_subtitle_pages.front();
1554                 gint64 diff_ms = ( page.show_pts - running_pts ) / 90;
1555                 eDebug("eServiceMP3::pushSubtitles show_pts = %lld  running_pts = %lld  diff = %lld", page.show_pts, running_pts, diff_ms);
1556                 if (diff_ms < -100)
1557                 {
1558                         GstFormat fmt = GST_FORMAT_TIME;
1559                         gint64 now;
1560                         if (gst_element_query_position(m_gst_playbin, &fmt, &now) != -1)
1561                         {
1562                                 now /= 11111;
1563                                 diff_ms = abs((now - running_pts) / 90);
1564                                 eDebug("diff < -100ms check decoder/pipeline diff: decoder: %lld, pipeline: %lld, diff: %lld", running_pts, now, diff_ms);
1565                                 if (diff_ms > 100000)
1566                                 {
1567                                         eDebug("high decoder/pipeline difference.. assume decoder has now started yet.. check again in 1sec");
1568                                         m_subtitle_sync_timer->start(1000, true);
1569                                         break;
1570                                 }
1571                         }
1572                         else
1573                                 eDebug("query position for decoder/pipeline check failed!");
1574                         eDebug("subtitle to late... drop");
1575                         m_subtitle_pages.pop_front();
1576                 }
1577                 else if ( diff_ms > 20 )
1578                 {
1579 //                      eDebug("start recheck timer");
1580                         m_subtitle_sync_timer->start(diff_ms > 1000 ? 1000 : diff_ms, true);
1581                         break;
1582                 }
1583                 else // immediate show
1584                 {
1585                         if (m_subtitle_widget)
1586                                 m_subtitle_widget->setPage(page);
1587                         m_subtitle_pages.pop_front();
1588                 }
1589         }
1590         if (m_subtitle_pages.empty())
1591                 pullSubtitle();
1592 }
1593
1594 RESULT eServiceMP3::enableSubtitles(eWidget *parent, ePyObject tuple)
1595 {
1596         ePyObject entry;
1597         int tuplesize = PyTuple_Size(tuple);
1598         int pid, type;
1599         gint text_pid = 0;
1600
1601         if (!PyTuple_Check(tuple))
1602                 goto error_out;
1603         if (tuplesize < 1)
1604                 goto error_out;
1605         entry = PyTuple_GET_ITEM(tuple, 1);
1606         if (!PyInt_Check(entry))
1607                 goto error_out;
1608         pid = PyInt_AsLong(entry);
1609         entry = PyTuple_GET_ITEM(tuple, 2);
1610         if (!PyInt_Check(entry))
1611                 goto error_out;
1612         type = PyInt_AsLong(entry);
1613
1614         if (m_currentSubtitleStream != pid)
1615         {
1616                 eSingleLocker l(m_subs_to_pull_lock);
1617                 g_object_set (G_OBJECT (m_gst_playbin), "current-text", pid, NULL);
1618                 m_currentSubtitleStream = pid;
1619                 m_subs_to_pull = 0;
1620                 m_subtitle_pages.clear();
1621         }
1622
1623         m_subtitle_widget = 0;
1624         m_subtitle_widget = new eSubtitleWidget(parent);
1625         m_subtitle_widget->resize(parent->size()); /* full size */
1626
1627         g_object_get (G_OBJECT (m_gst_playbin), "current-text", &text_pid, NULL);
1628
1629         eDebug ("eServiceMP3::switched to subtitle stream %i", text_pid);
1630
1631         return 0;
1632
1633 error_out:
1634         eDebug("eServiceMP3::enableSubtitles needs a tuple as 2nd argument!\n"
1635                 "for gst subtitles (2, subtitle_stream_count, subtitle_type)");
1636         return -1;
1637 }
1638
1639 RESULT eServiceMP3::disableSubtitles(eWidget *parent)
1640 {
1641         eDebug("eServiceMP3::disableSubtitles");
1642         m_subtitle_pages.clear();
1643         delete m_subtitle_widget;
1644         m_subtitle_widget = 0;
1645         return 0;
1646 }
1647
1648 PyObject *eServiceMP3::getCachedSubtitle()
1649 {
1650 //      eDebug("eServiceMP3::getCachedSubtitle");
1651         Py_RETURN_NONE;
1652 }
1653
1654 PyObject *eServiceMP3::getSubtitleList()
1655 {
1656         eDebug("eServiceMP3::getSubtitleList");
1657
1658         ePyObject l = PyList_New(0);
1659         int stream_count[sizeof(subtype_t)];
1660         for ( unsigned int i = 0; i < sizeof(subtype_t); i++ )
1661                 stream_count[i] = 0;
1662
1663         for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
1664         {
1665                 subtype_t type = IterSubtitleStream->type;
1666                 ePyObject tuple = PyTuple_New(5);
1667                 PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1668                 PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(stream_count[type]));
1669                 PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(int(type)));
1670                 PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(0));
1671                 PyTuple_SET_ITEM(tuple, 4, PyString_FromString((IterSubtitleStream->language_code).c_str()));
1672                 PyList_Append(l, tuple);
1673                 Py_DECREF(tuple);
1674                 stream_count[type]++;
1675         }
1676         return l;
1677 }
1678
1679 RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
1680 {
1681         ptr = this;
1682         return 0;
1683 }
1684
1685 PyObject *eServiceMP3::getBufferCharge()
1686 {
1687         ePyObject tuple = PyTuple_New(5);
1688         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(m_bufferInfo.bufferPercent));
1689         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(m_bufferInfo.avgInRate));
1690         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(m_bufferInfo.avgOutRate));
1691         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(m_bufferInfo.bufferingLeft));
1692         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(m_buffer_size));
1693         return tuple;
1694 }
1695
1696 int eServiceMP3::setBufferSize(int size)
1697 {
1698         m_buffer_size = size;
1699         g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
1700         return 0;
1701 }
1702
1703 int eServiceMP3::getAC3Delay()
1704 {
1705         return ac3_delay;
1706 }
1707
1708 int eServiceMP3::getPCMDelay()
1709 {
1710         return pcm_delay;
1711 }
1712
1713 void eServiceMP3::setAC3Delay(int delay)
1714 {
1715         ac3_delay = delay;
1716         if (!m_gst_playbin || m_state != stRunning)
1717                 return;
1718         else
1719         {
1720                 GstElement *sink;
1721                 int config_delay_int = delay;
1722                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1723
1724                 if (sink)
1725                 {
1726                         std::string config_delay;
1727                         if(ePythonConfigQuery::getConfigValue("config.av.generalAC3delay", config_delay) == 0)
1728                                 config_delay_int += atoi(config_delay.c_str());
1729                         gst_object_unref(sink);
1730                 }
1731                 else
1732                 {
1733                         eDebug("dont apply ac3 delay when no video is running!");
1734                         config_delay_int = 0;
1735                 }
1736
1737                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1738
1739                 if (sink)
1740                 {
1741                         gchar *name = gst_element_get_name(sink);
1742                         if (strstr(name, "dvbaudiosink"))
1743                                 eTSMPEGDecoder::setHwAC3Delay(config_delay_int);
1744                         g_free(name);
1745                         gst_object_unref(sink);
1746                 }
1747         }
1748 }
1749
1750 void eServiceMP3::setPCMDelay(int delay)
1751 {
1752         pcm_delay = delay;
1753         if (!m_gst_playbin || m_state != stRunning)
1754                 return;
1755         else
1756         {
1757                 GstElement *sink;
1758                 int config_delay_int = delay;
1759                 g_object_get (G_OBJECT (m_gst_playbin), "video-sink", &sink, NULL);
1760
1761                 if (sink)
1762                 {
1763                         std::string config_delay;
1764                         if(ePythonConfigQuery::getConfigValue("config.av.generalPCMdelay", config_delay) == 0)
1765                                 config_delay_int += atoi(config_delay.c_str());
1766                         gst_object_unref(sink);
1767                 }
1768                 else
1769                 {
1770                         eDebug("dont apply pcm delay when no video is running!");
1771                         config_delay_int = 0;
1772                 }
1773
1774                 g_object_get (G_OBJECT (m_gst_playbin), "audio-sink", &sink, NULL);
1775
1776                 if (sink)
1777                 {
1778                         gchar *name = gst_element_get_name(sink);
1779                         if (strstr(name, "dvbaudiosink"))
1780                                 eTSMPEGDecoder::setHwPCMDelay(config_delay_int);
1781                         else
1782                         {
1783                                 // this is realy untested..and not used yet
1784                                 gint64 offset = config_delay_int;
1785                                 offset *= 1000000; // milli to nano
1786                                 g_object_set (G_OBJECT (m_gst_playbin), "ts-offset", offset, NULL);
1787                         }
1788                         g_free(name);
1789                         gst_object_unref(sink);
1790                 }
1791         }
1792 }
1793
1794 #else
1795 #warning gstreamer not available, not building media player
1796 #endif