initialize variable
[enigma2.git] / lib / dvb / db.cpp
1 #include <errno.h>
2 #include <lib/dvb/db.h>
3 #include <lib/dvb/dvb.h>
4 #include <lib/dvb/frontend.h>
5 #include <lib/dvb/epgcache.h>
6 #include <lib/base/eerror.h>
7 #include <lib/base/estring.h>
8 #include <dvbsi++/service_description_section.h>
9 #include <dvbsi++/descriptor_tag.h>
10 #include <dvbsi++/service_descriptor.h>
11 #include <dvbsi++/satellite_delivery_system_descriptor.h>
12
13 DEFINE_REF(eDVBService);
14
15 RESULT eBouquet::addService(const eServiceReference &ref)
16 {
17         list::iterator it =
18                 std::find(m_services.begin(), m_services.end(), ref);
19         if ( it != m_services.end() )
20                 return -1;
21         m_services.push_back(ref);
22         return 0;
23 }
24
25 RESULT eBouquet::removeService(const eServiceReference &ref)
26 {
27         list::iterator it =
28                 std::find(m_services.begin(), m_services.end(), ref);
29         if ( it == m_services.end() )
30                 return -1;
31         m_services.erase(it);
32         return 0;
33 }
34
35 RESULT eBouquet::moveService(const eServiceReference &ref, unsigned int pos)
36 {
37         if ( pos < 0 || pos >= m_services.size() )
38                 return -1;
39         ++pos;
40         list::iterator source=m_services.end();
41         list::iterator dest=m_services.end();
42         bool forward = false;
43         for (list::iterator it(m_services.begin()); it != m_services.end(); ++it)
44         {
45                 if (dest == m_services.end() && !--pos)
46                         dest = it;
47                 if (*it == ref)
48                 {
49                         source = it;
50                         forward = pos>0;
51                 }
52                 if (dest != m_services.end() && source != m_services.end())
53                         break;
54         }
55         if (dest == m_services.end() || source == m_services.end() || source == dest)
56                 return -1;
57         while (source != dest)
58         {
59                 if (forward)
60                         std::iter_swap(source++, source);
61                 else
62                         std::iter_swap(source--, source);
63         }
64         return 0;
65 }
66
67 RESULT eBouquet::flushChanges()
68 {
69         FILE *f=fopen((CONFIGDIR"/enigma2/"+m_filename).c_str(), "w");
70         if (!f)
71                 return -1;
72         if ( fprintf(f, "#NAME %s\r\n", m_bouquet_name.c_str()) < 0 )
73                 goto err;
74         for (list::iterator i(m_services.begin()); i != m_services.end(); ++i)
75         {
76                 eServiceReference tmp = *i;
77                 std::string str = tmp.path;
78                 if ( (i->flags&eServiceReference::flagDirectory) == eServiceReference::flagDirectory )
79                 {
80                         unsigned int p1 = str.find("FROM BOUQUET \"");
81                         if (p1 == std::string::npos)
82                         {
83                                 eDebug("doof... kaputt");
84                                 continue;
85                         }
86                         str.erase(0, p1+14);
87                         p1 = str.find("\"");
88                         if (p1 == std::string::npos)
89                         {
90                                 eDebug("doof2... kaputt");
91                                 continue;
92                         }
93                         str.erase(p1);
94                         tmp.path=str;
95                 }
96                 if ( fprintf(f, "#SERVICE %s\r\n", tmp.toString().c_str()) < 0 )
97                         goto err;
98                 if ( i->name.length() )
99                         if ( fprintf(f, "#DESCRIPTION %s\r\n", i->name.c_str()) < 0 )
100                                 goto err;
101         }
102         fclose(f);
103         return 0;
104 err:
105         fclose(f);
106         eDebug("couldn't write file %s", m_filename.c_str());
107         return -1;
108 }
109
110 RESULT eBouquet::setListName(const std::string &name)
111 {
112         m_bouquet_name = name;
113         return 0;
114 }
115
116 eDVBService::eDVBService()
117         :m_flags(0)
118 {
119 }
120
121 eDVBService::~eDVBService()
122 {
123 }
124
125 eDVBService &eDVBService::operator=(const eDVBService &s)
126 {
127         m_service_name = s.m_service_name;
128         m_service_name_sort = s.m_service_name_sort;
129         m_provider_name = s.m_provider_name;
130         m_flags = s.m_flags;
131         m_ca = s.m_ca;
132         m_cache = s.m_cache;
133         return *this;
134 }
135
136 void eDVBService::genSortName()
137 {
138         m_service_name_sort = removeDVBChars(m_service_name);
139         makeUpper(m_service_name_sort);
140         while ((!m_service_name_sort.empty()) && m_service_name_sort[0] == ' ')
141                 m_service_name_sort.erase(0, 1);
142
143                 /* put unnamed services at the end, not at the beginning. */
144         if (m_service_name_sort.empty())
145                 m_service_name_sort = "\xFF";
146 }
147
148 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
149 {
150         if (!ref.name.empty())
151                 name = ref.name; // use renamed service name..
152         else if (!m_service_name.empty())
153                 name = m_service_name;
154         else
155                 name = "(...)";
156         return 0;
157 }
158
159 RESULT eDVBService::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &ptr, time_t start_time)
160 {
161         return eEPGCache::getInstance()->lookupEventTime(ref, start_time, ptr);
162 }
163
164 bool eDVBService::isPlayable(const eServiceReference &ref, const eServiceReference &ignore)
165 {
166         ePtr<eDVBResourceManager> res_mgr;
167         if ( eDVBResourceManager::getInstance( res_mgr ) )
168                 eDebug("isPlayble... no res manager!!");
169         else
170         {
171                 eDVBChannelID chid, chid_ignore;
172                 ((const eServiceReferenceDVB&)ref).getChannelID(chid);
173                 ((const eServiceReferenceDVB&)ignore).getChannelID(chid_ignore);
174                 return res_mgr->canAllocateChannel(chid, chid_ignore);
175         }
176         return false;
177 }
178
179 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
180 {
181         int res = 0;
182         switch (query.m_type)
183         {
184         case eDVBChannelQuery::tName:
185                 res = m_service_name_sort.find(query.m_string) != std::string::npos;
186                 break;
187         case eDVBChannelQuery::tProvider:
188                 res = m_provider_name.find(query.m_string) != std::string::npos;
189                 break;
190         case eDVBChannelQuery::tType:
191                 res = ref.getServiceType() == query.m_int;
192                 break;
193         case eDVBChannelQuery::tBouquet:
194                 res = 0;
195                 break;
196         case eDVBChannelQuery::tSatellitePosition:
197                 res = (ref.getDVBNamespace().get() >> 16) == query.m_int;
198                 break;
199         case eDVBChannelQuery::tChannelID:
200         {
201                 eDVBChannelID chid;
202                 ref.getChannelID(chid);
203                 res = chid == query.m_channelid;
204                 break;
205         }
206         case eDVBChannelQuery::tAND:
207                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
208                 break;
209         case eDVBChannelQuery::tOR:
210                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
211                 break;
212         }
213
214         if (query.m_inverse)
215                 return !res;
216         else
217                 return res;
218 }
219
220 int eDVBService::getCachePID(cacheID id)
221 {
222         std::map<int, int>::iterator it = m_cache.find(id);
223         if ( it != m_cache.end() )
224                 return it->second;
225         return -1;
226 }
227
228 void eDVBService::setCachePID(cacheID id, int pid)
229 {
230         if (pid == -1)
231                 m_cache.erase(id);
232         else
233                 m_cache[id] = pid;
234 }
235
236 DEFINE_REF(eDVBDB);
237
238         /* THIS CODE IS BAD. it should be replaced by somethine better. */
239 void eDVBDB::reloadServicelist()
240 {
241         eDebug("---- opening lame channel db");
242         FILE *f=fopen(CONFIGDIR"/enigma2/lamedb", "rt");
243         if (!f)
244         {
245                 struct stat s;
246                 if ( !stat("lamedb", &s) )
247                 {
248                         if ( !stat(CONFIGDIR"/enigma2", &s) )
249                         {
250                                 rename("lamedb", CONFIGDIR"/enigma2/lamedb" );
251                                 reloadServicelist();
252                         }
253                 }
254                 return;
255         }
256         char line[256];
257         if ((!fgets(line, 256, f)) || strncmp(line, "eDVB services", 13))
258         {
259                 eDebug("not a servicefile");
260                 fclose(f);
261                 return;
262         }
263         eDebug("reading services");
264         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
265         {
266                 eDebug("services invalid, no transponders");
267                 fclose(f);
268                 return;
269         }
270
271         // clear all transponders
272
273         while (!feof(f))
274         {
275                 if (!fgets(line, 256, f))
276                         break;
277                 if (!strcmp(line, "end\n"))
278                         break;
279                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
280                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
281                 if (original_network_id == -1)
282                         continue;
283                 eDVBChannelID channelid = eDVBChannelID(
284                         eDVBNamespace(dvb_namespace),
285                         eTransportStreamID(transport_stream_id),
286                         eOriginalNetworkID(original_network_id));
287
288                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
289                 while (!feof(f))
290                 {
291                         fgets(line, 256, f);
292                         if (!strcmp(line, "/\n"))
293                                 break;
294                         if (line[1]=='s')
295                         {
296                                 eDVBFrontendParametersSatellite sat;
297                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion;
298                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion);
299                                 sat.frequency = frequency;
300                                 sat.symbol_rate = symbol_rate;
301                                 sat.polarisation = polarisation;
302                                 sat.fec = fec;
303                                 sat.orbital_position =
304                                         orbital_position < 0 ? orbital_position + 3600 : orbital_position;
305                                 sat.inversion = inversion;
306                                 feparm->setDVBS(sat);
307                         } else if (line[1]=='t')
308                         {
309                                 eDVBFrontendParametersTerrestrial ter;
310                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion;
311                                 sscanf(line+2, "%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &bandwidth, &code_rate_HP, &code_rate_LP, &modulation, &transmission_mode, &guard_interval, &hierarchy, &inversion);
312                                 ter.frequency = frequency;
313                                 ter.bandwidth = bandwidth;
314                                 ter.code_rate_HP = code_rate_HP;
315                                 ter.code_rate_LP = code_rate_LP;
316                                 ter.modulation = modulation;
317                                 ter.transmission_mode = transmission_mode;
318                                 ter.guard_interval = guard_interval;
319                                 ter.hierarchy = hierarchy;
320                                 ter.inversion = inversion;
321                                 feparm->setDVBT(ter);
322                         } else if (line[1]=='c')
323                         {
324                                 eDVBFrontendParametersCable cab;
325                                 int frequency, symbol_rate,
326                                         inversion=eDVBFrontendParametersCable::Inversion::Unknown,
327                                         modulation=eDVBFrontendParametersCable::Modulation::Auto,
328                                         fec_inner=eDVBFrontendParametersCable::FEC::fAuto;
329                                 sscanf(line+2, "%d:%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation, &fec_inner);
330                                 cab.frequency = frequency;
331                                 cab.fec_inner = fec_inner;
332                                 cab.inversion = inversion;
333                                 cab.symbol_rate = symbol_rate;
334                                 cab.modulation = modulation;
335                                 feparm->setDVBC(cab);
336                         }
337                 }
338                 addChannelToList(channelid, feparm);
339         }
340
341         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
342         {
343                 eDebug("services invalid, no services");
344                 return;
345         }
346
347         // clear all services
348
349         int count=0;
350
351         while (!feof(f))
352         {
353                 if (!fgets(line, 256, f))
354                         break;
355                 if (!strcmp(line, "end\n"))
356                         break;
357
358                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
359                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
360                 if (service_number == -1)
361                         continue;
362                 ePtr<eDVBService> s = new eDVBService;
363                 eServiceReferenceDVB ref =
364                                                 eServiceReferenceDVB(
365                                                 eDVBNamespace(dvb_namespace),
366                                                 eTransportStreamID(transport_stream_id),
367                                                 eOriginalNetworkID(original_network_id),
368                                                 eServiceID(service_id),
369                                                 service_type);
370                 count++;
371                 fgets(line, 256, f);
372                 if (strlen(line))
373                         line[strlen(line)-1]=0;
374
375                 s->m_service_name = line;
376                 s->genSortName();
377
378                 fgets(line, 256, f);
379                 if (strlen(line))
380                         line[strlen(line)-1]=0;
381                 std::string str=line;
382
383                 if (str[1]!=':')        // old ... (only service_provider)
384                 {
385                         s->m_provider_name=line;
386                 } else
387                         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
388                         {
389                                 unsigned int c=str.find(',');
390                                 char p=str[0];
391                                 std::string v;
392                                 if (c == std::string::npos)
393                                 {
394                                         v=str.substr(2);
395                                         str="";
396                                 } else
397                                 {
398                                         v=str.substr(2, c-2);
399                                         str=str.substr(c+1);
400                                 }
401 //                              eDebug("%c ... %s", p, v.c_str());
402                                 if (p == 'p')
403                                         s->m_provider_name=v;
404                                 else if (p == 'f')
405                                 {
406                                         sscanf(v.c_str(), "%x", &s->m_flags);
407                                 } else if (p == 'c')
408                                 {
409                                         int cid, val;
410                                         sscanf(v.c_str(), "%02d%04x", &cid, &val);
411                                         s->m_cache[cid]=val;
412                                 } else if (p == 'C')
413                                 {
414                                         int val;
415                                         sscanf(v.c_str(), "%04x", &val);
416                                         s->m_ca.insert(val);
417                                 }
418                         }
419                 addService(ref, s);
420         }
421
422         eDebug("loaded %d services", count);
423
424         fclose(f);
425 }
426
427 void eDVBDB::saveServicelist()
428 {
429         eDebug("---- saving lame channel db");
430         FILE *f=fopen(CONFIGDIR"/enigma2/lamedb", "w");
431         int channels=0, services=0;
432         if (!f)
433                 eFatal("couldn't save lame channel db!");
434         fprintf(f, "eDVB services /3/\n");
435         fprintf(f, "transponders\n");
436         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
437                         i != m_channels.end(); ++i)
438         {
439                 const eDVBChannelID &chid = i->first;
440                 const channel &ch = i->second;
441
442                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
443                                 chid.transport_stream_id.get(), chid.original_network_id.get());
444                 eDVBFrontendParametersSatellite sat;
445                 eDVBFrontendParametersTerrestrial ter;
446                 eDVBFrontendParametersCable cab;
447                 if (!ch.m_frontendParameters->getDVBS(sat))
448                 {
449                         fprintf(f, "\ts %d:%d:%d:%d:%d:%d\n",
450                                 sat.frequency, sat.symbol_rate,
451                                 sat.polarisation, sat.fec,
452                                 sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
453                                 sat.inversion);
454                 }
455                 if (!ch.m_frontendParameters->getDVBT(ter))
456                 {
457                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d\n",
458                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
459                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
460                                 ter.guard_interval, ter.hierarchy, ter.inversion);
461                 }
462                 if (!ch.m_frontendParameters->getDVBC(cab))
463                 {
464                         fprintf(f, "\tc %d:%d:%d:%d:%d\n",
465                                 cab.frequency, cab.symbol_rate, cab.inversion, cab.modulation, cab.fec_inner);
466                 }
467                 fprintf(f, "/\n");
468                 channels++;
469         }
470         fprintf(f, "end\nservices\n");
471
472         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
473                 i != m_services.end(); ++i)
474         {
475                 const eServiceReferenceDVB &s = i->first;
476                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
477                                 s.getServiceID().get(), s.getDVBNamespace().get(),
478                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
479                                 s.getServiceType(),
480                                 0);
481
482                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
483
484                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
485
486                 // write cached pids
487                 for (std::map<int,int>::const_iterator ca(i->second->m_cache.begin());
488                         ca != i->second->m_cache.end(); ++ca)
489                         fprintf(f, ",c:%02d%04x", ca->first, ca->second);
490
491                 // write cached ca pids
492                 for (std::set<int>::const_iterator ca(i->second->m_ca.begin());
493                         ca != i->second->m_ca.end(); ++ca)
494                         fprintf(f, ",C:%04x", *ca);
495
496                 if (i->second->m_flags)
497                         fprintf(f, ",f:%x", i->second->m_flags);
498
499                 fprintf(f, "\n");
500                 services++;
501         }
502         fprintf(f, "end\nHave a lot of bugs!\n");
503         eDebug("saved %d channels and %d services!", channels, services);
504         fclose(f);
505 }
506
507 void eDVBDB::loadBouquet(const char *path)
508 {
509         std::string bouquet_name = path;
510         if (!bouquet_name.length())
511         {
512                 eDebug("Bouquet load failed.. no path given..");
513                 return;
514         }
515         unsigned int pos = bouquet_name.rfind('/');
516         if ( pos != std::string::npos )
517                 bouquet_name.erase(0, pos+1);
518         if (bouquet_name.empty())
519         {
520                 eDebug("Bouquet load failed.. no filename given..");
521                 return;
522         }
523         eBouquet &bouquet = m_bouquets[bouquet_name];
524         bouquet.m_filename = bouquet_name;
525         std::list<eServiceReference> &list = bouquet.m_services;
526         list.clear();
527
528         std::string p = CONFIGDIR"/enigma2/";
529         p+=path;
530         eDebug("loading bouquet... %s", p.c_str());
531         FILE *fp=fopen(p.c_str(), "rt");
532         int entries=0;
533         if (!fp)
534         {
535                 struct stat s;
536                 if ( !stat(path, &s) )
537                 {
538                         rename(path, p.c_str() );
539                         loadBouquet(path);
540                         return;
541                 }
542                 eDebug("failed to open.");
543                 if ( strstr(path, "bouquets.tv") )
544                 {
545                         eDebug("recreate bouquets.tv");
546                         bouquet.m_bouquet_name="Bouquets (TV)";
547                         bouquet.flushChanges();
548                 }
549                 else if ( strstr(path, "bouquets.radio") )
550                 {
551                         eDebug("recreate bouquets.radio");
552                         bouquet.m_bouquet_name="Bouquets (Radio)";
553                         bouquet.flushChanges();
554                 }
555                 return;
556         }
557         char line[256];
558         bool read_descr=false;
559         eServiceReference *e = NULL;
560         while (1)
561         {
562                 if (!fgets(line, 256, fp))
563                         break;
564                 line[strlen(line)-1]=0;
565                 if (strlen(line) && line[strlen(line)-1]=='\r')
566                         line[strlen(line)-1]=0;
567                 if (!line[0])
568                         break;
569                 if (line[0]=='#')
570                 {
571                         if (!strncmp(line, "#SERVICE ", 9) || !strncmp(line, "#SERVICE: ", 10))
572                         {
573                                 int offs = line[8] == ':' ? 10 : 9;
574                                 eServiceReference tmp(line+offs);
575                                 if (tmp.type != eServiceReference::idDVB)
576                                 {
577                                         eDebug("only DVB Bouquets supported");
578                                         continue;
579                                 }
580                                 if ( (tmp.flags&eServiceReference::flagDirectory) == eServiceReference::flagDirectory )
581                                 {
582                                         unsigned int pos = tmp.path.rfind('/');
583                                         if ( pos != std::string::npos )
584                                                 tmp.path.erase(0, pos+1);
585                                         if (tmp.path.empty())
586                                         {
587                                                 eDebug("Bouquet load failed.. no filename given..");
588                                                 continue;
589                                         }
590                                         loadBouquet(tmp.path.c_str());
591                                         char buf[256];
592                                         snprintf(buf, 256, "(type == %d) FROM BOUQUET \"%s\" ORDER BY bouquet", tmp.data[0], tmp.path.c_str());
593                                         tmp.path = buf;
594                                 }
595                                 list.push_back(tmp);
596                                 e = &list.back();
597                                 read_descr=true;
598                                 ++entries;
599                         }
600                         else if (read_descr && !strncmp(line, "#DESCRIPTION ", 13))
601                         {
602                                 e->name = line+13;
603                                 read_descr=false;
604                         }
605                         else if (!strncmp(line, "#NAME ", 6))
606                                 bouquet.m_bouquet_name=line+6;
607                         continue;
608                 }
609         }
610         fclose(fp);
611         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
612 }
613
614 void eDVBDB::reloadBouquets()
615 {
616         m_bouquets.clear();
617         loadBouquet("bouquets.tv");
618         loadBouquet("bouquets.radio");
619 // create default bouquets when missing
620         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
621         {
622                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
623                 b.m_filename = "userbouquet.favourites.tv";
624                 b.m_bouquet_name = "Favourites (TV)";
625                 b.flushChanges();
626                 eServiceReference ref;
627                 memset(ref.data, 0, sizeof(ref.data));
628                 ref.type=1;
629                 ref.flags=7;
630                 ref.data[0]=1;
631                 ref.path="(type == 1) FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
632                 eBouquet &parent = m_bouquets["bouquets.tv"];
633                 parent.m_services.push_back(ref);
634                 parent.flushChanges();
635         }
636         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
637         {
638                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
639                 b.m_filename = "userbouquet.favourites.radio";
640                 b.m_bouquet_name = "Favourites (Radio)";
641                 b.flushChanges();
642                 eServiceReference ref;
643                 memset(ref.data, 0, sizeof(ref.data));
644                 ref.type=1;
645                 ref.flags=7;
646                 ref.data[0]=2;
647                 ref.path="(type == 2) FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
648                 eBouquet &parent = m_bouquets["bouquets.radio"];
649                 parent.m_services.push_back(ref);
650                 parent.flushChanges();
651         }
652 }
653
654 eDVBDB *eDVBDB::instance;
655
656 eDVBDB::eDVBDB()
657 {
658         instance = this;
659         reloadServicelist();
660 }
661
662 eDVBDB::~eDVBDB()
663 {
664         instance=NULL;
665 }
666
667 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
668 {
669         channel ch;
670         assert(feparm);
671         ch.m_frontendParameters = feparm;
672         m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
673         return 0;
674 }
675
676 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
677 {
678         m_channels.erase(id);
679         return 0;
680 }
681
682 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
683 {
684         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
685         if (i == m_channels.end())
686         {
687                 parm = 0;
688                 return -ENOENT;
689         }
690         parm = i->second.m_frontendParameters;
691         return 0;
692 }
693
694 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
695 {
696         m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
697         return 0;
698 }
699
700 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
701 {
702         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
703         i = m_services.find(reference);
704         if (i == m_services.end())
705         {
706                 service = 0;
707                 return -ENOENT;
708         }
709         service = i->second;
710         return 0;
711 }
712
713 RESULT eDVBDB::flush()
714 {
715         saveServicelist();
716         return 0;
717 }
718
719 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
720 {
721         std::string str = ref.path;
722         if (str.empty())
723         {
724                 eDebug("getBouquet failed.. no path given!");
725                 return -1;
726         }
727         unsigned int pos = str.find("FROM BOUQUET \"");
728         if ( pos != std::string::npos )
729         {
730                 str.erase(0, pos+14);
731                 pos = str.find('"');
732                 if ( pos != std::string::npos )
733                         str.erase(pos);
734                 else
735                         str.clear();
736         }
737         if (str.empty())
738         {
739                 eDebug("getBouquet failed.. couldn't parse bouquet name");
740                 return -1;
741         }
742         std::map<std::string, eBouquet>::iterator i =
743                 m_bouquets.find(str);
744         if (i == m_bouquets.end())
745         {
746                 bouquet = 0;
747                 return -ENOENT;
748         }
749         bouquet = &i->second;
750         return 0;
751 }
752
753 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
754 {
755         if ( source.path.find("FROM") != std::string::npos )
756         {
757                 if ( source.path.find("BOUQUET") != std::string::npos )
758                         query = new eDVBDBBouquetQuery(this, source, q);
759                 else if ( source.path.find("SATELLITES") != std::string::npos )
760                         query = new eDVBDBSatellitesQuery(this, source, q);
761                 else if ( source.path.find("PROVIDERS") != std::string::npos )
762                         query = new eDVBDBProvidersQuery(this, source, q);
763                 else
764                         eFatal("invalid query %s", source.toString().c_str());
765         }
766         else
767                 query = new eDVBDBQuery(this, source, q);
768         return 0;
769 }
770
771 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
772 {
773         eServiceID Sid(sid);
774         eTransportStreamID Tsid(tsid);
775         eOriginalNetworkID Onid(onid);
776         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
777                 sit != m_services.end(); ++sit)
778         {
779                 if (sit->first.getTransportStreamID() == Tsid &&
780                         sit->first.getOriginalNetworkID() == Onid &&
781                         sit->first.getServiceID() == Sid)
782                         return sit->first;
783         }
784         return eServiceReference();
785 }
786
787 DEFINE_REF(eDVBDBQueryBase);
788
789 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
790         :m_db(db), m_query(query), m_source(source)
791 {
792 }
793
794 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
795 {
796         ePtr<eDVBService> a_service, b_service;
797         
798         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
799         
800         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
801         {
802                 if (m_db->getService(a, a_service))
803                         return 1;
804                 if (m_db->getService(b, b_service))
805                         return 1;
806         }
807         
808         switch (sortmode)
809         {
810         case eDVBChannelQuery::tName:
811                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
812         case eDVBChannelQuery::tProvider:
813                 return a_service->m_provider_name < b_service->m_provider_name;
814         case eDVBChannelQuery::tType:
815                 return a.getServiceType() < b.getServiceType();
816         case eDVBChannelQuery::tBouquet:
817                 return 0;
818         case eDVBChannelQuery::tSatellitePosition:
819                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
820         default:
821                 return 1;
822         }
823         return 0;
824 }
825
826 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
827         :eDVBDBQueryBase(db, source, query)
828 {
829         m_cursor = m_db->m_services.begin();
830 }
831
832 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
833 {
834         while (m_cursor != m_db->m_services.end())
835         {
836                 ref = m_cursor->first;
837
838                 int res = (!m_query) || m_cursor->second->checkFilter(ref, *m_query);
839
840                 ++m_cursor;
841
842                 if (res)
843                         return 0;
844         }
845
846         ref.type = eServiceReference::idInvalid;
847
848         return 1;
849 }
850
851 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
852         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
853 {
854 }
855
856 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
857 {
858         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
859         std::list<eServiceReference> &list = bouquet.m_services;
860         while (m_cursor != list.end())
861         {
862                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
863
864                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
865                         m_db->m_services.find(ref);
866
867                 int res = (!m_query) || it == m_db->m_services.end() || it->second->checkFilter(ref, *m_query);
868
869                 ++m_cursor;
870
871                 if (res)
872                         return 0;
873         }
874
875         ref.type = eServiceReference::idInvalid;
876
877         return 1;
878 }
879
880 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
881         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
882 {
883 }
884
885 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
886 {
887         if (m_cursor != m_list.end())
888         {
889                 ref = *m_cursor++;
890                 return 0;
891         }
892         ref.type = eServiceReference::idInvalid;
893         return 1;
894 }
895
896 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
897 {
898         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
899         {
900                 int x = (a.getDVBNamespace().get() >> 16);
901                 int y = (b.getDVBNamespace().get() >> 16);
902                 if ( x > 1800 )
903                         x -= 3600;
904                 if ( y > 1800 )
905                         y -= 3600;
906                 return x < y;
907         }
908         return a.name < b.name;
909 }
910
911 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
912         :eDVBDBListQuery(db, source, query)
913 {
914         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
915                 it != m_db->m_services.end(); ++it)
916         {
917                 int res = it->second->checkFilter(it->first, *query);
918                 if (res)
919                 {
920                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
921                         bool found=0;
922                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
923                                 if ( (i->getDVBNamespace().get()&0xFFFF0000) == dvbnamespace )
924                                 {
925                                         found=true;
926                                         break;
927                                 }
928                         if (!found)
929                         {
930                                 eServiceReferenceDVB ref;
931                                 ref.setDVBNamespace(dvbnamespace);
932                                 ref.flags=eServiceReference::flagDirectory;
933                                 char buf[64];
934                                 snprintf(buf, 64, "(satellitePosition == %d) && ", dvbnamespace>>16);
935
936                                 ref.path=buf+source.path;
937                                 unsigned int pos=ref.path.find("FROM");
938                                 ref.path.erase(pos);
939                                 ref.path+="ORDER BY name";
940 //                              eDebug("ref.path now %s", ref.path.c_str());
941                                 m_list.push_back(ref);
942
943                                 ref.path=buf+source.path;
944                                 pos=ref.path.find("FROM");
945                                 ref.path.erase(pos+5);
946                                 ref.path+="PROVIDERS ORDER BY name";
947 //                              eDebug("ref.path now %s", ref.path.c_str());
948                                 m_list.push_back(ref);
949                         }
950                 }
951         }
952         m_cursor=m_list.begin();
953 }
954
955 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
956         :eDVBDBListQuery(db, source, query)
957 {
958         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
959                 it != m_db->m_services.end(); ++it)
960         {
961                 int res = it->second->checkFilter(it->first, *query);
962                 if (res)
963                 {
964                         bool found=0;
965
966                         const char *provider_name = it->second->m_provider_name.length() ?
967                                 it->second->m_provider_name.c_str() :
968                                 "Unknown";
969
970                         for (std::list<eServiceReferenceDVB>::iterator i(m_list.begin()); i != m_list.end(); ++i)
971                                 if (i->name == provider_name)
972                                 {
973                                         found=true;
974                                         break;
975                                 }
976                         if (!found)
977                         {
978                                 eServiceReferenceDVB ref;
979                                 char buf[64];
980                                 ref.name=provider_name;
981                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
982                                 ref.path=buf+source.path;
983                                 unsigned int pos = ref.path.find("FROM");
984                                 ref.flags=eServiceReference::flagDirectory;
985                                 ref.path.erase(pos);
986                                 ref.path+="ORDER BY name";
987 //                              eDebug("ref.path now %s", ref.path.c_str());
988                                 m_list.push_back(ref);
989                         }
990                 }
991         }
992         m_cursor=m_list.begin();
993 }
994
995 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
996
997 static int decodeType(const std::string &type)
998 {
999         if (type == "name")
1000                 return eDVBChannelQuery::tName;
1001         else if (type == "provider")
1002                 return eDVBChannelQuery::tProvider;
1003         else if (type == "type")
1004                 return eDVBChannelQuery::tType;
1005         else if (type == "bouquet")
1006                 return eDVBChannelQuery::tBouquet;
1007         else if (type == "satellitePosition")
1008                 return eDVBChannelQuery::tSatellitePosition;
1009         else if (type == "channelID")
1010                 return eDVBChannelQuery::tChannelID;
1011         else
1012                 return -1;
1013 }
1014
1015         /* never, NEVER write a parser in C++! */
1016 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1017 {
1018         std::list<std::string>::const_iterator end_of_exp;
1019         if (*begin == "(")
1020         {
1021                 end_of_exp = begin;
1022                 while (end_of_exp != end)
1023                         if (*end_of_exp == ")")
1024                                 break;
1025                         else
1026                                 ++end_of_exp;
1027         
1028                 if (end_of_exp == end)
1029                 {
1030                         eDebug("expression parse: end of expression while searching for closing brace");
1031                         return -1;
1032                 }
1033                 
1034                 ++begin;
1035                 // begin..end_of_exp
1036                 int r = parseExpression(res, begin, end_of_exp);
1037                 if (r)
1038                         return r;
1039                 ++end_of_exp;
1040                 
1041                         /* we had only one sub expression */
1042                 if (end_of_exp == end)
1043                 {
1044 //                      eDebug("only one sub expression");
1045                         return 0;
1046                 }
1047                 
1048                         /* otherwise we have an operator here.. */
1049                 
1050                 ePtr<eDVBChannelQuery> r2 = res;
1051                 res = new eDVBChannelQuery();
1052                 res->m_sort = 0;
1053                 res->m_p1 = r2;
1054                 res->m_inverse = 0;
1055                 r2 = 0;
1056                 
1057                 if (*end_of_exp == "||")
1058                         res->m_type = eDVBChannelQuery::tOR;
1059                 else if (*end_of_exp == "&&")
1060                         res->m_type = eDVBChannelQuery::tAND;
1061                 else
1062                 {
1063                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1064                         res = 0;
1065                         return 1;
1066                 }
1067                 
1068                 ++end_of_exp;
1069                 
1070                 return parseExpression(res->m_p2, end_of_exp, end);
1071         }
1072         
1073         // "begin" <op> "end"
1074         std::string type, op, val;
1075         
1076         res = new eDVBChannelQuery();
1077         res->m_sort = 0;
1078         
1079         int cnt = 0;
1080         while (begin != end)
1081         {
1082                 switch (cnt)
1083                 {
1084                 case 0:
1085                         type = *begin;
1086                         break;
1087                 case 1:
1088                         op = *begin;
1089                         break;
1090                 case 2:
1091                         val = *begin;
1092                         break;
1093                 case 3:
1094                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1095                         return 1;
1096                 }
1097                 ++begin;
1098                 ++cnt;
1099         }
1100         
1101         if (cnt != 3)
1102         {
1103                 eDebug("malformed query: missing stuff");
1104                 res = 0;
1105                 return 1;
1106         }
1107         
1108         res->m_type = decodeType(type);
1109         
1110         if (res->m_type == -1)
1111         {
1112                 eDebug("malformed query: invalid type %s", type.c_str());
1113                 res = 0;
1114                 return 1;
1115         }
1116         
1117         if (op == "==")
1118                 res->m_inverse = 0;
1119         else if (op == "!=")
1120                 res->m_inverse = 1;
1121         else
1122         {
1123                 eDebug("invalid operator %s", op.c_str());
1124                 res = 0;
1125                 return 1;
1126         }
1127         
1128         res->m_string = val;
1129         res->m_int = atoi(val.c_str());
1130 //      res->m_channelid = eDVBChannelID(val);
1131         
1132         return 0;
1133 }
1134
1135 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1136 {
1137         std::list<std::string> tokens;
1138         
1139         std::string current_token;
1140         std::string bouquet_name;
1141
1142 //      eDebug("splitting %s....", query.c_str());
1143         unsigned int i = 0;
1144         const char *splitchars="()";
1145         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1146         while (i <= query.size())
1147         {
1148                 int c = (i < query.size()) ? query[i] : ' ';
1149                 ++i;
1150                 
1151                 int issplit = !!strchr(splitchars, c);
1152                 int isaln = isalnum(c);
1153                 int iswhite = c == ' ';
1154                 int isquot = c == '\"';
1155                 
1156                 if (quotemode)
1157                 {
1158                         iswhite = issplit = 0;
1159                         isaln = lastalnum;
1160                 }
1161                 
1162                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1163                 {
1164                         if (current_token.size())
1165                                 tokens.push_back(current_token);
1166                         current_token.clear();
1167                 }
1168                 
1169                 if (!(iswhite || isquot))
1170                         current_token += c;
1171                 
1172                 if (isquot)
1173                         quotemode = !quotemode;
1174                 lastsplit = issplit;
1175                 lastalnum = isaln;
1176         }
1177         
1178 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1179 //      {
1180 //              printf("%s\n", a->c_str());
1181 //      }
1182
1183         int sort = eDVBChannelQuery::tName;
1184                 /* check for "ORDER BY ..." */
1185
1186         std::list<std::string>::iterator it = tokens.begin();
1187         while (it != tokens.end())
1188         {
1189                 if (*it == "ORDER")
1190                 {
1191                         tokens.erase(it++);
1192                         if (it != tokens.end() && *it == "BY")
1193                         {
1194                                 tokens.erase(it++);
1195                                 sort = decodeType(*it);
1196                                 tokens.erase(it++);
1197                         } else
1198                                 sort = -1;
1199                 }
1200                 else if (*it == "FROM")
1201                 {
1202                         tokens.erase(it++);
1203                         if (it != tokens.end() && *it == "BOUQUET")
1204                         {
1205                                 tokens.erase(it++);
1206                                 bouquet_name = *it;
1207                                 tokens.erase(it++);
1208                         }
1209                         else if (it != tokens.end() && *it == "SATELLITES")
1210                                 tokens.erase(it++);
1211                         else if (it != tokens.end() && *it == "PROVIDERS")
1212                                 tokens.erase(it++);
1213                         else
1214                         {
1215                                 eDebug("FROM unknown %s", (*it).c_str());
1216                                 tokens.erase(it++);
1217                         }
1218                 }
1219                 else
1220                         ++it;
1221         }
1222
1223         if (sort == -1)
1224         {
1225                 eWarning("ORDER BY .. string invalid.");
1226                 res = 0;
1227                 return -1;
1228         }
1229         
1230 //      eDebug("sort by %d", sort);
1231         
1232                 /* now we recursivly parse that. */
1233         int r = parseExpression(res, tokens.begin(), tokens.end());
1234         
1235         if (res)
1236         {
1237                 res->m_sort = sort;
1238                 res->m_bouquet_name = bouquet_name;
1239         }
1240
1241 //      eDebug("return: %d", r);
1242         return r;
1243 }
1244
1245 DEFINE_REF(eDVBChannelQuery);