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