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