lib/dvb/db.cpp: skip unknown attributes in satellites/cables/terrestrial.xml
[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 <xmlccwrap/xmlccwrap.h>
9 #include <dvbsi++/service_description_section.h>
10 #include <dvbsi++/descriptor_tag.h>
11 #include <dvbsi++/service_descriptor.h>
12 #include <dvbsi++/satellite_delivery_system_descriptor.h>
13
14 DEFINE_REF(eDVBService);
15
16 RESULT eBouquet::addService(const eServiceReference &ref, eServiceReference before)
17 {
18         list::iterator it =
19                 std::find(m_services.begin(), m_services.end(), ref);
20         if ( it != m_services.end() )
21                 return -1;
22         if (before.valid())
23         {
24                 it = std::find(m_services.begin(), m_services.end(), before);
25                 m_services.insert(it, ref);
26         }
27         else
28                 m_services.push_back(ref);
29         return 0;
30 }
31
32 RESULT eBouquet::removeService(const eServiceReference &ref)
33 {
34         list::iterator it =
35                 std::find(m_services.begin(), m_services.end(), ref);
36         if ( it == m_services.end() )
37                 return -1;
38         m_services.erase(it);
39         return 0;
40 }
41
42 RESULT eBouquet::moveService(const eServiceReference &ref, unsigned int pos)
43 {
44         if ( pos < 0 || pos >= m_services.size() )
45                 return -1;
46         ++pos;
47         list::iterator source=m_services.end();
48         list::iterator dest=m_services.end();
49         bool forward = false;
50         for (list::iterator it(m_services.begin()); it != m_services.end(); ++it)
51         {
52                 if (dest == m_services.end() && !--pos)
53                         dest = it;
54                 if (*it == ref)
55                 {
56                         source = it;
57                         forward = pos>0;
58                 }
59                 if (dest != m_services.end() && source != m_services.end())
60                         break;
61         }
62         if (dest == m_services.end() || source == m_services.end() || source == dest)
63                 return -1;
64         while (source != dest)
65         {
66                 if (forward)
67                         std::iter_swap(source++, source);
68                 else
69                         std::iter_swap(source--, source);
70         }
71         return 0;
72 }
73
74 RESULT eBouquet::flushChanges()
75 {
76         FILE *f=fopen((CONFIGDIR"/enigma2/"+m_filename).c_str(), "w");
77         if (!f)
78                 return -1;
79         if ( fprintf(f, "#NAME %s\r\n", m_bouquet_name.c_str()) < 0 )
80                 goto err;
81         for (list::iterator i(m_services.begin()); i != m_services.end(); ++i)
82         {
83                 eServiceReference tmp = *i;
84                 std::string str = tmp.path;
85                 if ( fprintf(f, "#SERVICE %s\r\n", tmp.toString().c_str()) < 0 )
86                         goto err;
87                 if ( i->name.length() )
88                         if ( fprintf(f, "#DESCRIPTION %s\r\n", i->name.c_str()) < 0 )
89                                 goto err;
90         }
91         fclose(f);
92         return 0;
93 err:
94         fclose(f);
95         eDebug("couldn't write file %s", m_filename.c_str());
96         return -1;
97 }
98
99 RESULT eBouquet::setListName(const std::string &name)
100 {
101         m_bouquet_name = name;
102         return 0;
103 }
104
105 eDVBService::eDVBService()
106         :m_cache(0), m_flags(0)
107 {
108 }
109
110 eDVBService::~eDVBService()
111 {
112         delete [] m_cache;
113 }
114
115 eDVBService &eDVBService::operator=(const eDVBService &s)
116 {
117         m_service_name = s.m_service_name;
118         m_service_name_sort = s.m_service_name_sort;
119         m_provider_name = s.m_provider_name;
120         m_flags = s.m_flags;
121         m_ca = s.m_ca;
122         copyCache(s.m_cache);
123         return *this;
124 }
125
126 void eDVBService::genSortName()
127 {
128         m_service_name_sort = removeDVBChars(m_service_name);
129         makeUpper(m_service_name_sort);
130         while ((!m_service_name_sort.empty()) && m_service_name_sort[0] == ' ')
131                 m_service_name_sort.erase(0, 1);
132
133                 /* put unnamed services at the end, not at the beginning. */
134         if (m_service_name_sort.empty())
135                 m_service_name_sort = "\xFF";
136 }
137
138 RESULT eDVBService::getName(const eServiceReference &ref, std::string &name)
139 {
140         if (!ref.name.empty())
141                 name = ref.name; // use renamed service name..
142         else if (!m_service_name.empty())
143                 name = m_service_name;
144         else
145                 name = "(...)";
146         return 0;
147 }
148
149 RESULT eDVBService::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &ptr, time_t start_time)
150 {
151         return eEPGCache::getInstance()->lookupEventTime(ref, start_time, ptr);
152 }
153
154 int eDVBService::isPlayable(const eServiceReference &ref, const eServiceReference &ignore, bool simulate)
155 {
156         ePtr<eDVBResourceManager> res_mgr;
157         if ( eDVBResourceManager::getInstance( res_mgr ) )
158                 eDebug("isPlayble... no res manager!!");
159         else
160         {
161                 eDVBChannelID chid, chid_ignore;
162                 ((const eServiceReferenceDVB&)ref).getChannelID(chid);
163                 ((const eServiceReferenceDVB&)ignore).getChannelID(chid_ignore);
164                 return res_mgr->canAllocateChannel(chid, chid_ignore, simulate);
165         }
166         return 0;
167 }
168
169 int eDVBService::checkFilter(const eServiceReferenceDVB &ref, const eDVBChannelQuery &query)
170 {
171         int res = 0;
172         switch (query.m_type)
173         {
174         case eDVBChannelQuery::tName:
175                 res = m_service_name_sort.find(query.m_string) != std::string::npos;
176                 break;
177         case eDVBChannelQuery::tProvider:
178                 res = m_provider_name.find(query.m_string) != std::string::npos;
179                 break;
180         case eDVBChannelQuery::tType:
181                 res = ref.getServiceType() == query.m_int;
182                 break;
183         case eDVBChannelQuery::tBouquet:
184                 res = 0;
185                 break;
186         case eDVBChannelQuery::tSatellitePosition:
187                 res = ((unsigned int)ref.getDVBNamespace().get())>>16 == (unsigned int)query.m_int;
188                 break;
189         case eDVBChannelQuery::tFlags:
190                 res = (m_flags & query.m_int) == query.m_int;
191                 break;
192         case eDVBChannelQuery::tChannelID:
193         {
194                 eDVBChannelID chid;
195                 ref.getChannelID(chid);
196                 res = chid == query.m_channelid;
197                 break;
198         }
199         case eDVBChannelQuery::tAND:
200                 res = checkFilter(ref, *query.m_p1) && checkFilter(ref, *query.m_p2);
201                 break;
202         case eDVBChannelQuery::tOR:
203                 res = checkFilter(ref, *query.m_p1) || checkFilter(ref, *query.m_p2);
204                 break;
205         case eDVBChannelQuery::tAny:
206                 res = 1;
207                 break;
208         }
209
210         if (query.m_inverse)
211                 return !res;
212         else
213                 return res;
214 }
215
216 bool eDVBService::cacheEmpty()
217 {
218         if (m_cache)
219                 for (int i=0; i < cacheMax; ++i)
220                         if (m_cache[i] != -1)
221                                 return false;
222         return true;
223 }
224
225 void eDVBService::initCache()
226 {
227         m_cache = new int[cacheMax];
228         memset(m_cache, -1, sizeof(int) * cacheMax);
229 }
230
231 void eDVBService::copyCache(int *source)
232 {
233         if (source)
234         {
235                 if (!m_cache)
236                         m_cache = new int[cacheMax];
237                 memcpy(m_cache, source, cacheMax * sizeof(int));
238         }
239         else
240         {
241                 delete [] m_cache;
242                 m_cache = 0;
243         }
244 }
245
246 int eDVBService::getCacheEntry(cacheID id)
247 {
248         if (id >= cacheMax || !m_cache)
249                 return -1;
250         return m_cache[id];
251 }
252
253 void eDVBService::setCacheEntry(cacheID id, int pid)
254 {
255         if (!m_cache)
256                 initCache();
257         if (id < cacheMax)
258                 m_cache[id] = pid;
259 }
260
261 DEFINE_REF(eDVBDB);
262
263 void eDVBDB::reloadServicelist()
264 {
265         loadServicelist(CONFIGDIR"/enigma2/lamedb");
266 }
267
268 void eDVBDB::parseServiceData(ePtr<eDVBService> s, std::string str)
269 {
270         while ((!str.empty()) && str[1]==':') // new: p:, f:, c:%02d...
271         {
272                 size_t c=str.find(',');
273                 char p=str[0];
274                 std::string v;
275                 if (c == std::string::npos)
276                 {
277                         v=str.substr(2);
278                         str="";
279                 } else
280                 {
281                         v=str.substr(2, c-2);
282                         str=str.substr(c+1);
283                 }
284 //              eDebug("%c ... %s", p, v.c_str());
285                 if (p == 'p')
286                         s->m_provider_name=v;
287                 else if (p == 'f')
288                 {
289                         sscanf(v.c_str(), "%x", &s->m_flags);
290                 } else if (p == 'c')
291                 {
292                         int cid, val;
293                         sscanf(v.c_str(), "%02d%x", &cid, &val);
294                         s->setCacheEntry((eDVBService::cacheID)cid,val);
295                 } else if (p == 'C')
296                 {
297                         int val;
298                         sscanf(v.c_str(), "%04x", &val);
299                         s->m_ca.push_front((uint16_t)val);
300                 }
301         }
302 }
303
304         /* THIS CODE IS BAD. it should be replaced by somethine better. */
305 void eDVBDB::loadServicelist(const char *file)
306 {
307         eDebug("---- opening lame channel db");
308         FILE *f=fopen(file, "rt");
309         if (!f && strcmp(file, CONFIGDIR"/enigma2/lamedb") == 0)
310         {
311                 struct stat s;
312                 if ( !stat("lamedb", &s) )
313                 {
314                         if ( !stat(CONFIGDIR"/enigma2", &s) )
315                         {
316                                 rename("lamedb", CONFIGDIR"/enigma2/lamedb" );
317                                 reloadServicelist();
318                         }
319                 }
320                 return;
321         }
322         char line[256];
323         int version=3;
324         if ((!fgets(line, 256, f)) || sscanf(line, "eDVB services /%d/", &version) != 1)
325         {
326                 eDebug("not a valid servicefile");
327                 fclose(f);
328                 return;
329         }
330         eDebug("reading services (version %d)", version);
331         if ((!fgets(line, 256, f)) || strcmp(line, "transponders\n"))
332         {
333                 eDebug("services invalid, no transponders");
334                 fclose(f);
335                 return;
336         }
337
338         // clear all transponders
339
340         while (!feof(f))
341         {
342                 if (!fgets(line, 256, f))
343                         break;
344                 if (!strcmp(line, "end\n"))
345                         break;
346                 int dvb_namespace=-1, transport_stream_id=-1, original_network_id=-1;
347                 sscanf(line, "%x:%x:%x", &dvb_namespace, &transport_stream_id, &original_network_id);
348                 if (original_network_id == -1)
349                         continue;
350                 eDVBChannelID channelid = eDVBChannelID(
351                         eDVBNamespace(dvb_namespace),
352                         eTransportStreamID(transport_stream_id),
353                         eOriginalNetworkID(original_network_id));
354
355                 ePtr<eDVBFrontendParameters> feparm = new eDVBFrontendParameters;
356                 while (!feof(f))
357                 {
358                         fgets(line, 256, f);
359                         if (!strcmp(line, "/\n"))
360                                 break;
361                         if (line[1]=='s')
362                         {
363                                 eDVBFrontendParametersSatellite sat;
364                                 int frequency, symbol_rate, polarisation, fec, orbital_position, inversion,
365                                         flags=0,
366                                         system=eDVBFrontendParametersSatellite::System_DVB_S,
367                                         modulation=eDVBFrontendParametersSatellite::Modulation_QPSK,
368                                         rolloff=eDVBFrontendParametersSatellite::RollOff_alpha_0_35,
369                                         pilot=eDVBFrontendParametersSatellite::Pilot_Unknown;
370                                 if (version == 3)
371                                         sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion, &system, &modulation, &rolloff, &pilot);
372                                 else
373                                         sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &polarisation, &fec, &orbital_position, &inversion, &flags, &system, &modulation, &rolloff, &pilot);
374                                 sat.frequency = frequency;
375                                 sat.symbol_rate = symbol_rate;
376                                 sat.polarisation = polarisation;
377                                 sat.fec = fec;
378                                 sat.orbital_position =
379                                         orbital_position < 0 ? orbital_position + 3600 : orbital_position;
380                                 sat.inversion = inversion;
381                                 sat.system = system;
382                                 sat.modulation = modulation;
383                                 sat.rolloff = rolloff;
384                                 sat.pilot = pilot;
385                                 feparm->setDVBS(sat);
386                                 feparm->setFlags(flags);
387                         } else if (line[1]=='t')
388                         {
389                                 eDVBFrontendParametersTerrestrial ter;
390                                 int frequency, bandwidth, code_rate_HP, code_rate_LP, modulation, transmission_mode, guard_interval, hierarchy, inversion, flags=0;
391                                 sscanf(line+3, "%d:%d:%d:%d:%d:%d:%d:%d:%d:%d", &frequency, &bandwidth, &code_rate_HP, &code_rate_LP, &modulation, &transmission_mode, &guard_interval, &hierarchy, &inversion, &flags);
392                                 ter.frequency = frequency;
393                                 ter.bandwidth = bandwidth;
394                                 ter.code_rate_HP = code_rate_HP;
395                                 ter.code_rate_LP = code_rate_LP;
396                                 ter.modulation = modulation;
397                                 ter.transmission_mode = transmission_mode;
398                                 ter.guard_interval = guard_interval;
399                                 ter.hierarchy = hierarchy;
400                                 ter.inversion = inversion;
401                                 feparm->setDVBT(ter);
402                                 feparm->setFlags(flags);
403                         } else if (line[1]=='c')
404                         {
405                                 eDVBFrontendParametersCable cab;
406                                 int frequency, symbol_rate,
407                                         inversion=eDVBFrontendParametersCable::Inversion_Unknown,
408                                         modulation=eDVBFrontendParametersCable::Modulation_Auto,
409                                         fec_inner=eDVBFrontendParametersCable::FEC_Auto,
410                                         flags=0;
411                                 sscanf(line+3, "%d:%d:%d:%d:%d:%d", &frequency, &symbol_rate, &inversion, &modulation, &fec_inner, &flags);
412                                 cab.frequency = frequency;
413                                 cab.fec_inner = fec_inner;
414                                 cab.inversion = inversion;
415                                 cab.symbol_rate = symbol_rate;
416                                 cab.modulation = modulation;
417                                 feparm->setDVBC(cab);
418                                 feparm->setFlags(flags);
419                         }
420                 }
421                 addChannelToList(channelid, feparm);
422         }
423
424         if ((!fgets(line, 256, f)) || strcmp(line, "services\n"))
425         {
426                 eDebug("services invalid, no services");
427                 return;
428         }
429
430         // clear all services
431
432         int count=0;
433
434         while (!feof(f))
435         {
436                 if (!fgets(line, 256, f))
437                         break;
438                 if (!strcmp(line, "end\n"))
439                         break;
440
441                 int service_id=-1, dvb_namespace, transport_stream_id=-1, original_network_id=-1, service_type=-1, service_number=-1;
442                 sscanf(line, "%x:%x:%x:%x:%d:%d", &service_id, &dvb_namespace, &transport_stream_id, &original_network_id, &service_type, &service_number);
443                 if (service_number == -1)
444                         continue;
445                 ePtr<eDVBService> s = new eDVBService;
446                 eServiceReferenceDVB ref =
447                                                 eServiceReferenceDVB(
448                                                 eDVBNamespace(dvb_namespace),
449                                                 eTransportStreamID(transport_stream_id),
450                                                 eOriginalNetworkID(original_network_id),
451                                                 eServiceID(service_id),
452                                                 service_type);
453                 count++;
454                 fgets(line, 256, f);
455                 if (strlen(line))
456                         line[strlen(line)-1]=0;
457
458                 s->m_service_name = line;
459                 s->genSortName();
460
461                 fgets(line, 256, f);
462                 if (strlen(line))
463                         line[strlen(line)-1]=0;
464                 if (line[1]!=':')       // old ... (only service_provider)
465                         s->m_provider_name=line;
466                 else
467                         parseServiceData(s, line);
468                 addService(ref, s);
469         }
470
471         eDebug("loaded %d services", count);
472
473         fclose(f);
474 }
475
476 void eDVBDB::saveServicelist(const char *file)
477 {
478         eDebug("---- saving lame channel db");
479         FILE *f=fopen(file, "w");
480         int channels=0, services=0;
481         if (!f)
482                 eFatal("couldn't save lame channel db!");
483         fprintf(f, "eDVB services /4/\n");
484         fprintf(f, "transponders\n");
485         for (std::map<eDVBChannelID, channel>::const_iterator i(m_channels.begin());
486                         i != m_channels.end(); ++i)
487         {
488                 const eDVBChannelID &chid = i->first;
489                 const channel &ch = i->second;
490
491                 fprintf(f, "%08x:%04x:%04x\n", chid.dvbnamespace.get(),
492                                 chid.transport_stream_id.get(), chid.original_network_id.get());
493                 eDVBFrontendParametersSatellite sat;
494                 eDVBFrontendParametersTerrestrial ter;
495                 eDVBFrontendParametersCable cab;
496                 unsigned int flags;  // flagOnlyFree yet..
497                 ch.m_frontendParameters->getFlags(flags);
498                 if (!ch.m_frontendParameters->getDVBS(sat))
499                 {
500                         if (sat.system == eDVBFrontendParametersSatellite::System_DVB_S2)
501                         {
502                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d:%d:%d:%d:%d:%d\n",
503                                         sat.frequency, sat.symbol_rate,
504                                         sat.polarisation, sat.fec,
505                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
506                                         sat.inversion,
507                                         flags,
508                                         sat.system,
509                                         sat.modulation,
510                                         sat.rolloff,
511                                         sat.pilot);
512                         }
513                         else
514                         {
515                                 fprintf(f, "\ts %d:%d:%d:%d:%d:%d:%d\n",
516                                         sat.frequency, sat.symbol_rate,
517                                         sat.polarisation, sat.fec,
518                                         sat.orbital_position > 1800 ? sat.orbital_position - 3600 : sat.orbital_position,
519                                         sat.inversion, flags);
520                         }
521                 }
522                 else if (!ch.m_frontendParameters->getDVBT(ter))
523                 {
524                         fprintf(f, "\tt %d:%d:%d:%d:%d:%d:%d:%d:%d:%d\n",
525                                 ter.frequency, ter.bandwidth, ter.code_rate_HP,
526                                 ter.code_rate_LP, ter.modulation, ter.transmission_mode,
527                                 ter.guard_interval, ter.hierarchy, ter.inversion, flags);
528                 }
529                 else if (!ch.m_frontendParameters->getDVBC(cab))
530                 {
531                         fprintf(f, "\tc %d:%d:%d:%d:%d:%d\n",
532                                 cab.frequency, cab.symbol_rate, cab.inversion, cab.modulation, cab.fec_inner, flags);
533                 }
534                 fprintf(f, "/\n");
535                 channels++;
536         }
537         fprintf(f, "end\nservices\n");
538
539         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i(m_services.begin());
540                 i != m_services.end(); ++i)
541         {
542                 const eServiceReferenceDVB &s = i->first;
543                 fprintf(f, "%04x:%08x:%04x:%04x:%d:%d\n",
544                                 s.getServiceID().get(), s.getDVBNamespace().get(),
545                                 s.getTransportStreamID().get(),s.getOriginalNetworkID().get(),
546                                 s.getServiceType(),
547                                 0);
548
549                 fprintf(f, "%s\n", i->second->m_service_name.c_str());
550
551                 fprintf(f, "p:%s", i->second->m_provider_name.c_str());
552
553                 // write cached pids
554                 for (int x=0; x < eDVBService::cacheMax; ++x)
555                 {
556                         int entry = i->second->getCacheEntry((eDVBService::cacheID)x);
557                         if (entry != -1)
558                                 fprintf(f, ",c:%02d%04x", x, entry);
559                 }
560
561                 // write cached ca pids
562                 for (CAID_LIST::const_iterator ca(i->second->m_ca.begin());
563                         ca != i->second->m_ca.end(); ++ca)
564                         fprintf(f, ",C:%04x", *ca);
565
566                 if (i->second->m_flags)
567                         fprintf(f, ",f:%x", i->second->m_flags);
568
569                 fprintf(f, "\n");
570                 services++;
571         }
572         fprintf(f, "end\nHave a lot of bugs!\n");
573         eDebug("saved %d channels and %d services!", channels, services);
574         fclose(f);
575 }
576
577 void eDVBDB::saveServicelist()
578 {
579         saveServicelist(CONFIGDIR"/enigma2/lamedb");
580 }
581
582 void eDVBDB::loadBouquet(const char *path)
583 {
584         std::string bouquet_name = path;
585         if (!bouquet_name.length())
586         {
587                 eDebug("Bouquet load failed.. no path given..");
588                 return;
589         }
590         size_t pos = bouquet_name.rfind('/');
591         if ( pos != std::string::npos )
592                 bouquet_name.erase(0, pos+1);
593         if (bouquet_name.empty())
594         {
595                 eDebug("Bouquet load failed.. no filename given..");
596                 return;
597         }
598         eBouquet &bouquet = m_bouquets[bouquet_name];
599         bouquet.m_filename = bouquet_name;
600         std::list<eServiceReference> &list = bouquet.m_services;
601         list.clear();
602
603         std::string p = CONFIGDIR"/enigma2/";
604         p+=path;
605         eDebug("loading bouquet... %s", p.c_str());
606         FILE *fp=fopen(p.c_str(), "rt");
607         int entries=0;
608         if (!fp)
609         {
610                 struct stat s;
611                 if ( !stat(path, &s) )
612                 {
613                         rename(path, p.c_str() );
614                         loadBouquet(path);
615                         return;
616                 }
617                 eDebug("failed to open.");
618                 if ( strstr(path, "bouquets.tv") )
619                 {
620                         eDebug("recreate bouquets.tv");
621                         bouquet.m_bouquet_name="Bouquets (TV)";
622                         bouquet.flushChanges();
623                 }
624                 else if ( strstr(path, "bouquets.radio") )
625                 {
626                         eDebug("recreate bouquets.radio");
627                         bouquet.m_bouquet_name="Bouquets (Radio)";
628                         bouquet.flushChanges();
629                 }
630                 return;
631         }
632         char line[256];
633         bool read_descr=false;
634         eServiceReference *e = NULL;
635         while (1)
636         {
637                 if (!fgets(line, 256, fp))
638                         break;
639                 line[strlen(line)-1]=0;
640                 if (strlen(line) && line[strlen(line)-1]=='\r')
641                         line[strlen(line)-1]=0;
642                 if (!line[0])
643                         break;
644                 if (line[0]=='#')
645                 {
646                         if (!strncmp(line, "#SERVICE", 8))
647                         {
648                                 int offs = line[8] == ':' ? 10 : 9;
649                                 eServiceReference tmp(line+offs);
650                                 if (tmp.type != eServiceReference::idDVB)
651                                 {
652                                         eDebug("only DVB Bouquets supported");
653                                         continue;
654                                 }
655                                 if ( tmp.flags&eServiceReference::canDescent )
656                                 {
657                                         size_t pos = tmp.path.rfind('/');
658                                         char buf[256];
659                                         std::string path = tmp.path;
660                                         if ( pos != std::string::npos )
661                                                 path.erase(0, pos+1);
662                                         if (path.empty())
663                                         {
664                                                 eDebug("Bouquet load failed.. no filename given..");
665                                                 continue;
666                                         }
667                                         pos = path.find("FROM BOUQUET ");
668                                         if (pos != std::string::npos)
669                                         {
670                                                 char endchr = path[pos+13];
671                                                 if (endchr != '"')
672                                                 {
673                                                         eDebug("ignore invalid bouquet '%s' (only \" are allowed)",
674                                                                 tmp.toString().c_str());
675                                                         continue;
676                                                 }
677                                                 char *beg = &path[pos+14];
678                                                 char *end = strchr(beg, endchr);
679                                                 path.assign(beg, end - beg);
680                                         }
681                                         else
682                                         {
683                                                 snprintf(buf, 256, "FROM BOUQUET \"%s\" ORDER BY bouquet", path.c_str());
684                                                 tmp.path = buf;
685                                         }
686                                         loadBouquet(path.c_str());
687                                 }
688                                 list.push_back(tmp);
689                                 e = &list.back();
690                                 read_descr=true;
691                                 ++entries;
692                         }
693                         else if (read_descr && !strncmp(line, "#DESCRIPTION", 12))
694                         {
695                                 int offs = line[12] == ':' ? 14 : 13;
696                                 e->name = line+offs;
697                                 read_descr=false;
698                         }
699                         else if (!strncmp(line, "#NAME ", 6))
700                                 bouquet.m_bouquet_name=line+6;
701                         continue;
702                 }
703         }
704         fclose(fp);
705         eDebug("%d entries in Bouquet %s", entries, bouquet_name.c_str());
706 }
707
708 void eDVBDB::reloadBouquets()
709 {
710         m_bouquets.clear();
711         loadBouquet("bouquets.tv");
712         loadBouquet("bouquets.radio");
713 // create default bouquets when missing
714         if ( m_bouquets.find("userbouquet.favourites.tv") == m_bouquets.end() )
715         {
716                 eBouquet &b = m_bouquets["userbouquet.favourites.tv"];
717                 b.m_filename = "userbouquet.favourites.tv";
718                 b.m_bouquet_name = "Favourites (TV)";
719                 b.flushChanges();
720                 eServiceReference ref;
721                 memset(ref.data, 0, sizeof(ref.data));
722                 ref.type=1;
723                 ref.flags=7;
724                 ref.data[0]=1;
725                 ref.path="FROM BOUQUET \"userbouquet.favourites.tv\" ORDER BY bouquet";
726                 eBouquet &parent = m_bouquets["bouquets.tv"];
727                 parent.m_services.push_back(ref);
728                 parent.flushChanges();
729         }
730         if ( m_bouquets.find("userbouquet.favourites.radio") == m_bouquets.end() )
731         {
732                 eBouquet &b = m_bouquets["userbouquet.favourites.radio"];
733                 b.m_filename = "userbouquet.favourites.radio";
734                 b.m_bouquet_name = "Favourites (Radio)";
735                 b.flushChanges();
736                 eServiceReference ref;
737                 memset(ref.data, 0, sizeof(ref.data));
738                 ref.type=1;
739                 ref.flags=7;
740                 ref.data[0]=2;
741                 ref.path="FROM BOUQUET \"userbouquet.favourites.radio\" ORDER BY bouquet";
742                 eBouquet &parent = m_bouquets["bouquets.radio"];
743                 parent.m_services.push_back(ref);
744                 parent.flushChanges();
745         }
746 }
747
748 eDVBDB *eDVBDB::instance;
749
750 using namespace xmlcc;
751
752 eDVBDB::eDVBDB()
753 {
754         instance = this;
755         reloadServicelist();
756 }
757
758 PyObject *eDVBDB::readSatellites(ePyObject sat_list, ePyObject sat_dict, ePyObject tp_dict)
759 {
760         if (!PyDict_Check(tp_dict)) {
761                 PyErr_SetString(PyExc_StandardError,
762                         "type error");
763                         eDebug("arg 2 is not a python dict");
764                 return NULL;
765         }
766         else if (!PyDict_Check(sat_dict))
767         {
768                 PyErr_SetString(PyExc_StandardError,
769                         "type error");
770                         eDebug("arg 1 is not a python dict");
771                 return NULL;
772         }
773         else if (!PyList_Check(sat_list))
774         {
775                 PyErr_SetString(PyExc_StandardError,
776                         "type error");
777                         eDebug("arg 0 is not a python list");
778                 return NULL;
779         }
780         XMLTree tree;
781         tree.setFilename("/etc/tuxbox/satellites.xml");
782         tree.read();
783         Element *root = tree.getRoot();
784         if (!root)
785         {
786                 eDebug("couldn't open /etc/tuxbox/satellites.xml!!");
787                 Py_INCREF(Py_False);
788                 return Py_False;
789         }
790         int tmp, *dest = NULL,
791                 modulation, system, freq, sr, pol, fec, inv, pilot, rolloff, tsid, onid;
792         char *end_ptr;
793         const Attribute *at;
794         std::string name;
795         const ElementList &root_elements = root->getElementList();
796         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
797         {
798 //              eDebug("element: %s", (*it)->name().c_str());
799                 const Element *el = *it;
800                 const ElementList &sat_elements = el->getElementList();
801                 const AttributeList &sat_attributes = el->getAttributeList();
802                 ePyObject sat_name;
803                 ePyObject sat_pos;
804                 ePyObject sat_flags;
805                 for (AttributeConstIterator it(sat_attributes.begin()); it != sat_attributes.end(); ++it)
806                 {
807 //                      eDebug("\tattr: %s", at->name().c_str());
808                         at = *it;
809                         name = at->name();
810                         if (name == "name")
811                                 sat_name = PyString_FromString(at->value().c_str());
812                         else if (name == "flags")
813                         {
814                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
815                                 if (!*end_ptr)
816                                         sat_flags = PyInt_FromLong(tmp);
817                         }
818                         else if (name == "position")
819                         {
820                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
821                                 if (!*end_ptr)
822                                 {
823                                         if (tmp < 0)
824                                                 tmp = 3600 + tmp;
825                                         sat_pos = PyInt_FromLong(tmp);
826                                 }
827                         }
828                 }
829                 if (sat_pos && sat_name)
830                 {
831                         ePyObject tplist = PyList_New(0);
832                         ePyObject tuple = PyTuple_New(3);
833                         if (!sat_flags)
834                                 sat_flags = PyInt_FromLong(0);
835                         PyTuple_SET_ITEM(tuple, 0, sat_pos);
836                         PyTuple_SET_ITEM(tuple, 1, sat_name);
837                         PyTuple_SET_ITEM(tuple, 2, sat_flags);
838                         PyList_Append(sat_list, tuple);
839                         Py_DECREF(tuple);
840                         PyDict_SetItem(sat_dict, sat_pos, sat_name);
841                         PyDict_SetItem(tp_dict, sat_pos, tplist);
842                         for (ElementConstIterator it(sat_elements.begin()); it != sat_elements.end(); ++it)
843                         {
844                                 //eDebug("\telement: %s", (*it)->name().c_str());
845                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
846                                 AttributeConstIterator end = tp_attributes.end();
847                                 modulation = eDVBFrontendParametersSatellite::Modulation_QPSK;
848                                 system = eDVBFrontendParametersSatellite::System_DVB_S;
849                                 freq = 0;
850                                 sr = 0;
851                                 pol = -1;
852                                 fec = eDVBFrontendParametersSatellite::FEC_Auto;
853                                 inv = eDVBFrontendParametersSatellite::Inversion_Unknown;
854                                 pilot = eDVBFrontendParametersSatellite::Pilot_Unknown;
855                                 rolloff = eDVBFrontendParametersSatellite::RollOff_alpha_0_35;
856                                 tsid = -1;
857                                 onid = -1;
858
859                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
860                                 {
861                                         at = *it;
862                                         //eDebug("\t\tattr: %s", at->name().c_str());
863                                         name = at->name();
864                                         if (name == "modulation") dest = &modulation;
865                                         else if (name == "system") dest = &system;
866                                         else if (name == "frequency") dest = &freq;
867                                         else if (name == "symbol_rate") dest = &sr;
868                                         else if (name == "polarization") dest = &pol;
869                                         else if (name == "fec_inner") dest = &fec;
870                                         else if (name == "inversion") dest = &inv;
871                                         else if (name == "rolloff") dest = &rolloff;
872                                         else if (name == "pilot") dest = &pilot;
873                                         else if (name == "tsid") dest = &tsid;
874                                         else if (name == "onid") dest = &onid;
875                                         else continue;
876                                         if (dest)
877                                         {
878                                                 //eDebug("\t\t\tvalue: %s", at->value().c_str());
879                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
880                                                 if (!*end_ptr)
881                                                         *dest = tmp;
882                                         }
883                                 }
884                                 if (freq && sr && pol != -1)
885                                 {
886                                         tuple = PyTuple_New(12);
887                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(0));
888                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
889                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(sr));
890                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(pol));
891                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(fec));
892                                         PyTuple_SET_ITEM(tuple, 5, PyInt_FromLong(system));
893                                         PyTuple_SET_ITEM(tuple, 6, PyInt_FromLong(modulation));
894                                         PyTuple_SET_ITEM(tuple, 7, PyInt_FromLong(inv));
895                                         PyTuple_SET_ITEM(tuple, 8, PyInt_FromLong(rolloff));
896                                         PyTuple_SET_ITEM(tuple, 9, PyInt_FromLong(pilot));
897                                         PyTuple_SET_ITEM(tuple, 10, PyInt_FromLong(tsid));
898                                         PyTuple_SET_ITEM(tuple, 11, PyInt_FromLong(onid));
899                                         PyList_Append(tplist, tuple);
900                                         Py_DECREF(tuple);
901                                 }
902                         }
903                         Py_DECREF(tplist);
904                 }
905                 else
906                 {
907                         if (sat_pos)
908                                 Py_DECREF(sat_pos);
909                         if (sat_name)
910                                 Py_DECREF(sat_name);
911                         if (sat_flags)
912                                 Py_DECREF(sat_flags);
913                 }
914         }
915         Py_INCREF(Py_True);
916         return Py_True;
917 }
918
919 PyObject *eDVBDB::readCables(ePyObject cab_list, ePyObject tp_dict)
920 {
921         if (!PyDict_Check(tp_dict)) {
922                 PyErr_SetString(PyExc_StandardError,
923                         "type error");
924                         eDebug("arg 1 is not a python dict");
925                 return NULL;
926         }
927         else if (!PyList_Check(cab_list))
928         {
929                 PyErr_SetString(PyExc_StandardError,
930                         "type error");
931                         eDebug("arg 0 is not a python list");
932                 return NULL;
933         }
934         XMLTree tree;
935         tree.setFilename("/etc/tuxbox/cables.xml");
936         tree.read();
937         Element *root = tree.getRoot();
938         if (!root)
939         {
940                 eDebug("couldn't open /etc/tuxbox/cables.xml!!");
941                 Py_INCREF(Py_False);
942                 return Py_False;
943         }
944         const Attribute *at;
945         int tmp, *dest,
946                 modulation, fec, freq, sr;
947         std::string name;
948         char *end_ptr;
949         const ElementList &root_elements = root->getElementList();
950         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
951         {
952 //              eDebug("element: %s", el->name().c_str());
953                 const Element *el = *it;
954                 const ElementList &cab_elements = el->getElementList();
955                 const AttributeList &cab_attributes = el->getAttributeList();
956                 ePyObject cab_name;
957                 ePyObject cab_flags;
958                 for (AttributeConstIterator it(cab_attributes.begin()); it != cab_attributes.end(); ++it)
959                 {
960 //                      eDebug("\tattr: %s", at->name().c_str());
961                         at = *it;
962                         name = at->name();
963                         if (name == "name")
964                                 cab_name = PyString_FromString(at->value().c_str());
965                         else if (name == "flags")
966                         {
967                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
968                                 if (!*end_ptr)
969                                         cab_flags = PyInt_FromLong(tmp);
970                         }
971                 }
972                 if (cab_name)
973                 {
974                         ePyObject tplist = PyList_New(0);
975                         ePyObject tuple = PyTuple_New(2);
976                         if (!cab_flags)
977                                 cab_flags = PyInt_FromLong(0);
978                         PyTuple_SET_ITEM(tuple, 0, cab_name);
979                         PyTuple_SET_ITEM(tuple, 1, cab_flags);
980                         PyList_Append(cab_list, tuple);
981                         Py_DECREF(tuple);
982                         PyDict_SetItem(tp_dict, cab_name, tplist);
983                         for (ElementConstIterator it(cab_elements.begin()); it != cab_elements.end(); ++it)
984                         {
985 //                              eDebug("\telement: %s", (*it)->name().c_str());
986                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
987                                 AttributeConstIterator end = tp_attributes.end();
988                                 modulation = eDVBFrontendParametersCable::Modulation_QAM64;
989                                 fec = eDVBFrontendParametersCable::FEC_Auto;
990                                 freq = 0;
991                                 sr = 0;
992                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
993                                 {
994 //                                      eDebug("\t\tattr: %s", at->name().c_str());
995                                         at = *it;
996                                         dest = 0;
997                                         name = at->name();
998                                         if (name == "modulation") dest = &modulation;
999                                         else if (name == "frequency") dest = &freq;
1000                                         else if (name == "symbol_rate") dest = &sr;
1001                                         else if (name == "fec_inner") dest = &fec;
1002                                         else continue;
1003                                         if (dest)
1004                                         {
1005                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1006                                                 if (!*end_ptr)
1007                                                         *dest = tmp;
1008                                         }
1009                                 }
1010                                 if (freq && sr)
1011                                 {
1012                                         while (freq > 999999)
1013                                                 freq /= 10;
1014                                         tuple = PyTuple_New(5);
1015                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(1));
1016                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
1017                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(sr));
1018                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(modulation));
1019                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(fec));
1020                                         PyList_Append(tplist, tuple);
1021                                         Py_DECREF(tuple);
1022                                 }
1023                         }
1024                         Py_DECREF(tplist);
1025                 }
1026                 else if (cab_flags)
1027                         Py_DECREF(cab_flags);
1028         }
1029         Py_INCREF(Py_True);
1030         return Py_True;
1031 }
1032
1033 PyObject *eDVBDB::readTerrestrials(ePyObject ter_list, ePyObject tp_dict)
1034 {
1035         if (!PyDict_Check(tp_dict)) {
1036                 PyErr_SetString(PyExc_StandardError,
1037                         "type error");
1038                         eDebug("arg 1 is not a python dict");
1039                 return NULL;
1040         }
1041         else if (!PyList_Check(ter_list))
1042         {
1043                 PyErr_SetString(PyExc_StandardError,
1044                         "type error");
1045                         eDebug("arg 0 is not a python list");
1046                 return NULL;
1047         }
1048         XMLTree tree;
1049         tree.setFilename("/etc/tuxbox/terrestrial.xml");
1050         tree.read();
1051         Element *root = tree.getRoot();
1052         if (!root)
1053         {
1054                 eDebug("couldn't open /etc/tuxbox/terrestrial.xml!!");
1055                 Py_INCREF(Py_False);
1056                 return Py_False;
1057         }
1058         const Attribute *at;
1059         std::string name;
1060         int tmp, *dest,
1061                 freq, bw, constellation, crh = 5, crl = 5, guard = 4, transm, hierarchy, inv = 2;
1062         char *end_ptr;
1063         const ElementList &root_elements = root->getElementList();
1064         for (ElementConstIterator it(root_elements.begin()); it != root_elements.end(); ++it)
1065         {
1066 //              eDebug("element: %s", el->name().c_str());
1067                 const Element *el = *it;
1068                 const ElementList &ter_elements = el->getElementList();
1069                 const AttributeList &ter_attributes = el->getAttributeList();
1070                 ePyObject ter_name;
1071                 ePyObject ter_flags;
1072                 for (AttributeConstIterator it(ter_attributes.begin()); it != ter_attributes.end(); ++it)
1073                 {
1074 //                      eDebug("\tattr: %s", at->name().c_str());
1075                         at = *it;
1076                         name = at->name();
1077                         if (name == "name")
1078                                 ter_name = PyString_FromString(at->value().c_str());
1079                         else if (name == "flags")
1080                         {
1081                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1082                                 if (!*end_ptr)
1083                                         ter_flags = PyInt_FromLong(tmp);
1084                         }
1085                 }
1086                 if (ter_name)
1087                 {
1088                         ePyObject tplist = PyList_New(0);
1089                         ePyObject tuple = PyTuple_New(2);
1090                         if (!ter_flags)
1091                                 ter_flags = PyInt_FromLong(0);
1092                         PyTuple_SET_ITEM(tuple, 0, ter_name);
1093                         PyTuple_SET_ITEM(tuple, 1, ter_flags);
1094                         PyList_Append(ter_list, tuple);
1095                         Py_DECREF(tuple);
1096                         PyDict_SetItem(tp_dict, ter_name, tplist);
1097                         for (ElementConstIterator it(ter_elements.begin()); it != ter_elements.end(); ++it)
1098                         {
1099 //                              eDebug("\telement: %s", (*it)->name().c_str());
1100                                 const AttributeList &tp_attributes = (*it)->getAttributeList();
1101                                 AttributeConstIterator end = tp_attributes.end();
1102                                 freq = 0;
1103                                 bw = eDVBFrontendParametersTerrestrial::Bandwidth_Auto;
1104                                 constellation = eDVBFrontendParametersTerrestrial::Modulation_Auto;
1105                                 crh = eDVBFrontendParametersTerrestrial::FEC_Auto;
1106                                 crl = eDVBFrontendParametersTerrestrial::FEC_Auto;
1107                                 guard = eDVBFrontendParametersTerrestrial::GuardInterval_Auto;
1108                                 transm = eDVBFrontendParametersTerrestrial::TransmissionMode_Auto;
1109                                 hierarchy = eDVBFrontendParametersTerrestrial::Hierarchy_Auto;
1110                                 inv = eDVBFrontendParametersTerrestrial::Inversion_Unknown;
1111                                 for (AttributeConstIterator it(tp_attributes.begin()); it != end; ++it)
1112                                 {
1113 //                                      eDebug("\t\tattr: %s", at->name().c_str());
1114                                         at = *it;
1115                                         dest = 0;
1116                                         name = at->name();
1117                                         if (name == "centre_frequency") dest = &freq;
1118                                         else if (name == "bandwidth") dest = &bw;
1119                                         else if (name == "constellation") dest = &constellation;
1120                                         else if (name == "code_rate_hp") dest = &crh;
1121                                         else if (name == "code_rate_lp") dest = &crl;
1122                                         else if (name == "guard_interval") dest = &guard;
1123                                         else if (name == "transmission_mode") dest = &transm;
1124                                         else if (name == "hierarchy_information") dest = &hierarchy;
1125                                         else if (name == "inversion") dest = &inv;
1126                                         else continue;
1127                                         if (dest)
1128                                         {
1129                                                 tmp = strtol(at->value().c_str(), &end_ptr, 10);
1130                                                 if (!*end_ptr)
1131                                                         *dest = tmp;
1132                                         }
1133                                 }
1134                                 if (freq)
1135                                 {
1136                                         if (crh > 5) // our terrestrial.xml is buggy... 6 for AUTO
1137                                                 crh = 5;
1138                                         if (crl > 5) // our terrestrial.xml is buggy... 6 for AUTO
1139                                                 crl = 5;
1140                                         tuple = PyTuple_New(10);
1141                                         PyTuple_SET_ITEM(tuple, 0, PyInt_FromLong(2));
1142                                         PyTuple_SET_ITEM(tuple, 1, PyInt_FromLong(freq));
1143                                         PyTuple_SET_ITEM(tuple, 2, PyInt_FromLong(bw));
1144                                         PyTuple_SET_ITEM(tuple, 3, PyInt_FromLong(constellation));
1145                                         PyTuple_SET_ITEM(tuple, 4, PyInt_FromLong(crh));
1146                                         PyTuple_SET_ITEM(tuple, 5, PyInt_FromLong(crl));
1147                                         PyTuple_SET_ITEM(tuple, 6, PyInt_FromLong(guard));
1148                                         PyTuple_SET_ITEM(tuple, 7, PyInt_FromLong(transm));
1149                                         PyTuple_SET_ITEM(tuple, 8, PyInt_FromLong(hierarchy));
1150                                         PyTuple_SET_ITEM(tuple, 9, PyInt_FromLong(inv));
1151                                         PyList_Append(tplist, tuple);
1152                                         Py_DECREF(tuple);
1153                                 }
1154                         }
1155                         Py_DECREF(tplist);
1156                 }
1157                 else if (ter_flags)
1158                         Py_DECREF(ter_flags);
1159         }
1160         Py_INCREF(Py_True);
1161         return Py_True;
1162 }
1163
1164 eDVBDB::~eDVBDB()
1165 {
1166         instance=NULL;
1167 }
1168
1169 RESULT eDVBDB::removeService(const eServiceReference &ref)
1170 {
1171         if (ref.type == eServiceReference::idDVB)
1172         {
1173                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1174                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1175                 if (it != m_services.end())
1176                 {
1177                         m_services.erase(it);
1178                         return 0;
1179                 }
1180         }
1181         return -1;
1182 }
1183
1184 RESULT eDVBDB::removeServices(int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
1185 {
1186         return removeServices(eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
1187 }
1188
1189 RESULT eDVBDB::removeServices(eDVBChannelID chid, unsigned int orbpos)
1190 {
1191         RESULT ret=-1;
1192         eDVBNamespace eNs;
1193         eTransportStreamID eTsid;
1194         eOriginalNetworkID eOnid;
1195         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1196         std::set<eDVBChannelID> removed_chids;
1197         while (it != m_channels.end())
1198         {
1199                 const eDVBChannelID &ch = it->first;
1200                 bool remove=true;
1201                 int system;
1202                 it->second.m_frontendParameters->getSystem(system);
1203                 if ( system == iDVBFrontend::feSatellite )
1204                 {
1205                         eDVBFrontendParametersSatellite sat;
1206                         it->second.m_frontendParameters->getDVBS(sat);
1207                         if ((unsigned int)sat.orbital_position != orbpos)
1208                                 remove=false;
1209                 }
1210                 if ( remove && chid.dvbnamespace != eNs ) // namespace given?
1211                 {
1212                         if ( system == iDVBFrontend::feCable && chid.dvbnamespace.get() == (int)0xFFFF0000 )
1213                                 ;
1214                         else if ( system == iDVBFrontend::feTerrestrial && chid.dvbnamespace.get() == (int)0xEEEE0000 )
1215                                 ;
1216                         else if ( chid.dvbnamespace != ch.dvbnamespace )
1217                                 remove=false;
1218                 }
1219                 else if ( system == iDVBFrontend::feCable || system == iDVBFrontend::feTerrestrial )
1220                         remove=false;
1221                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
1222                         remove=false;
1223                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
1224                         remove=false;
1225                 if ( remove )
1226                 {
1227                         eDebug("remove %08x %04x %04x",
1228                                 ch.dvbnamespace.get(),
1229                                 ch.original_network_id.get(),
1230                                 ch.transport_stream_id.get());
1231                         removed_chids.insert(it->first);
1232                         m_channels.erase(it++);
1233                 }
1234                 else
1235                         ++it;
1236         }
1237         if (!removed_chids.empty())
1238         {
1239                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1240                 while(service != m_services.end())
1241                 {
1242                         eDVBChannelID chid;
1243                         service->first.getChannelID(chid);
1244                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1245                         if (it != removed_chids.end())
1246                                 m_services.erase(service++);
1247                         else
1248                                 ++service;
1249                         ret=0;
1250                 }
1251         }
1252         return ret;
1253 }
1254
1255 RESULT eDVBDB::removeServices(iDVBFrontendParameters *feparm)
1256 {
1257         int ret = -1;
1258         std::set<eDVBChannelID> removed_chids;
1259         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1260         while (it != m_channels.end())
1261         {
1262                 int diff;
1263                 if (!feparm->calculateDifference(&(*it->second.m_frontendParameters), diff, false))
1264                 {
1265                         if (diff < 4000)
1266                         {
1267                                 removed_chids.insert(it->first);
1268                                 m_channels.erase(it++);
1269                         }
1270                         else
1271                                 ++it;
1272                 }
1273                 else
1274                         ++it;
1275         }
1276         if (!removed_chids.empty())
1277         {
1278                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1279                 while(service != m_services.end())
1280                 {
1281                         eDVBChannelID chid;
1282                         service->first.getChannelID(chid);
1283                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1284                         if (it != removed_chids.end())
1285                                 m_services.erase(service++);
1286                         else
1287                                 ++service;
1288                 }
1289                 ret = 0;
1290         }
1291         return ret;
1292 }
1293
1294 RESULT eDVBDB::addFlag(const eServiceReference &ref, unsigned int flagmask)
1295 {
1296         if (ref.type == eServiceReference::idDVB)
1297         {
1298                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1299                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1300                 if (it != m_services.end())
1301                         it->second->m_flags |= ~flagmask;
1302                 return 0;
1303         }
1304         return -1;
1305 }
1306
1307 RESULT eDVBDB::removeFlag(const eServiceReference &ref, unsigned int flagmask)
1308 {
1309         if (ref.type == eServiceReference::idDVB)
1310         {
1311                 eServiceReferenceDVB &service = (eServiceReferenceDVB&)ref;
1312                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(service));
1313                 if (it != m_services.end())
1314                         it->second->m_flags &= ~flagmask;
1315                 return 0;
1316         }
1317         return -1;
1318 }
1319
1320 RESULT eDVBDB::removeFlags(unsigned int flagmask, int dvb_namespace, int tsid, int onid, unsigned int orb_pos)
1321 {
1322         return removeFlags(flagmask, eDVBChannelID(eDVBNamespace(dvb_namespace), eTransportStreamID(tsid), eOriginalNetworkID(onid)), orb_pos);
1323 }
1324
1325 RESULT eDVBDB::removeFlags(unsigned int flagmask, eDVBChannelID chid, unsigned int orbpos)
1326 {
1327         eDVBNamespace eNs;
1328         eTransportStreamID eTsid;
1329         eOriginalNetworkID eOnid;
1330         std::map<eDVBChannelID, channel>::iterator it(m_channels.begin());
1331         std::set<eDVBChannelID> removed_chids;
1332         while (it != m_channels.end())
1333         {
1334                 const eDVBChannelID &ch = it->first;
1335                 bool remove=true;
1336                 int system;
1337                 it->second.m_frontendParameters->getSystem(system);
1338                 if ( orbpos != 0xFFFFFFFF && system == iDVBFrontend::feSatellite )
1339                 {
1340                         eDVBFrontendParametersSatellite sat;
1341                         it->second.m_frontendParameters->getDVBS(sat);
1342                         if ((unsigned int)sat.orbital_position != orbpos)
1343                                 remove=false;
1344                 }
1345                 if ( remove && chid.dvbnamespace != eNs )
1346                 {
1347                         if (system == iDVBFrontend::feCable && chid.dvbnamespace.get() == (int)0xFFFF0000)
1348                                 ;
1349                         else if (system == iDVBFrontend::feTerrestrial && chid.dvbnamespace.get() == (int)0xEEEE0000)
1350                                 ;
1351                         else if ( chid.dvbnamespace != ch.dvbnamespace )
1352                                 remove=false;
1353                 }
1354                 if ( remove && chid.original_network_id != eOnid && chid.original_network_id != ch.original_network_id )
1355                         remove=false;
1356                 if ( remove && chid.transport_stream_id != eTsid && chid.transport_stream_id != ch.transport_stream_id )
1357                         remove=false;
1358                 if ( remove )
1359                         removed_chids.insert(it->first);
1360                 ++it;
1361         }
1362         if (!removed_chids.empty())
1363         {
1364                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator service(m_services.begin());
1365                 while(service != m_services.end())
1366                 {
1367                         eDVBChannelID chid;
1368                         service->first.getChannelID(chid);
1369                         std::set<eDVBChannelID>::iterator it(removed_chids.find(chid));
1370                         if (it != removed_chids.end())
1371                                 service->second->m_flags &= ~flagmask;
1372                         ++service;
1373                 }
1374         }
1375         return 0;
1376 }
1377
1378 RESULT eDVBDB::addChannelToList(const eDVBChannelID &id, iDVBFrontendParameters *feparm)
1379 {
1380         channel ch;
1381         std::map<eDVBChannelID, channel>::iterator it = m_channels.find(id);
1382         ASSERT(feparm);
1383         ch.m_frontendParameters = feparm;
1384         if (it != m_channels.end())
1385                 it->second = ch;
1386         else
1387                 m_channels.insert(std::pair<eDVBChannelID, channel>(id, ch));
1388         return 0;
1389 }
1390
1391 RESULT eDVBDB::removeChannel(const eDVBChannelID &id)
1392 {
1393         m_channels.erase(id);
1394         return 0;
1395 }
1396
1397 RESULT eDVBDB::getChannelFrontendData(const eDVBChannelID &id, ePtr<iDVBFrontendParameters> &parm)
1398 {
1399         std::map<eDVBChannelID, channel>::iterator i = m_channels.find(id);
1400         if (i == m_channels.end())
1401         {
1402                 parm = 0;
1403                 return -ENOENT;
1404         }
1405         parm = i->second.m_frontendParameters;
1406         return 0;
1407 }
1408
1409 RESULT eDVBDB::addService(const eServiceReferenceDVB &serviceref, eDVBService *service)
1410 {
1411         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_services.find(serviceref));
1412         if (it == m_services.end())
1413                 m_services.insert(std::pair<eServiceReferenceDVB, ePtr<eDVBService> >(serviceref, service));
1414         return 0;
1415 }
1416
1417 RESULT eDVBDB::getService(const eServiceReferenceDVB &reference, ePtr<eDVBService> &service)
1418 {
1419         std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator i;
1420         i = m_services.find(reference);
1421         if (i == m_services.end())
1422         {
1423                 service = 0;
1424                 return -ENOENT;
1425         }
1426         service = i->second;
1427         return 0;
1428 }
1429
1430 RESULT eDVBDB::flush()
1431 {
1432         saveServicelist();
1433         return 0;
1434 }
1435
1436 RESULT eDVBDB::getBouquet(const eServiceReference &ref, eBouquet* &bouquet)
1437 {
1438         std::string str = ref.path;
1439         if (str.empty())
1440         {
1441                 eDebug("getBouquet failed.. no path given!");
1442                 return -1;
1443         }
1444         size_t pos = str.find("FROM BOUQUET \"");
1445         if ( pos != std::string::npos )
1446         {
1447                 str.erase(0, pos+14);
1448                 pos = str.find('"');
1449                 if ( pos != std::string::npos )
1450                         str.erase(pos);
1451                 else
1452                         str.clear();
1453         }
1454         if (str.empty())
1455         {
1456                 eDebug("getBouquet failed.. couldn't parse bouquet name");
1457                 return -1;
1458         }
1459         std::map<std::string, eBouquet>::iterator i =
1460                 m_bouquets.find(str);
1461         if (i == m_bouquets.end())
1462         {
1463                 bouquet = 0;
1464                 return -ENOENT;
1465         }
1466         bouquet = &i->second;
1467         return 0;
1468 }
1469
1470 RESULT eDVBDB::startQuery(ePtr<iDVBChannelListQuery> &query, eDVBChannelQuery *q, const eServiceReference &source)
1471 {
1472         if ( source.path.find("FROM") != std::string::npos )
1473         {
1474                 if ( source.path.find("BOUQUET") != std::string::npos )
1475                         query = new eDVBDBBouquetQuery(this, source, q);
1476                 else if ( source.path.find("SATELLITES") != std::string::npos )
1477                         query = new eDVBDBSatellitesQuery(this, source, q);
1478                 else if ( source.path.find("PROVIDERS") != std::string::npos )
1479                         query = new eDVBDBProvidersQuery(this, source, q);
1480                 else
1481                         eFatal("invalid query %s", source.toString().c_str());
1482         }
1483         else
1484                 query = new eDVBDBQuery(this, source, q);
1485         return 0;
1486 }
1487
1488 eServiceReference eDVBDB::searchReference(int tsid, int onid, int sid)
1489 {
1490         eServiceID Sid(sid);
1491         eTransportStreamID Tsid(tsid);
1492         eOriginalNetworkID Onid(onid);
1493         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator sit(m_services.begin());
1494                 sit != m_services.end(); ++sit)
1495         {
1496                 if (sit->first.getTransportStreamID() == Tsid &&
1497                         sit->first.getOriginalNetworkID() == Onid &&
1498                         sit->first.getServiceID() == Sid)
1499                         return sit->first;
1500         }
1501         return eServiceReference();
1502 }
1503
1504 DEFINE_REF(eDVBDBQueryBase);
1505
1506 eDVBDBQueryBase::eDVBDBQueryBase(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1507         :m_db(db), m_query(query), m_source(source)
1508 {
1509 }
1510
1511 int eDVBDBQueryBase::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1512 {
1513         ePtr<eDVBService> a_service, b_service;
1514         int sortmode = m_query ? m_query->m_sort : eDVBChannelQuery::tName;
1515
1516         if ((sortmode == eDVBChannelQuery::tName) || (sortmode == eDVBChannelQuery::tProvider))
1517         {
1518                 if (a.name.empty() && m_db->getService(a, a_service))
1519                         return 1;
1520                 if (b.name.empty() && m_db->getService(b, b_service))
1521                         return 1;
1522         }
1523
1524         switch (sortmode)
1525         {
1526         case eDVBChannelQuery::tName:
1527                 if (a_service)
1528                 {
1529                         if (b_service)
1530                                 return a_service->m_service_name_sort < b_service->m_service_name_sort;
1531                         else
1532                         {
1533                                 std::string str = b.name;
1534                                 makeUpper(str);
1535                                 return a_service->m_service_name_sort < str;
1536                         }
1537                 }
1538                 else if (b_service)
1539                 {
1540                         std::string str = a.name;
1541                         makeUpper(str);
1542                         return str < b_service->m_service_name_sort;
1543                 }
1544                 else
1545                 {
1546                         std::string aa = a.name, bb = b.name;
1547                         makeUpper(aa);
1548                         makeUpper(bb);
1549                         return aa < bb;
1550                 }
1551         case eDVBChannelQuery::tProvider:
1552                 return a_service->m_provider_name < b_service->m_provider_name;
1553         case eDVBChannelQuery::tType:
1554                 return a.getServiceType() < b.getServiceType();
1555         case eDVBChannelQuery::tBouquet:
1556                 return 0;
1557         case eDVBChannelQuery::tSatellitePosition:
1558                 return (a.getDVBNamespace().get() >> 16) < (b.getDVBNamespace().get() >> 16);
1559         default:
1560                 return 1;
1561         }
1562         return 0;
1563 }
1564
1565 eDVBDBQuery::eDVBDBQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1566         :eDVBDBQueryBase(db, source, query)
1567 {
1568         m_cursor = m_db->m_services.begin();
1569 }
1570
1571 RESULT eDVBDBQuery::getNextResult(eServiceReferenceDVB &ref)
1572 {
1573         while (m_cursor != m_db->m_services.end())
1574         {
1575                 ePtr<eDVBService> service = m_cursor->second;
1576                 if (service->isHidden())
1577                         ++m_cursor;
1578                 else
1579                 {
1580                         ref = m_cursor->first;
1581
1582                         int res = (!m_query) || service->checkFilter(ref, *m_query);
1583
1584                         ++m_cursor;
1585
1586                         if (res)
1587                                 return 0;
1588                 }
1589         }
1590
1591         ref.type = eServiceReference::idInvalid;
1592
1593         return 1;
1594 }
1595
1596 eDVBDBBouquetQuery::eDVBDBBouquetQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1597         :eDVBDBQueryBase(db, source, query), m_cursor(db->m_bouquets[query->m_bouquet_name].m_services.begin())
1598 {
1599 }
1600
1601 RESULT eDVBDBBouquetQuery::getNextResult(eServiceReferenceDVB &ref)
1602 {
1603         eBouquet &bouquet = m_db->m_bouquets[m_query->m_bouquet_name];
1604         std::list<eServiceReference> &list = bouquet.m_services;
1605         while (m_cursor != list.end())
1606         {
1607                 ref = *((eServiceReferenceDVB*)&(*m_cursor));
1608
1609                 std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it =
1610                         m_db->m_services.find(ref);
1611
1612                 int res = (!m_query) || it == m_db->m_services.end() || !(it->second->isHidden() && it->second->checkFilter(ref, *m_query));
1613
1614                 ++m_cursor;
1615
1616                 if (res)
1617                         return 0;
1618         }
1619
1620         ref.type = eServiceReference::idInvalid;
1621
1622         return 1;
1623 }
1624
1625 eDVBDBListQuery::eDVBDBListQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1626         :eDVBDBQueryBase(db, source, query), m_cursor(m_list.end())
1627 {
1628 }
1629
1630 RESULT eDVBDBListQuery::getNextResult(eServiceReferenceDVB &ref)
1631 {
1632         if (m_cursor != m_list.end())
1633         {
1634                 ref = *m_cursor++;
1635                 return 0;
1636         }
1637         ref.type = eServiceReference::idInvalid;
1638         return 1;
1639 }
1640
1641 int eDVBDBListQuery::compareLessEqual(const eServiceReferenceDVB &a, const eServiceReferenceDVB &b)
1642 {
1643         if ( m_query->m_sort == eDVBChannelQuery::tSatellitePosition )
1644         {
1645                 int x = (a.getDVBNamespace().get() >> 16);
1646                 int y = (b.getDVBNamespace().get() >> 16);
1647                 if ( x > 1800 )
1648                         x -= 3600;
1649                 if ( y > 1800 )
1650                         y -= 3600;
1651                 return x < y;
1652         }
1653         std::string aa = a.name, bb = b.name;
1654         makeUpper(aa);
1655         makeUpper(bb);
1656         return aa < bb;
1657 }
1658
1659 eDVBDBSatellitesQuery::eDVBDBSatellitesQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1660         :eDVBDBListQuery(db, source, query)
1661 {
1662         std::set<unsigned int> found;
1663         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1664                 it != m_db->m_services.end(); ++it)
1665         {
1666                 int res = !it->second->isHidden() && it->second->checkFilter(it->first, *query);
1667                 if (res)
1668                 {
1669                         unsigned int dvbnamespace = it->first.getDVBNamespace().get()&0xFFFF0000;
1670                         if (found.find(dvbnamespace) == found.end())
1671                         {
1672                                 found.insert(dvbnamespace);
1673                                 eServiceReferenceDVB ref;
1674                                 ref.setDVBNamespace(dvbnamespace);
1675                                 ref.flags=eServiceReference::flagDirectory;
1676                                 char buf[128];
1677                                 snprintf(buf, 128, "(satellitePosition == %d) && ", dvbnamespace>>16);
1678
1679                                 ref.path=buf+source.path;
1680                                 unsigned int pos=ref.path.find("FROM");
1681                                 ref.path.erase(pos);
1682                                 ref.path+="ORDER BY name";
1683 //                              eDebug("ref.path now %s", ref.path.c_str());
1684                                 m_list.push_back(ref);
1685
1686                                 ref.path=buf+source.path;
1687                                 pos=ref.path.find("FROM");
1688                                 ref.path.erase(pos+5);
1689                                 ref.path+="PROVIDERS ORDER BY name";
1690 //                              eDebug("ref.path now %s", ref.path.c_str());
1691                                 m_list.push_back(ref);
1692
1693                                 snprintf(buf, 128, "(satellitePosition == %d) && (flags == %d) && ", dvbnamespace>>16, eDVBService::dxNewFound);
1694                                 ref.path=buf+source.path;
1695                                 pos=ref.path.find("FROM");
1696                                 ref.path.erase(pos);
1697                                 ref.path+="ORDER BY name";
1698 //                              eDebug("ref.path now %s", ref.path.c_str());
1699                                 m_list.push_back(ref);
1700                         }
1701                 }
1702         }
1703         m_cursor=m_list.begin();
1704 }
1705
1706 eDVBDBProvidersQuery::eDVBDBProvidersQuery(eDVBDB *db, const eServiceReference &source, eDVBChannelQuery *query)
1707         :eDVBDBListQuery(db, source, query)
1708 {
1709         std::set<std::string> found;
1710         for (std::map<eServiceReferenceDVB, ePtr<eDVBService> >::iterator it(m_db->m_services.begin());
1711                 it != m_db->m_services.end(); ++it)
1712         {
1713                 int res = !it->second->isHidden() && it->second->checkFilter(it->first, *query);
1714                 if (res)
1715                 {
1716                         const char *provider_name = it->second->m_provider_name.length() ?
1717                                 it->second->m_provider_name.c_str() :
1718                                 "Unknown";
1719                         if (found.find(std::string(provider_name)) == found.end())
1720                         {
1721                                 found.insert(std::string(provider_name));
1722                                 eServiceReferenceDVB ref;
1723                                 char buf[64];
1724                                 ref.name=provider_name;
1725                                 snprintf(buf, 64, "(provider == \"%s\") && ", provider_name);
1726                                 ref.path=buf+source.path;
1727                                 unsigned int pos = ref.path.find("FROM");
1728                                 ref.flags=eServiceReference::flagDirectory;
1729                                 ref.path.erase(pos);
1730                                 ref.path+="ORDER BY name";
1731 //                              eDebug("ref.path now %s", ref.path.c_str());
1732                                 m_list.push_back(ref);
1733                         }
1734                 }
1735         }
1736         m_cursor=m_list.begin();
1737 }
1738
1739 /* (<name|provider|type|bouquet|satpos|chid> <==|...> <"string"|int>)[||,&& (..)] */
1740
1741 static int decodeType(const std::string &type)
1742 {
1743         if (type == "name")
1744                 return eDVBChannelQuery::tName;
1745         else if (type == "provider")
1746                 return eDVBChannelQuery::tProvider;
1747         else if (type == "type")
1748                 return eDVBChannelQuery::tType;
1749         else if (type == "bouquet")
1750                 return eDVBChannelQuery::tBouquet;
1751         else if (type == "satellitePosition")
1752                 return eDVBChannelQuery::tSatellitePosition;
1753         else if (type == "channelID")
1754                 return eDVBChannelQuery::tChannelID;
1755         else if (type == "flags")
1756                 return eDVBChannelQuery::tFlags;
1757         else
1758                 return -1;
1759 }
1760
1761         /* never, NEVER write a parser in C++! */
1762 RESULT parseExpression(ePtr<eDVBChannelQuery> &res, std::list<std::string>::const_iterator begin, std::list<std::string>::const_iterator end)
1763 {
1764         std::list<std::string>::const_iterator end_of_exp;
1765
1766         if (begin == end)
1767                 return 0;
1768
1769         if (*begin == "(")
1770         {
1771                 end_of_exp = begin;
1772                 while (end_of_exp != end)
1773                         if (*end_of_exp == ")")
1774                                 break;
1775                         else
1776                                 ++end_of_exp;
1777
1778                 if (end_of_exp == end)
1779                 {
1780                         eDebug("expression parse: end of expression while searching for closing brace");
1781                         return -1;
1782                 }
1783
1784                 ++begin;
1785                 // begin..end_of_exp
1786                 int r = parseExpression(res, begin, end_of_exp);
1787                 if (r)
1788                         return r;
1789                 ++end_of_exp;
1790
1791                         /* we had only one sub expression */
1792                 if (end_of_exp == end)
1793                 {
1794 //                      eDebug("only one sub expression");
1795                         return 0;
1796                 }
1797
1798                         /* otherwise we have an operator here.. */
1799
1800                 ePtr<eDVBChannelQuery> r2 = res;
1801                 res = new eDVBChannelQuery();
1802                 res->m_sort = 0;
1803                 res->m_p1 = r2;
1804                 res->m_inverse = 0;
1805                 r2 = 0;
1806
1807                 if (*end_of_exp == "||")
1808                         res->m_type = eDVBChannelQuery::tOR;
1809                 else if (*end_of_exp == "&&")
1810                         res->m_type = eDVBChannelQuery::tAND;
1811                 else
1812                 {
1813                         eDebug("found operator %s, but only && and || are allowed!", end_of_exp->c_str());
1814                         res = 0;
1815                         return 1;
1816                 }
1817
1818                 ++end_of_exp;
1819
1820                 return parseExpression(res->m_p2, end_of_exp, end);
1821         }
1822
1823         // "begin" <op> "end"
1824         std::string type, op, val;
1825
1826         res = new eDVBChannelQuery();
1827         res->m_sort = 0;
1828
1829         int cnt = 0;
1830         while (begin != end)
1831         {
1832                 switch (cnt)
1833                 {
1834                 case 0:
1835                         type = *begin;
1836                         break;
1837                 case 1:
1838                         op = *begin;
1839                         break;
1840                 case 2:
1841                         val = *begin;
1842                         break;
1843                 case 3:
1844                         eDebug("malformed query: got '%s', but expected only <type> <op> <val>", begin->c_str());
1845                         return 1;
1846                 }
1847                 ++begin;
1848                 ++cnt;
1849         }
1850
1851         if (cnt != 3)
1852         {
1853                 eDebug("malformed query: missing stuff");
1854                 res = 0;
1855                 return 1;
1856         }
1857
1858         res->m_type = decodeType(type);
1859
1860         if (res->m_type == -1)
1861         {
1862                 eDebug("malformed query: invalid type %s", type.c_str());
1863                 res = 0;
1864                 return 1;
1865         }
1866
1867         if (op == "==")
1868                 res->m_inverse = 0;
1869         else if (op == "!=")
1870                 res->m_inverse = 1;
1871         else
1872         {
1873                 eDebug("invalid operator %s", op.c_str());
1874                 res = 0;
1875                 return 1;
1876         }
1877
1878         res->m_string = val;
1879
1880         if (res->m_type == eDVBChannelQuery::tChannelID)
1881         {
1882                 int ns, tsid, onid;
1883                 if (sscanf(val.c_str(), "%08x%04x%04x", &ns, &tsid, &onid) == 3)
1884                         res->m_channelid = eDVBChannelID(eDVBNamespace(ns), eTransportStreamID(tsid), eOriginalNetworkID(onid));
1885                 else
1886                         eDebug("couldn't parse channelid !! format should be hex NNNNNNNNTTTTOOOO (namespace, tsid, onid)");
1887         }
1888         else
1889                 res->m_int = atoi(val.c_str());
1890
1891         return 0;
1892 }
1893
1894 RESULT eDVBChannelQuery::compile(ePtr<eDVBChannelQuery> &res, std::string query)
1895 {
1896         std::list<std::string> tokens;
1897
1898         std::string current_token;
1899         std::string bouquet_name;
1900
1901 //      eDebug("splitting %s....", query.c_str());
1902         unsigned int i = 0;
1903         const char *splitchars="()";
1904         int quotemode = 0, lastsplit = 0, lastalnum = 0;
1905         while (i <= query.size())
1906         {
1907                 int c = (i < query.size()) ? query[i] : ' ';
1908                 ++i;
1909
1910                 int issplit = !!strchr(splitchars, c);
1911                 int isaln = isalnum(c);
1912                 int iswhite = c == ' ';
1913                 int isquot = c == '\"';
1914
1915                 if (quotemode)
1916                 {
1917                         iswhite = issplit = 0;
1918                         isaln = lastalnum;
1919                 }
1920
1921                 if (issplit || iswhite || isquot || lastsplit || (lastalnum != isaln))
1922                 {
1923                         if (current_token.size())
1924                                 tokens.push_back(current_token);
1925                         current_token.clear();
1926                 }
1927
1928                 if (!(iswhite || isquot))
1929                         current_token += c;
1930
1931                 if (isquot)
1932                         quotemode = !quotemode;
1933                 lastsplit = issplit;
1934                 lastalnum = isaln;
1935         }
1936
1937 //      for (std::list<std::string>::const_iterator a(tokens.begin()); a != tokens.end(); ++a)
1938 //      {
1939 //              printf("%s\n", a->c_str());
1940 //      }
1941
1942         int sort = eDVBChannelQuery::tName;
1943                 /* check for "ORDER BY ..." */
1944
1945         std::list<std::string>::iterator it = tokens.begin();
1946         while (it != tokens.end())
1947         {
1948                 if (*it == "ORDER")
1949                 {
1950                         tokens.erase(it++);
1951                         if (it != tokens.end() && *it == "BY")
1952                         {
1953                                 tokens.erase(it++);
1954                                 sort = decodeType(*it);
1955                                 tokens.erase(it++);
1956                         } else
1957                                 sort = -1;
1958                 }
1959                 else if (*it == "FROM")
1960                 {
1961                         tokens.erase(it++);
1962                         if (it != tokens.end() && *it == "BOUQUET")
1963                         {
1964                                 tokens.erase(it++);
1965                                 bouquet_name = *it;
1966                                 tokens.erase(it++);
1967                         }
1968                         else if (it != tokens.end() && *it == "SATELLITES")
1969                                 tokens.erase(it++);
1970                         else if (it != tokens.end() && *it == "PROVIDERS")
1971                                 tokens.erase(it++);
1972                         else
1973                         {
1974                                 eDebug("FROM unknown %s", (*it).c_str());
1975                                 tokens.erase(it++);
1976                         }
1977                 }
1978                 else
1979                         ++it;
1980         }
1981
1982         if (sort == -1)
1983         {
1984                 eWarning("ORDER BY .. string invalid.");
1985                 res = 0;
1986                 return -1;
1987         }
1988
1989 //      eDebug("sort by %d", sort);
1990
1991                 /* now we recursivly parse that. */
1992         int r = parseExpression(res, tokens.begin(), tokens.end());
1993
1994                 /* we have an empty (but valid!) expression */
1995         if (!r && !res)
1996         {
1997                 res = new eDVBChannelQuery();
1998                 res->m_inverse = 0;
1999                 res->m_type = eDVBChannelQuery::tAny;
2000         }
2001
2002         if (res)
2003         {
2004                 res->m_sort = sort;
2005                 res->m_bouquet_name = bouquet_name;
2006         }
2007
2008 //      eDebug("return: %d", r);
2009         return r;
2010 }
2011
2012 DEFINE_REF(eDVBChannelQuery);