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