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