]> git.vomp.tv Git - vompclient.git/blob - vdr.cc
Versionscheck fuer subtitles
[vompclient.git] / vdr.cc
1 /*
2     Copyright 2004-2008 Chris Tallon
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP; if not, write to the Free Software
18     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 */
20
21 #include "vdr.h"
22
23 #include "recman.h"
24 #include "tcp.h"
25 #include "log.h"
26 #include "recinfo.h"
27 #include "dsock.h"
28 #include "channel.h"
29 #include "event.h"
30 #include "wol.h"
31 #include "vdrrequestpacket.h"
32 #include "vdrresponsepacket.h"
33 #include "command.h"
34 #ifdef VOMP_MEDIAPLAYER
35 #include "media.h"
36 #include "mediaprovider.h"
37 #include "mediaproviderids.h"
38 #endif
39 #include "vdrcommand.h"
40 #include "video.h"
41 #include "osd.h"
42 #include "movieinfo.h"
43 #include "seriesinfo.h"
44 #include "osdvector.h"
45 #include "tvmedia.h"
46
47 #define VOMP_PROTOCOLL_VERSION 0x00000302
48
49 VDR* VDR::instance = NULL;
50 #ifdef VOMP_MEDIAPLAYER
51 //prepare a request
52 //will create a request package from a command variable and fill this
53 //caller has to destroy buffer
54 static SerializeBuffer * prepareRequest(VDR_Command *cmd) {
55   SerializeBuffer *buf=new SerializeBuffer(512,false,true);
56   if (cmd->serialize(buf) != 0) {
57     delete buf;
58     return NULL;
59   }
60   return buf;
61 }
62
63 //handle request/response
64 //TODO avoid copy of buffer (needs extension of requestpacket)
65 //TODO avoid command 2x (needs some more restructuring)
66 SerializeBuffer * VDR::doRequestResponse(SerializeBuffer *rq,int cmd) {
67   VDR_RequestPacket *rt=new VDR_RequestPacket;
68   if (! rt) {
69     delete rq;
70     return NULL;
71   }
72   if (! rt->init(cmd,true,rq->getCurrent()-rq->getStart())) {
73     delete rq;
74     delete rt;
75     return NULL;
76   }
77   if (! rt->copyin(rq->getStart(),(ULONG)(rq->getCurrent()-rq->getStart()))) {
78     delete rq;
79     delete rt;
80     return NULL;
81   }
82   delete rq;
83   VDR_ResponsePacket *rp=RequestResponse(rt);
84   logger->log("doRequestResponse",Log::DEBUG,"got response %p",rp);
85   if ( !rp) {
86     delete rt;
87     return NULL;
88   }
89   SerializeBuffer *buf=new SerializeBuffer(rp->getUserData(),rp->getUserDataLength(),true,true,false);
90   delete rp;
91   return buf;
92 }
93
94
95
96 //deserialize a received response
97 //delete the package
98 //return !=0 on error
99 static int decodeResponse(SerializeBuffer *rp,VDR_Command *c) {
100   ULONG expected=c->command;
101   if (c->deserialize(rp) != 0) {
102     delete rp;
103     Log::getInstance()->log("VDR", Log::ERR, "decodeResponse unable to deserialize for command %lu",expected);
104     return -1;
105   }
106   delete rp;
107   if (c->command != expected) {
108    Log::getInstance()->log("VDR", Log::ERR, "decodeResponse unexpected response received 0x%lx, expected 0x%lx",c->command,expected);
109     return -1;
110   }
111   Log::getInstance()->log("VDR", Log::DEBUG, "decodeResponse successfully decoded command 0x%lx",expected);
112   return 0;
113 }
114
115 #endif
116
117 VDR::VDR()
118 {
119   if (instance) return;
120   instance = this;
121   initted = 0;
122   findingServer = 0;
123   tcp = NULL;
124   connected = false;
125   maxChannelNumber = 0;
126   channelNumberWidth = 1;
127   doVDRShutdown = false;
128   TEMP_SINGLE_VDR_PR = NULL;
129 #ifdef VOMP_MEDIAPLAYER
130   providerId=MPROVIDERID_VDR;
131   subRange=MPROVIDERRANGE_VDR;
132   MediaPlayerRegister::getInstance()->registerMediaProvider(this,MPROVIDERID_VDR,MPROVIDERRANGE_VDR);
133 #endif
134 }
135
136 VDR::~VDR()
137 {
138   instance = NULL;
139   if (initted) shutdown();
140 }
141
142 VDR* VDR::getInstance()
143 {
144   return instance;
145 }
146
147 int VDR::init(int tport)
148 {
149   if (initted) return 0;
150   initted = 1;
151   port = tport;
152   logger = Log::getInstance();
153   return 1;
154 }
155
156 int VDR::shutdown()
157 {
158   if (!initted) return 0;
159   initted = 0;
160   disconnect();
161   return 1;
162 }
163
164 void VDR::findServers(vector<VDRServer>& servers)
165 {
166   Wol* wol = Wol::getInstance();
167   findingServer = 1;
168   char message[15];
169   memset(message, 0, 15);
170   strcpy(message, "VDP-0001");
171   /*tcp->getMAC(&message[9]); put mac here when TCP modified to do this*/
172
173   DatagramSocket ds(0);
174   int haveAtLeastOne = 0;
175   int retval;
176   int waitType = 1;
177   bool firstloop = true;
178   while(findingServer)
179   {
180     if (waitType == 1)
181     {
182       ds.shutdown();
183       ds.init();
184       logger->log("VDR", Log::NOTICE, "Broadcasting for server");
185       ds.send("255.255.255.255", 51051, message, 15);
186       ds.send("255.255.255.255", 51052, message, 15);
187       ds.send("255.255.255.255", 51053, message, 15);
188       ds.send("255.255.255.255", 51054, message, 15);
189       ds.send("255.255.255.255", 51055, message, 15);
190       if(!firstloop) wol->doWakeUp();
191     }
192     retval = ds.waitforMessage(waitType);
193
194     if (retval == 2) // we got a reply
195     {
196       waitType = 2;
197       
198       char* vdpreply = ds.getData();
199       if ((ds.getDataLength() >= 24) && !strncmp(vdpreply, "VDP-0002", 8))
200       {
201         VDRServer newServer;
202         // FIXME upgrade this to look for a return IP in the reply packet
203         newServer.ip = new char[16];
204         strcpy(newServer.ip, ds.getFromIPA());
205
206         USHORT newServerPort;
207         memcpy(&newServerPort, &vdpreply[26], 2);
208         newServer.port = ntohs(newServerPort);
209
210         ULONG newServerVersion;
211         memcpy(&newServerVersion, &vdpreply[28], 4);
212         newServer.version = ntohl(newServerVersion);
213
214         int newServerNameLength = ds.getDataLength() - 32;
215         newServer.name = new char[newServerNameLength];
216         strcpy(newServer.name, &vdpreply[32]);
217
218         servers.push_back(newServer);
219         haveAtLeastOne = 1;
220       }
221     }
222     else
223     {
224       if (haveAtLeastOne) break;
225       waitType = 1;
226       firstloop = false;
227 /* For DEBUGGING *
228       { VDRServer newServer;
229       newServer.ip = new char[16];
230       strcpy(newServer.ip, "192.168.1.7");
231       newServer.name = new char[6];
232       strcpy(newServer.name,"debug");
233       servers.push_back(newServer);
234       waitType = 2;
235       haveAtLeastOne = 1;}/ * */
236
237
238
239     }
240   }
241   logger->log("VDR", Log::NOTICE, "END loop");
242   sort(servers.begin(), servers.end(), ServerSorter());
243 }
244
245 void VDR::cancelFindingServer()
246 {
247   findingServer = 0;
248 }
249
250 void VDR::setServerIP(char* newIP)
251 {
252   strcpy(serverIP, newIP);
253 }
254
255 void VDR::setServerPort(USHORT newPort)
256 {
257   serverPort = newPort;
258 }
259
260 int VDR::connect()
261 {
262   maxChannelNumber = 0;
263   channelNumberWidth = 1;
264
265   if (tcp) delete tcp;
266   tcp = new TCP();
267   if (tcp->connectTo(serverIP, serverPort))
268   {
269     connected = true;
270     threadStart();
271     return 1;
272   }
273   else
274   {
275     return 0;
276   }
277 }
278
279 void VDR::disconnect()
280 {
281   threadCancel();
282   if (tcp) delete tcp;
283   tcp = NULL;
284   connected = false;
285   logger->log("VDR", Log::DEBUG, "Disconnect");
286 }
287
288 void VDR::setReceiveWindow(size_t size)
289 {
290   if (connected && size) tcp->setReceiveWindow(size);
291 }
292
293 ///////////////////////////////////////////////////////
294
295 void VDR::threadMethod()
296 {
297   logger->log("VDR", Log::DEBUG, "VDR RUN");  
298
299   threadSetKillable(); // FIXME - change this to deal with the EDRs
300   
301   ULONG channelID;
302   
303   ULONG requestID;
304   ULONG userDataLength;
305   UCHAR* userData;
306
307   ULONG streamID;
308   ULONG flag;
309
310   VDR_ResponsePacket* vresp;
311   
312   ULONG timeNow = 0;
313   ULONG lastKAsent = 0;
314   ULONG lastKArecv = time(NULL);
315   int readSuccess;
316
317   while(1)
318   {
319     timeNow = time(NULL);
320     
321     readSuccess = tcp->readData((UCHAR*)&channelID, sizeof(ULONG));  // 2s timeout atm
322
323     if (!readSuccess)
324     {
325       //logger->log("VDR", Log::DEBUG, "Net read timeout");
326       if (!tcp->isConnected()) { connectionDied(); return; } // return to stop this thread
327     }
328       
329     // Error or timeout.
330
331     if (!lastKAsent) // have not sent a KA
332     {
333       if (lastKArecv < (timeNow - 5))
334       {
335         logger->log("VDR", Log::DEBUG, "Sending KA packet");
336         if (!sendKA(timeNow))
337         {
338           logger->log("VDR", Log::DEBUG, "Could not send KA, calling connectionDied");
339           connectionDied();
340           return;
341         }
342         lastKAsent = timeNow;
343       }
344     }
345     else
346     {
347       if (lastKAsent <= (timeNow - 10))
348       {
349         logger->log("VDR", Log::DEBUG, "lastKA over 10s ago, calling connectionDied");
350         connectionDied();
351         return;
352       }    
353     }
354
355     if (!readSuccess) continue; // no data was read but the connection is ok.
356     
357     // Data was read
358             
359     channelID = ntohl(channelID);
360
361     if (channelID == CHANNEL_REQUEST_RESPONSE)
362     {
363       if (!tcp->readData((UCHAR*)&requestID, sizeof(ULONG))) break;
364       requestID = ntohl(requestID);
365       if (!tcp->readData((UCHAR*)&userDataLength, sizeof(ULONG))) break;
366       userDataLength = ntohl(userDataLength);
367       if (userDataLength > 5000000) break; // how big can these packets get?
368       userData = NULL;
369       if (userDataLength > 0)
370       {
371         userData = (UCHAR*)malloc(userDataLength);
372         if (!userData) break;
373         if (!tcp->readData(userData, userDataLength)) break;
374       }
375
376       vresp = new VDR_ResponsePacket();  
377       vresp->setResponse(requestID, userData, userDataLength);
378       logger->log("VDR", Log::DEBUG, "Rxd a response packet, requestID=%lu, len=%lu", requestID, userDataLength);
379
380       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
381       {
382         // If edFindAndCall returns true, edr was called and vresp was handed off.
383         // else, delete vresp here.
384         delete vresp;
385       }
386     }
387     else if (channelID == CHANNEL_STREAM || channelID == CHANNEL_TVMEDIA)
388     {
389       if (!tcp->readData((UCHAR*)&streamID, sizeof(ULONG))) break;
390       streamID = ntohl(streamID);
391
392       if (!tcp->readData((UCHAR*)&flag, sizeof(ULONG))) break;
393       flag = ntohl(flag);
394
395       if (!tcp->readData((UCHAR*)&userDataLength, sizeof(ULONG))) break; 
396       userDataLength = ntohl(userDataLength);
397       userData = NULL;
398       if (userDataLength > 0)
399       {
400         userData = (UCHAR*)malloc(userDataLength);
401         if (!userData) break;
402         if (!tcp->readData(userData, userDataLength)) break;
403       }
404
405       vresp = new VDR_ResponsePacket();    
406       vresp->setStream(streamID, flag, userData, userDataLength, channelID);
407       //logger->log("VDR", Log::DEBUG, "Rxd a stream packet, streamID=%lu, flag=%lu, len=%lu", streamID, flag, userDataLength);
408
409       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
410       {
411         // If edFindAndCall returns true, edr was called and vresp was handed off.
412         // else, delete vresp here.
413         delete vresp;
414       }
415     }
416     else if (channelID == CHANNEL_KEEPALIVE)
417     {
418       ULONG KAreply = 0;
419       if (!tcp->readData((UCHAR*)&KAreply, sizeof(ULONG))) break;
420       KAreply = (ULONG)ntohl(KAreply);
421       if (KAreply == lastKAsent) // successful KA response
422       {
423         lastKAsent = 0;
424         lastKArecv = KAreply;
425         logger->log("VDR", Log::DEBUG, "Rxd correct KA reply");
426       }
427     }
428     else
429     {
430       logger->log("VDR", Log::ERR, "Rxd a response packet on channel %lu !!", channelID);
431       break;
432     }
433     threadCheckExit();
434
435
436     // Who deletes vresp?
437     // If RR, the individual protocol functions must delete vresp.
438     // If stream, the data and length is taken out in ed_cb_call and vresp is deleted there.
439   }
440  
441   connectionDied();
442 }
443
444 void VDR::connectionDied()
445 {
446   // Called from within threadMethod to do cleanup if it decides the connection has died
447
448   connected = false; // though actually it could still be connected until someone calls vdr->disconnect
449
450   // Need to wake up any waiting channel 1 request-response threads
451   // Normally this is done by a packet coming in with channelid and requestid      
452   // Instead, go through the list and for each channel 1 edr, make an empty vresp
453   // An empty vresp will have userData == NULL, which means vresp->noResponse() == true
454
455   // If it's a stream receiver, generate a stream packet with flag == connection_lost
456
457   edLock();
458   VDR_PacketReceiver* vdrpr;
459   VDR_ResponsePacket* vresp;
460   while(receivers.size())
461   {
462     vdrpr = (VDR_PacketReceiver*) *(receivers.begin());
463     if (vdrpr->receiverChannel == CHANNEL_REQUEST_RESPONSE)
464     {
465       vresp = new VDR_ResponsePacket();
466       vresp->setResponse(vdrpr->requestSerialNumber, NULL, 0);
467       logger->log("VDR", Log::DEBUG, "Timeouts: created blank response packet for request serial %lu", vdrpr->requestSerialNumber);
468       edUnlock();
469       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
470       {
471         // If edFindAndCall returns true, edr was called and vresp was handed off.
472         // else, delete vresp here.
473         logger->log("VDR", Log::ERR, "Timeouts: no waiting thread found for request serial %lu !!!", vdrpr->requestSerialNumber);
474         delete vresp;
475       }
476       edLock();
477     }
478     else if (vdrpr->receiverChannel == CHANNEL_STREAM || vdrpr->receiverChannel == CHANNEL_TVMEDIA)
479     {
480       vresp = new VDR_ResponsePacket();
481       vresp->setStream(vdrpr->streamID, 2 /* connection-lost flag */ , NULL, 0, vdrpr->receiverChannel);
482       logger->log("VDR", Log::DEBUG, "Timeouts: created blank response packet for streamid %lu", vdrpr->streamID);
483       edUnlock();
484       if (!edFindAndCall(vresp)) // makes ED lock, find receiver for vresp (using ed_cb_find() ) and then call (using ed_cb_call() )
485       {
486         // If edFindAndCall returns true, edr was called and vresp was handed off.
487         // else, delete vresp here.
488         logger->log("VDR", Log::ERR, "Timeouts: no waiting stream receiver found for streamid %lu !!!", vdrpr->streamID);
489         delete vresp;
490       }
491       edLock();
492       
493       for(EDRL::iterator i = receivers.begin(); i != receivers.end(); i++)
494         if ((VDR_PacketReceiver*)*i == vdrpr) { receivers.erase(i); break; }
495     }
496   }
497   edUnlock();
498   // Ok, all event receviers should be dealt with. just in case there weren't any, inform command
499   logger->log("VDR", Log::DEBUG, "edUnlock at end of connectionDied");
500
501   Command::getInstance()->connectionLost();
502 }
503
504 bool VDR::ed_cb_find(EDReceiver* edr, void* userTag)
505 {
506   // edr is a VDR_PacketReceiver object made in VDR::RequestResponse
507   // userTag is a VDR_ResponsePacket made in threadMethod
508
509   VDR_PacketReceiver* vdrpr = (VDR_PacketReceiver*)edr;
510   VDR_ResponsePacket* vresp = (VDR_ResponsePacket*)userTag;
511   
512   // Is vresp for vdrpr ?
513   
514   ULONG packetChannel = vresp->getChannelID();
515   //logger->log("VDR", Log::DEBUG, "TVMedia debug %d %d %x", vdrpr->receiverChannel,packetChannel,vdrpr);
516   if (vdrpr->receiverChannel != packetChannel) return false;
517
518   if (packetChannel == CHANNEL_REQUEST_RESPONSE)
519   {
520     if (vdrpr->requestSerialNumber == vresp->getRequestID()) return true;
521   }
522   else if (packetChannel == CHANNEL_STREAM)
523   {
524     if (vdrpr->streamID == vresp->getStreamID()) return true;
525   } else  if (packetChannel == CHANNEL_TVMEDIA)
526   { //We want them all
527     return true;
528   }
529  
530   return false;
531 }
532
533 VDR_ResponsePacket* VDR::RequestResponse(VDR_RequestPacket* vrp)
534 {
535   //logger->log("VDR", Log::DEBUG, "RR %lu", vrp->getOpcode());
536
537   if (!connected)
538   {
539     logger->log("VDR", Log::DEBUG, "RR when !connected");
540     VDR_ResponsePacket* vresp = new VDR_ResponsePacket();
541     return vresp; // "no-response" return
542   }
543
544   // ED make new VDR and register
545   // make a VDR_PacketReceiver
546   // - init with serial number of request packet
547
548   VDR_PacketReceiver vdrpr;
549 //  vdrpr.requestTime = time(NULL);
550   vdrpr.receiverChannel = VDR::CHANNEL_REQUEST_RESPONSE;
551   vdrpr.requestSerialNumber = vrp->getSerial();
552
553   edRegister(&vdrpr);
554    
555   edLock();  
556
557   if ((ULONG)tcp->sendData(vrp->getPtr(), vrp->getLen()) != vrp->getLen())
558   {
559     edUnlock();
560     edUnregister(&vdrpr);
561     VDR_ResponsePacket* vresp = new VDR_ResponsePacket();
562     return vresp; // "no-response" return
563   }
564
565   // Sleep and block this thread. The sleep unlocks the mutex
566   logger->log("VDR", Log::DEBUG, "RR sleep - opcode %lu", vrp->getOpcode());
567   edSleepThisReceiver(&vdrpr);
568   logger->log("VDR", Log::DEBUG, "RR unsleep");
569     
570   // Woken because a response packet has arrived, mutex will be locked
571   logger->log("VDR", Log::DEBUG, "Packet delivered to me, requestID: %lu", vdrpr.save_vresp->getRequestID());
572   
573   edUnlock();
574   return vdrpr.save_vresp;
575 }
576
577 bool VDR::sendKA(ULONG timeStamp)
578 {
579   char buffer[8];
580
581   int pos=0;
582   ULONG ul=CHANNEL_KEEPALIVE;
583   buffer[pos++]=(ul>>24)&0xff;
584   buffer[pos++]=(ul>>16)&0xff;
585   buffer[pos++]=(ul>>8)&0xff;
586   buffer[pos++]=ul &0xff;
587   ul=timeStamp;
588   buffer[pos++]=(ul>>24)&0xff;
589   buffer[pos++]=(ul>>16)&0xff;
590   buffer[pos++]=(ul>>8)&0xff;
591   buffer[pos++]=ul &0xff;
592   if ((ULONG)tcp->sendData(buffer, 8) != 8) return false;
593   return true;
594 }
595
596 /////////////////////////////////////////////////////////////////////////////
597
598 // Here VDR takes a break for the VDR_PacketReceiver helper class
599
600 bool VDR_PacketReceiver::call(void* userTag, bool & deleteme)
601 {
602   if (receiverChannel == VDR::CHANNEL_REQUEST_RESPONSE)
603   {
604     // It's a RR. Save vresp and, signal the waiting thread and return.
605     // VDR::RequestResponse will be blocking waiting for this to happen.
606     // That function has a pointer to this object and can read save_vresp.
607     save_vresp = (VDR_ResponsePacket*)userTag;
608     deleteme=false;
609     return true; // Signals ED to remove edr from receivers and wake up edr thread
610   }
611   
612   if (receiverChannel == VDR::CHANNEL_STREAM)
613   {
614     // It's a stream packet.
615     VDR_ResponsePacket* vresp = (VDR_ResponsePacket*)userTag;
616     streamReceiver->streamReceive(vresp->getFlag(), vresp->getUserData(), vresp->getUserDataLength());
617     delete vresp;
618     deleteme=false;
619     return false;
620   }
621   if (receiverChannel == VDR::CHANNEL_TVMEDIA)
622   {
623           // It's TVMedia
624           VDR_ResponsePacket* vresp = (VDR_ResponsePacket*)userTag;
625           Log::getInstance()->log("VDR", Log::DEBUG, "TVMedia Pictures arrived VDR %x",vresp->getStreamID());
626           OsdVector *osd=dynamic_cast<OsdVector*>(Osd::getInstance());
627           if (osd) osd->getPictReader()->receivePicture(vresp);
628           else delete vresp; //nonsense
629           deleteme=false;
630           return true;
631   }
632
633
634   abort(); // unknown receiverChannel, should not happen
635 }
636
637 /////////////////////////////////////////////////////////////////////////////
638
639 int VDR::doLogin(unsigned int* v_server_min, unsigned int* v_server_max, unsigned int* v_client,
640                 ASLPrefList& list, int &subtitles)
641 {
642   VDR_RequestPacket vrp;
643   if (!vrp.init(VDR_LOGIN, true, 6)) return 0;
644
645   char* mactemp[6];
646   tcp->getMAC((char*)mactemp);
647   if (!vrp.copyin((UCHAR*)mactemp, 6)) return 0;
648
649   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
650   if (vresp->noResponse()) { delete vresp; return 0; }
651
652   ULONG vdrTime = vresp->extractULONG();
653   logger->log("VDR", Log::DEBUG, "vdrtime = %lu", vdrTime);
654   long vdrTimeOffset = vresp->extractLONG();
655   logger->log("VDR", Log::DEBUG, "offset = %i", vdrTimeOffset);
656
657   unsigned int version_min=vresp->extractULONG();
658
659   *v_server_min=version_min;
660   unsigned int version_max=vresp->extractULONG();
661   *v_server_max=version_max;
662   *v_client=VOMP_PROTOCOLL_VERSION;
663
664   if (0x00000302 <= version_max) {
665           unsigned int numlangcodes = vresp->extractULONG();
666           subtitles = vresp->extractULONG();
667           list.clear();
668           for (int i=0; i<numlangcodes; i++) {
669                   ASLPref newpref;
670                   newpref.audiopref = vresp->extractLONG();
671                   newpref.subtitlepref = vresp->extractLONG();
672                   newpref.langcode = vresp->extractStdString();
673                   //logger->log("VDR", Log::DEBUG, "Langpref %s %d %d", newpref.langcode.c_str(),  newpref.audiopref,  newpref.subtitlepref);
674                   list.push_back(newpref);
675           }
676   }
677
678
679   delete vresp;
680
681   if ((version_min > VOMP_PROTOCOLL_VERSION)
682                   || (version_max < VOMP_PROTOCOLL_VERSION) ) {
683
684           return 0;
685
686   }
687
688   // Set the time and zone on the MVP only
689
690 #if !defined(WIN32) && !defined(__ANDROID__)
691   struct timespec currentTime;
692   currentTime.tv_sec = vdrTime;
693   currentTime.tv_nsec = 0;
694
695   int b = clock_settime(CLOCK_REALTIME, &currentTime);
696
697   logger->log("VDR", Log::DEBUG, "set clock = %u", b);
698
699   // now make a TZ variable and set it
700   char sign;
701   int hours;
702   int minutes;
703   if (vdrTimeOffset > 0) sign = '-';
704   else sign = '+';
705
706   vdrTimeOffset = abs(vdrTimeOffset);
707
708   hours = (int)vdrTimeOffset / 3600;
709   minutes = vdrTimeOffset % 3600;
710
711   logger->log("VDR", Log::DEBUG, "%c %i %i", sign, hours, minutes);
712
713   minutes = (int)minutes / 60;
714
715   logger->log("VDR", Log::DEBUG, "%c %i %i", sign, hours, minutes);
716
717   char newTZ[30];
718   sprintf(newTZ, "MVP%c%i:%i", sign, hours, minutes);
719   setenv("TZ", newTZ, 1);
720
721   logger->log("VDR", Log::DEBUG, "Timezone data: %s", newTZ);
722 #endif
723
724   setCharset(Osd::getInstance()->charSet());
725
726   return 1;
727 }
728
729 bool VDR::LogExtern(const char* logString)
730 {
731   if (!connected) return false;
732   int stringLength = strlen(logString);
733   int packetLength = stringLength + 8;
734   char *buffer=new char[packetLength + 1];
735   int pos=0;
736   ULONG ul=CHANNEL_NETLOG;
737   buffer[pos++]=(ul>>24)&0xff;
738   buffer[pos++]=(ul>>16)&0xff;
739   buffer[pos++]=(ul>>8)&0xff;
740   buffer[pos++]=ul &0xff;
741   ul=stringLength;
742   buffer[pos++]=(ul>>24)&0xff;
743   buffer[pos++]=(ul>>16)&0xff;
744   buffer[pos++]=(ul>>8)&0xff;
745   buffer[pos++]=ul &0xff;
746
747   strcpy(&buffer[8], logString);
748   
749   if (tcp->sendData(buffer, packetLength) != packetLength)
750   {
751     connected = false; // stop the rest of the connection  
752     delete [] buffer;
753     return false;
754   }
755   delete [] buffer;
756   return true;
757 }
758
759 bool VDR::setCharset(int charset)
760 {
761   VDR_RequestPacket vrp;
762   if (!vrp.init(VDR_SETCHARSET, true, sizeof(ULONG))) return false;
763   if (!vrp.addULONG(charset)) return false;
764
765   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
766   if (vresp->noResponse()) { delete vresp; return false; }
767
768   ULONG success = vresp->extractULONG();
769   delete vresp;
770
771   if (!success) return false;
772
773   return true;
774 }
775
776 bool VDR::getRecordingsList(RecMan* recman)
777 {
778   VDR_RequestPacket vrp;
779   if (!vrp.init(VDR_GETRECORDINGLIST, true, 0)) return false;
780
781   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
782   if (vresp->noResponse()) { delete vresp; return false; }
783
784   ULONG totalSpace = vresp->extractULONG();
785   ULONG freeSpace = vresp->extractULONG();
786   ULONG percent = vresp->extractULONG();
787
788   recman->setStats(totalSpace, freeSpace, percent);
789
790   ULONG start;
791   UCHAR isNew;
792   char* name;
793   char* fileName;
794
795   while (!vresp->end())
796   {
797     start = vresp->extractULONG();
798     isNew = vresp->extractUCHAR();
799     name = vresp->extractString();
800     fileName = vresp->extractString();
801     recman->addEntry(isNew, start, name, fileName);
802     delete[] name;
803     delete[] fileName;
804   }
805   delete vresp;
806
807   return true;
808 }
809
810 int VDR::deleteRecording(char* fileName)
811 {
812   VDR_RequestPacket vrp;
813   if (!vrp.init(VDR_DELETERECORDING, true, strlen(fileName) + 1)) return 0;
814   if (!vrp.addString(fileName)) return 0;
815   
816   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
817   if (vresp->noResponse()) { delete vresp; return 0; }
818   
819   int toReturn = (int)vresp->extractULONG();
820   delete vresp;
821
822   return toReturn;
823 }
824
825 char* VDR::moveRecording(char* fileName, char* newPath)
826 {
827   VDR_RequestPacket vrp;
828   if (!vrp.init(VDR_MOVERECORDING, true, strlen(fileName) + 1 + strlen(newPath) + 1)) return NULL;
829   if (!vrp.addString(fileName)) return NULL;
830   if (!vrp.addString(newPath)) return NULL;
831   
832   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
833   if (vresp->noResponse()) { delete vresp; return NULL; }
834   
835   char* toReturn = NULL;
836   int success = (int)vresp->extractULONG();
837   if (success == 1)
838   {
839     toReturn = vresp->extractString();
840   }
841
842   delete vresp;
843
844   return toReturn;
845 }
846
847 ChannelList* VDR::getChannelsList(ULONG type)
848 {
849   VDR_RequestPacket vrp;
850   if (!vrp.init(VDR_GETCHANNELLIST, true, 0)) return NULL;
851
852   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
853   if (vresp->noResponse()) { delete vresp; return NULL; }
854   
855   ChannelList* chanList = new ChannelList();
856
857   bool h264support=Video::getInstance()->supportsh264();
858   bool mpeg2support=Video::getInstance()->supportsmpeg2();
859
860   while (!vresp->end())
861   {
862     Channel* chan = new Channel();
863     chan->number = vresp->extractULONG();
864     chan->type = vresp->extractULONG();
865     chan->name = vresp->extractString();
866     chan->vstreamtype = vresp->extractULONG();
867
868     if (chan->type == type && ((chan->vstreamtype==0x1b && h264support)|| (chan->vstreamtype!=0x1b &&mpeg2support)) )
869     {
870       chanList->push_back(chan);
871       logger->log("VDR", Log::DEBUG, "Have added a channel to list. %lu %lu %s", chan->number, chan->type, chan->name);
872       if (chan->number > maxChannelNumber) maxChannelNumber = chan->number;
873     }
874     else
875     {
876       delete chan;
877     }
878   }
879
880   delete vresp;
881
882   if (maxChannelNumber > 99999)
883     channelNumberWidth = 6;
884   else if (maxChannelNumber > 9999)
885     channelNumberWidth = 5;
886   else if (maxChannelNumber > 999)
887     channelNumberWidth = 4;
888   else if (maxChannelNumber > 99)
889     channelNumberWidth = 3;
890   else if (maxChannelNumber > 9)
891     channelNumberWidth = 2;
892   else
893     channelNumberWidth = 1;
894
895   return chanList;
896 }
897
898 int VDR::streamChannel(ULONG number, StreamReceiver* tstreamReceiver)
899 {
900   VDR_RequestPacket vrp;
901   if (!vrp.init(VDR_STREAMCHANNEL, true, sizeof(ULONG))) return 0;
902   if (!vrp.addULONG(number)) return 0;
903   
904   
905   VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
906   vdrpr->receiverChannel = VDR::CHANNEL_STREAM;
907   vdrpr->streamID = vrp.getSerial();
908   vdrpr->streamReceiver = tstreamReceiver;
909   edRegister(vdrpr);
910   TEMP_SINGLE_VDR_PR = vdrpr;
911   
912   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
913   if (vresp->noResponse())
914   {
915     delete vresp;
916     edUnregister(vdrpr);
917     delete vdrpr;
918     return 0;
919   }
920   
921   int toReturn = (int)vresp->extractULONG();
922   logger->log("VDR", Log::DEBUG, "VDR said %lu to start streaming request", toReturn);
923   delete vresp;
924
925   return toReturn;
926 }
927
928 int VDR::stopStreaming()
929 {
930   VDR_RequestPacket vrp;
931   if (!vrp.init(VDR_STOPSTREAMING, true, 0)) return 0;
932
933   if (TEMP_SINGLE_VDR_PR) // this block only needs to be done if it was a live stream
934                           // TEMP_SINGLE_VDR_PR will not be set unless we are streaming a channel
935   {
936     edUnregister(TEMP_SINGLE_VDR_PR);
937     delete TEMP_SINGLE_VDR_PR;
938     TEMP_SINGLE_VDR_PR = NULL;
939   }
940
941   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
942   if (vresp->noResponse()) { delete vresp; return 0; }
943   
944   int toReturn = (int)vresp->extractULONG();
945   delete vresp;
946
947   return toReturn;
948 }
949
950 UCHAR* VDR::getBlock(ULLONG position, UINT maxAmount, UINT* amountReceived)
951 {
952   VDR_RequestPacket vrp;
953   if (!vrp.init(VDR_GETBLOCK, true, sizeof(ULLONG) + sizeof(ULONG))) return NULL;
954   if (!vrp.addULLONG(position)) return NULL;
955   if (!vrp.addULONG(maxAmount)) return NULL;
956
957   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
958   if (vresp->noResponse()) { delete vresp; return NULL; }
959
960   if (vresp->serverError())
961   {
962     logger->log("VDR", Log::DEBUG, "Detected getblock 0");
963     delete vresp;
964     return NULL;
965   }
966
967   // Special handling for getblock
968   UCHAR* toReturn = vresp->getUserData();
969   *amountReceived = vresp->getUserDataLength();
970   
971   delete vresp;
972   
973   return toReturn;
974 }
975
976 ULLONG VDR::streamRecording(char* fileName, ULONG* totalFrames, bool* IsPesRecording)
977 {
978   VDR_RequestPacket vrp;
979   if (!vrp.init(VDR_STREAMRECORDING, true, strlen(fileName) + 1)) return 0;
980   if (!vrp.addString(fileName)) return 0;
981
982   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
983   if (vresp->noResponse()) { delete vresp; return 0; }
984   
985   ULLONG lengthBytes = vresp->extractULLONG();
986   ULONG lengthFrames = vresp->extractULONG();
987   UCHAR isPesRecording = vresp->extractUCHAR();
988   delete vresp;
989
990   *totalFrames = lengthFrames;
991   *IsPesRecording = (isPesRecording);//convert Uchar to bool
992
993   logger->log("VDR", Log::DEBUG, "VDR said length is: %llu %lu, IsPesRecording %x", lengthBytes, lengthFrames, *IsPesRecording);
994
995   return lengthBytes;
996 }
997
998 ULLONG VDR::positionFromFrameNumber(ULONG frameNumber)
999 {
1000   VDR_RequestPacket vrp;
1001   if (!vrp.init(VDR_POSFROMFRAME, true, sizeof(ULONG))) return 0;
1002   if (!vrp.addULONG(frameNumber)) return 0;
1003
1004   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1005   if (vresp->noResponse()) { delete vresp; return 0; }
1006   
1007   ULLONG position = vresp->extractULLONG();
1008   delete vresp;
1009   
1010   logger->log("VDR", Log::DEBUG, "VDR said new position is: %llu", position);
1011
1012   return position;
1013 }
1014
1015 ULONG VDR::frameNumberFromPosition(ULLONG position)
1016 {
1017   VDR_RequestPacket vrp;
1018   if (!vrp.init(VDR_FRAMEFROMPOS, true, sizeof(ULLONG))) return 0;
1019   if (!vrp.addULLONG(position)) return 0;
1020
1021   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1022   if (vresp->noResponse()) { delete vresp; return 0; }
1023   
1024   ULONG framenumber = vresp->extractULONG();
1025   delete vresp;
1026   
1027   logger->log("VDR", Log::DEBUG, "VDR said new framenumber is: %u", framenumber);
1028
1029   return framenumber;
1030 }
1031
1032 bool VDR::getNextIFrame(ULONG frameNumber, ULONG direction, ULLONG* rfilePosition, ULONG* rframeNumber, ULONG* rframeLength)
1033 {
1034   VDR_RequestPacket vrp;
1035   if (!vrp.init(VDR_GETNEXTIFRAME, true, sizeof(ULONG)*2)) return false;
1036   if (!vrp.addULONG(frameNumber)) return false;
1037   if (!vrp.addULONG(direction)) return false;
1038
1039   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1040   if (vresp->noResponse()) { delete vresp; return false; }
1041   
1042   if (vresp->serverError())
1043   {
1044     logger->log("VDR", Log::DEBUG, "Detected getNextIFrame error");
1045     delete vresp;
1046     return false;
1047   }
1048
1049   *rfilePosition = vresp->extractULLONG();
1050   *rframeNumber = vresp->extractULONG();
1051   *rframeLength = vresp->extractULONG();
1052
1053   delete vresp;
1054
1055   logger->log("VDR", Log::DEBUG, "VDR GNIF said %llu %lu %lu", *rfilePosition, *rframeNumber, *rframeLength);
1056
1057   return true;
1058 }
1059
1060 EventList* VDR::getChannelSchedule(ULONG number)
1061 {
1062   time_t now;
1063   time(&now);
1064   return getChannelSchedule(number, now, 24 * 60 * 60);
1065 }
1066
1067 EventList* VDR::getChannelSchedule(ULONG number, time_t start, ULONG duration)
1068 {
1069 // retrieve event list (vector of events) from vdr within filter window. duration is in seconds
1070
1071   VDR_RequestPacket vrp;
1072   if (!vrp.init(VDR_GETCHANNELSCHEDULE, true, sizeof(ULONG)*3)) return NULL;
1073   if (!vrp.addULONG(number)) return NULL;
1074   if (!vrp.addULONG(start)) return NULL;
1075   if (!vrp.addULONG(duration)) return NULL;
1076
1077   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1078   if (vresp->noResponse()) { delete vresp; return NULL; }
1079
1080   // received a ulong(0) - schedules error in the plugin
1081   if (vresp->serverError())
1082   {
1083     delete vresp;
1084     return NULL;
1085   }
1086
1087   EventList* eventList = new EventList();
1088
1089   while (!vresp->end())
1090   {
1091     Event* event = new Event();
1092     event->id = vresp->extractULONG();
1093     event->time = vresp->extractULONG();
1094     event->duration = vresp->extractULONG();
1095     event->title = vresp->extractString();
1096     event->subtitle = vresp->extractString();
1097     event->description = vresp->extractString();
1098     eventList->push_back(event);
1099   }
1100
1101   delete vresp;
1102
1103   logger->log("VDR", Log::DEBUG, "Success got to end of getChannelSchedule");
1104   return eventList;
1105 }
1106
1107 int VDR::configSave(const char* section, const char* key, const char* value)
1108 {
1109   VDR_RequestPacket vrp;
1110   if (!vrp.init(VDR_CONFIGSAVE, false, 0)) return 0;
1111   if (!vrp.addString(section)) return 0;
1112   if (!vrp.addString(key)) return 0;
1113   if (!vrp.addString(value)) return 0;
1114
1115   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1116   if (vresp->noResponse()) { delete vresp; return 0; }
1117
1118   int toReturn = (int)vresp->extractULONG();
1119   delete vresp;
1120
1121   return toReturn;
1122 }
1123
1124 char* VDR::configLoad(const char* section, const char* key)
1125 {
1126   VDR_RequestPacket vrp;
1127   if (!vrp.init(VDR_CONFIGLOAD, false, 0)) return NULL;
1128   if (!vrp.addString(section)) return NULL;
1129   if (!vrp.addString(key)) return NULL;
1130
1131   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1132   if (vresp->noResponse()) { delete vresp; return NULL; }
1133   
1134   char* toReturn = vresp->extractString();
1135   delete vresp;
1136
1137   return toReturn;
1138 }
1139
1140 RecTimerList* VDR::getRecTimersList()
1141 {
1142   VDR_RequestPacket vrp;
1143   if (!vrp.init(VDR_GETTIMERS, true, 0)) return NULL;
1144
1145   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1146   if (vresp->noResponse()) { delete vresp; return NULL; }
1147
1148   RecTimerList* recTimerList = new RecTimerList();
1149
1150   ULONG numTimers = vresp->extractULONG();
1151   if (numTimers > 0)
1152   {
1153     RecTimer* newRecTimer;
1154     char* tempString;
1155
1156     while (!vresp->end())
1157     {
1158       newRecTimer = new RecTimer();
1159       newRecTimer->active = vresp->extractULONG();
1160       newRecTimer->recording = vresp->extractULONG();
1161       newRecTimer->pending = vresp->extractULONG();
1162       newRecTimer->priority = vresp->extractULONG();
1163       newRecTimer->lifeTime = vresp->extractULONG();
1164       newRecTimer->channelNumber = vresp->extractULONG();
1165       newRecTimer->startTime = vresp->extractULONG();
1166       newRecTimer->stopTime = vresp->extractULONG();
1167       newRecTimer->day = vresp->extractULONG();
1168       newRecTimer->weekDays = vresp->extractULONG();
1169
1170       tempString = vresp->extractString();
1171       newRecTimer->setFile(tempString);
1172       delete[] tempString;
1173
1174       recTimerList->push_back(newRecTimer);
1175       logger->log("VDR", Log::DEBUG, "TL: %lu %lu %lu %lu %lu %lu %lu %lu %s",
1176         newRecTimer->active, newRecTimer->recording, newRecTimer->pending, newRecTimer->priority, newRecTimer->lifeTime,
1177         newRecTimer->channelNumber, newRecTimer->startTime, newRecTimer->stopTime, newRecTimer->getFile());
1178     }
1179   }
1180
1181   delete vresp;
1182
1183   sort(recTimerList->begin(), recTimerList->end(), RecTimerSorter());
1184
1185   return recTimerList;
1186 }
1187
1188 ULONG VDR::setEventTimer(char* timerString)
1189 {
1190   VDR_RequestPacket vrp;
1191   if (!vrp.init(VDR_SETTIMER, true, strlen(timerString) + 1)) return 0;
1192   if (!vrp.addString(timerString)) return 0;
1193
1194   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1195   if (vresp->noResponse()) { delete vresp; return 0; }
1196   
1197   ULONG toReturn = vresp->extractULONG();
1198   delete vresp;
1199
1200   return toReturn;
1201 }
1202
1203 RecInfo* VDR::getRecInfo(char* fileName)
1204 {
1205   VDR_RequestPacket vrp;
1206   if (!vrp.init(VDR_GETRECINFO, true, strlen(fileName) + 1)) return NULL;
1207   if (!vrp.addString(fileName)) return NULL;
1208   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1209
1210   if (vresp->noResponse()) { delete vresp; return NULL; }
1211
1212   if (vresp->serverError())
1213   {
1214     logger->log("VDR", Log::DEBUG, "Could not get rec info");
1215     delete vresp;
1216     return NULL;
1217   }
1218
1219   RecInfo* recInfo = new RecInfo();
1220
1221   recInfo->timerStart = vresp->extractULONG();
1222   recInfo->timerEnd = vresp->extractULONG();
1223   recInfo->resumePoint = vresp->extractULONG();
1224   recInfo->summary = vresp->extractString();
1225
1226   ULONG numComponents = vresp->extractULONG();
1227   if (numComponents)
1228   {
1229     recInfo->setNumComponents(numComponents);
1230     for (ULONG i = 0; i < numComponents; i++)
1231     {
1232       recInfo->streams[i] = vresp->extractUCHAR();
1233       recInfo->types[i] = vresp->extractUCHAR();
1234       recInfo->languages[i] = vresp->extractString();
1235       recInfo->descriptions[i] = vresp->extractString();
1236     }
1237   }
1238   recInfo->fps=vresp->extractdouble();
1239   recInfo->title=vresp->extractString();
1240   
1241
1242   recInfo->print();
1243
1244   delete vresp;
1245   return recInfo;
1246 }
1247
1248 // FIXME obselete
1249 ULLONG VDR::rescanRecording(ULONG* totalFrames)
1250 {
1251   VDR_RequestPacket vrp;
1252   if (!vrp.init(VDR_RESCANRECORDING, true, 0)) return 0;
1253
1254   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1255   if (vresp->noResponse()) { delete vresp; return 0; }
1256   
1257   ULLONG lengthBytes = vresp->extractULLONG();
1258   ULONG lengthFrames = vresp->extractULONG();
1259   delete vresp;
1260   
1261   logger->log("VDR", Log::DEBUG, "VDR said length is: %llu %lu", lengthBytes, lengthFrames);
1262
1263   *totalFrames = lengthFrames;
1264   return lengthBytes;
1265 }
1266
1267 MarkList* VDR::getMarks(char* fileName)
1268 {
1269   VDR_RequestPacket vrp;
1270   if (!vrp.init(VDR_GETMARKS, true, strlen(fileName) + 1)) return NULL;
1271   if (!vrp.addString(fileName)) return NULL;
1272
1273   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1274   if (vresp->noResponse()) { delete vresp; return NULL; }
1275   
1276   if (vresp->serverError())
1277   {
1278     delete vresp;
1279     return NULL;
1280   }
1281
1282   MarkList* markList = new MarkList();
1283
1284   while (!vresp->end())
1285   {
1286     Mark* mark = new Mark();
1287     mark->pos = vresp->extractULONG();
1288
1289     markList->push_back(mark);
1290     logger->log("VDR", Log::DEBUG, "Have added a mark to list. %lu", mark->pos);
1291   }
1292
1293   delete vresp;
1294   
1295   return markList;
1296 }
1297
1298 void VDR::getChannelPids(Channel* channel)
1299 {
1300   VDR_RequestPacket vrp;
1301   if (!vrp.init(VDR_GETCHANNELPIDS, true, sizeof(ULONG))) return ;
1302   if (!vrp.addULONG(channel->number)) return ;
1303
1304   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1305   if (vresp->noResponse()) { delete vresp; return ; }
1306   
1307   // Format of response
1308   // vpid
1309   // number of apids
1310   // {
1311   //    apid
1312   //    lang string
1313   // }
1314
1315   channel->vpid = vresp->extractULONG();
1316   channel->vstreamtype = vresp->extractULONG();
1317   channel->numAPids = vresp->extractULONG();
1318
1319   for (ULONG i = 0; i < channel->numAPids; i++)
1320   {
1321     apid newapid;
1322     newapid.pid = vresp->extractULONG();
1323     char * name=vresp->extractString();
1324     strncpy(newapid.desc,name,9);
1325     delete [] name;
1326     channel->apids.push_back(newapid);
1327   }
1328
1329   channel->numDPids = vresp->extractULONG();
1330
1331   for (ULONG i = 0; i < channel->numDPids; i++)
1332   {
1333     apid newdpid;
1334     newdpid.pid = vresp->extractULONG();
1335     char * name=vresp->extractString();
1336     strncpy(newdpid.desc,name,9);
1337     delete [] name;
1338     channel->dpids.push_back(newdpid);
1339   }
1340
1341   channel->numSPids = vresp->extractULONG();
1342
1343   for (ULONG i = 0; i < channel->numSPids; i++)
1344   {
1345     apid newspid;
1346     newspid.pid = vresp->extractULONG();
1347     char * name=vresp->extractString();
1348     strncpy(newspid.desc,name,9);
1349     delete [] name;
1350     channel->spids.push_back(newspid);
1351   }
1352   channel->tpid = vresp->extractULONG();
1353   // extension
1354   for (ULONG i = 0; i < channel->numAPids; i++)
1355   {
1356           channel->apids[i].type = vresp->extractULONG();
1357   }
1358   for (ULONG i = 0; i < channel->numDPids; i++)
1359   {
1360           channel->dpids[i].type = vresp->extractULONG();
1361   }
1362   for (ULONG i = 0; i < channel->numSPids; i++)
1363   {
1364           channel->spids[i].type = vresp->extractULONG();
1365           channel->spids[i].data1 = vresp->extractULONG();
1366           channel->spids[i].data2 = vresp->extractULONG();
1367   }
1368
1369   delete vresp;
1370   
1371   return ;
1372 }
1373
1374 #ifdef VOMP_MEDIAPLAYER
1375 MediaList * VDR::getRootList() {
1376   return getMediaList(NULL);
1377 }
1378 /**
1379   * media List Request:
1380   * mediaURI
1381   * Media List response:
1382   * mediaList
1383 */
1384 MediaList* VDR::getMediaList(const MediaURI * root)
1385 {
1386   logger->log("VDR", Log::DEBUG, "getMediaList %s,d=%s, prov=%d", (root?root->getName():"NULL"), 
1387       ((root && root->hasDisplayName())?root->getDisplayName():"NULL"),
1388       (root?root->getProvider():providerId));
1389   MediaURI remoteURI(root);
1390   VDR_GetMediaListRequest request(&remoteURI);
1391   SerializeBuffer *vrp=prepareRequest(&request);
1392   if (!vrp) {
1393     logger->log("VDR", Log::ERR, "getMediaList unable to create command");
1394     return NULL;
1395   }
1396     
1397   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1398   if (!vresp) {
1399     Command::getInstance()->connectionLost();
1400     return NULL;
1401   }
1402   
1403   MediaList *rt=new MediaList(NULL);
1404   ULONG rtflags=0;
1405   VDR_GetMediaListResponse resp(&rtflags,rt);
1406   if (decodeResponse(vresp,&resp) != 0) {
1407     return NULL;
1408   }
1409   return rt;
1410 }
1411
1412 /**
1413   * get image Request:
1414   * uri,x,y, channel
1415   * get media response:
1416   * 4 flags
1417   * 8 len of image
1418 */
1419 int VDR::openMedium(ULONG channel,const MediaURI *uri,  ULLONG * size, ULONG x, ULONG y)
1420 {
1421   MediaURI remoteURI(uri);
1422   VDR_OpenMediumRequest request(&channel,&remoteURI,&x,&y);
1423   *size=0;
1424   SerializeBuffer *vrp=prepareRequest(&request);
1425   if (!vrp) {
1426     logger->log("VDR", Log::ERR, "openMedium unable to create command");
1427     return -1;
1428   }
1429   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1430   if (!vresp) {
1431     Command::getInstance()->connectionLost();
1432     return -1;
1433   }
1434   ULONG flags=0;
1435   VDR_OpenMediumResponse response(&flags,size);
1436   if (decodeResponse(vresp,&response) != 0) {
1437     return -1;
1438   }
1439   logger->log("VDR", Log::DEBUG, "openMedia len=%llu", *size);
1440   return 0;
1441 }
1442
1443 /**
1444   * getMediaBlock - no separate response class - simple data block
1445   * resp
1446   * packet
1447   */
1448 int VDR::getMediaBlock(ULONG channel, ULLONG position, ULONG maxAmount, ULONG* amountReceived, unsigned char **buffer)
1449 {
1450   *amountReceived=0;
1451   VDR_GetMediaBlockRequest request(&channel,&position,&maxAmount);
1452   SerializeBuffer *vrp=prepareRequest(&request);
1453   if (!vrp) {
1454     logger->log("VDR", Log::ERR, "getMediaBlock unable to create command");
1455     return -1;
1456   }
1457   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1458   if (!vresp) {
1459     Command::getInstance()->connectionLost();
1460     return -1;
1461   }
1462   
1463   // Special handling for getblock
1464   *amountReceived = (ULONG)(vresp->getEnd()-vresp->getStart());
1465   *buffer = vresp->steelBuffer();
1466   delete vresp;
1467   return 0;
1468 }
1469
1470 /**
1471   * VDR_GETMEDIAINFO
1472   * channel
1473   * rt
1474   * flags
1475   * info
1476   */
1477
1478 int VDR::getMediaInfo(ULONG channel, MediaInfo * result) {
1479   if (! result) return -1;
1480   VDR_GetMediaInfoRequest request(&channel);
1481   SerializeBuffer *vrp=prepareRequest(&request);
1482   if (!vrp) {
1483     logger->log("VDR", Log::ERR, "getMediaInfo unable to create command");
1484     return -1;
1485   }
1486   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1487   if (!vresp) {
1488     Command::getInstance()->connectionLost();
1489     return -1;
1490   }
1491
1492   ULONG flags=0;
1493   VDR_GetMediaInfoResponse response(&flags,result);
1494   if (decodeResponse(vresp,&response) != 0) {
1495     return -1;
1496   }
1497   return 0;
1498 }
1499
1500 /**
1501   * VDR_CLOSECHANNEL
1502   * channel
1503   * rt
1504   * flags
1505   */
1506
1507 int VDR::closeMediaChannel(ULONG channel) {
1508   VDR_CloseMediaChannelRequest request(&channel);
1509   SerializeBuffer *vrp=prepareRequest(&request);
1510   if (!vrp) {
1511     logger->log("VDR", Log::ERR, "closeMediaChannel unable to create command");
1512     return -1;
1513   }
1514   SerializeBuffer* vresp = doRequestResponse(vrp,request.command);
1515   if (!vresp) {
1516     Command::getInstance()->connectionLost();
1517     return -1;
1518   }
1519   ULONG flags;
1520   VDR_CloseMediaChannelResponse response(&flags);
1521   if (decodeResponse(vresp,&response) != 0) return -1;
1522   return (flags != 0)?-1:0;
1523 }
1524
1525 #endif
1526
1527
1528 int VDR::deleteTimer(RecTimer* delTimer)
1529 {
1530   logger->log("VDR", Log::DEBUG, "Delete timer called");
1531   
1532   VDR_RequestPacket vrp;
1533   if (!vrp.init(VDR_DELETETIMER, false, 0)) return 0;
1534   if (!vrp.addULONG(delTimer->channelNumber)) return 0;
1535   if (!vrp.addULONG(delTimer->weekDays)) return 0;    
1536   if (!vrp.addULONG(delTimer->day)) return 0;
1537   if (!vrp.addULONG(delTimer->startTime)) return 0;  
1538   if (!vrp.addULONG(delTimer->stopTime)) return 0; 
1539    
1540   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1541   if (vresp->noResponse()) { delete vresp; return 0; }
1542   
1543   int toReturn = (int)vresp->extractULONG();
1544   delete vresp;
1545
1546   return toReturn;
1547 }
1548
1549 I18n::lang_code_list VDR::getLanguageList()
1550 {
1551   I18n::lang_code_list CodeList;
1552   CodeList["en"] = "English"; // Default entry
1553   VDR_RequestPacket vrp;
1554   if (!vrp.init(VDR_GETLANGUAGELIST, false, 0)) return CodeList;
1555   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1556   if (vresp->noResponse() || vresp->end())
1557   {
1558     delete vresp;
1559     return CodeList;
1560   }
1561   CodeList.clear();
1562   while (!vresp->end())
1563   {
1564     char* c_code = vresp->extractString();
1565     char* c_name = vresp->extractString();
1566     string code = c_code;
1567     string name = c_name;
1568     CodeList[code] = name;
1569     delete[] c_code;
1570     delete[] c_name;
1571   }
1572   delete vresp;
1573   return CodeList;
1574 }
1575
1576 int VDR::getLanguageContent(const std::string code, I18n::trans_table& texts)
1577 {
1578   VDR_RequestPacket vrp;
1579   if (!vrp.init(VDR_GETLANGUAGECONTENT, false, 0)) return 0;
1580   if (!vrp.addString(code.c_str())) return 0;
1581   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1582   if (vresp->noResponse()) { delete vresp; return 0; }
1583   texts.clear();
1584   while (!vresp->end())
1585   {
1586     char* c_key = vresp->extractString();
1587     char* c_text = vresp->extractString();
1588     string key = c_key;
1589     string text = c_text;
1590     texts[key] = text;
1591     delete[] c_key;
1592     delete[] c_text;
1593   }
1594   delete vresp;
1595   return 1;
1596 }
1597
1598 void VDR::shutdownVDR()
1599 {
1600   if(doVDRShutdown)
1601     logger->log("VDR", Log::DEBUG, "Shutting down vdr");
1602   else
1603     logger->log("VDR", Log::DEBUG, "Shutting down vomp only");
1604
1605   if(!doVDRShutdown || !connected)
1606     return;
1607
1608   VDR_RequestPacket vrp;
1609   logger->log("VDR", Log::DEBUG, "Sending shutdown");
1610   if (!vrp.init(VDR_SHUTDOWN, false, 0)) return;
1611   VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1612   delete vresp;
1613
1614   logger->log("VDR", Log::DEBUG, "VDR shutdown");
1615 }
1616
1617 void VDR::getScraperEventType(char * fileName, int & movieID,
1618                 int & seriesID, int & episodeID)
1619 {
1620         movieID = 0;
1621         seriesID = 0;
1622         episodeID = 0;
1623         VDR_RequestPacket vrp;
1624         if (!vrp.init(VDR_GETRECSCRAPEREVENTTYPE, true, strlen(fileName) + 1)) return;
1625         if (!vrp.addString(fileName)) return ;
1626         Log::getInstance()->log("Recording", Log::DEBUG, "Before Response ");
1627         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1628         Log::getInstance()->log("Recording", Log::DEBUG, "After Response ");
1629         if (vresp->noResponse()) { delete vresp; return ; }
1630         int type = vresp->extractUCHAR();
1631         if (type == 0) //serie
1632         {
1633                 seriesID = vresp->extractLONG();
1634                 episodeID = vresp->extractLONG();
1635         } else if (type == 1) //movie
1636         {
1637                 movieID = vresp->extractLONG();
1638         }
1639         delete vresp;
1640
1641 }
1642
1643 void VDR::getScraperEventType(UINT channelid, UINT eventid, int & movieID,
1644                 int & seriesID, int & episodeID, int & epgImage )
1645 {
1646         movieID = 0;
1647         seriesID = 0;
1648         episodeID = 0;
1649         epgImage = 0;
1650         VDR_RequestPacket vrp;
1651         if (!vrp.init(VDR_GETEVENTSCRAPEREVENTTYPE, false, 0)) return;
1652         if (!vrp.addULONG(channelid)) return ;
1653         if (!vrp.addULONG(eventid)) return ;
1654         Log::getInstance()->log("Recording", Log::DEBUG, "Before Response ");
1655         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1656         Log::getInstance()->log("Recording", Log::DEBUG, "After Response ");
1657         if (vresp->noResponse()) { delete vresp; return ; }
1658         int type = vresp->extractUCHAR();
1659         if (type == 0) //serie
1660         {
1661                 seriesID = vresp->extractLONG();
1662                 episodeID = vresp->extractLONG();
1663         } else if (type == 1) //movie
1664         {
1665                 movieID = vresp->extractLONG();
1666         }
1667         epgImage = vresp->extractLONG();
1668         delete vresp;
1669
1670 }
1671
1672 MovieInfo *VDR::getScraperMovieInfo(int movieID)
1673 {
1674         VDR_RequestPacket vrp;
1675         if (!vrp.init(VDR_GETSCRAPERMOVIEINFO, false, 0)) return NULL;
1676         if (!vrp.addULONG(movieID)) return NULL;
1677         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1678         if (vresp->noResponse()) { delete vresp; return NULL; }
1679         MovieInfo * movieinf= new MovieInfo();
1680
1681         movieinf->id=movieID;
1682         movieinf->title = vresp->extractStdString();
1683         movieinf->originalTitle = vresp->extractStdString();
1684         movieinf->tagline = vresp->extractStdString();
1685         movieinf->overview = vresp->extractStdString();
1686         movieinf->adult = vresp->extractUCHAR();
1687         movieinf->collectionName = vresp->extractStdString();
1688
1689         movieinf->budget = vresp->extractLONG();
1690         movieinf->revenue = vresp->extractLONG();
1691         movieinf->genres = vresp->extractStdString();
1692         movieinf->homepage = vresp->extractStdString();
1693         movieinf->releaseDate = vresp->extractStdString();
1694         movieinf->runtime = vresp->extractLONG();
1695         movieinf->popularity = vresp->extractdouble();
1696         movieinf->voteAverage = vresp->extractdouble();
1697         movieinf->poster.width = vresp->extractULONG();
1698         movieinf->poster.height = vresp->extractULONG();
1699         movieinf->poster.info.setMovieInfo(movieinf);
1700         movieinf->poster.info.setElement(0,0);
1701         movieinf->fanart.width = vresp->extractULONG();
1702         movieinf->fanart.height = vresp->extractULONG();
1703         movieinf->fanart.info.setMovieInfo(movieinf);
1704         movieinf->fanart.info.setElement(1,0);
1705         movieinf->collectionPoster.width = vresp->extractULONG();
1706         movieinf->collectionPoster.height = vresp->extractULONG();
1707         movieinf->collectionPoster.info.setMovieInfo(movieinf);
1708         movieinf->collectionPoster.info.setElement(2,0);
1709         movieinf->collectionFanart.width = vresp->extractULONG();
1710         movieinf->collectionFanart.height = vresp->extractULONG();
1711         movieinf->collectionFanart.info.setMovieInfo(movieinf);
1712         movieinf->collectionFanart.info.setElement(3,0);
1713         ULONG num_actors =  vresp->extractULONG();
1714         movieinf->actors.clear();
1715         movieinf->actors.reserve(num_actors);
1716         for (ULONG acty=0; acty < num_actors; acty++) {
1717                 Actor new_act;
1718                 new_act.name =  vresp->extractStdString();
1719                 new_act.role =  vresp->extractStdString();
1720                 new_act.thumb.width = vresp->extractULONG();
1721                 new_act.thumb.height = vresp->extractULONG();
1722                 new_act.thumb.info.setMovieInfo(movieinf);
1723                 new_act.thumb.info.setElement(4,acty);
1724                 movieinf->actors.push_back(new_act);
1725         }
1726
1727
1728         delete vresp;
1729         return movieinf;
1730
1731 }
1732
1733 SeriesInfo *VDR::getScraperSeriesInfo(int seriesID, int episodeID)
1734 {
1735         VDR_RequestPacket vrp;
1736         if (!vrp.init(VDR_GETSCRAPERSERIESINFO, false, 0)) return NULL;
1737         if (!vrp.addULONG(seriesID)) return NULL;
1738         if (!vrp.addULONG(episodeID)) return NULL;
1739
1740         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1741         if (vresp->noResponse()) { delete vresp; return 0; }
1742         SeriesInfo * seriesinf= new SeriesInfo();
1743
1744         seriesinf->id=seriesID;
1745
1746
1747         seriesinf->name = vresp->extractStdString();
1748         seriesinf->overview = vresp->extractStdString();
1749         seriesinf->firstAired = vresp->extractStdString();
1750         seriesinf->network = vresp->extractStdString();
1751         seriesinf->genre = vresp->extractStdString();
1752         seriesinf->rating =  vresp->extractdouble();
1753         seriesinf->status = vresp->extractStdString();
1754
1755
1756         seriesinf->episode.episodeid=episodeID;
1757         seriesinf->episode.number = vresp->extractLONG();
1758         seriesinf->episode.season = vresp->extractLONG();
1759         seriesinf->episode.name =  vresp->extractStdString();
1760         seriesinf->episode.firstAired =  vresp->extractStdString();
1761         seriesinf->episode.guestStars =  vresp->extractStdString();
1762         seriesinf->episode.overview =  vresp->extractStdString();
1763         seriesinf->episode.rating = vresp->extractdouble();
1764         seriesinf->episode.image.width =  vresp->extractULONG();
1765         seriesinf->episode.image.height =  vresp->extractULONG();
1766         seriesinf->episode.image.info.setSeriesInfo(seriesinf);
1767         seriesinf->episode.image.info.setElement(0,0);
1768
1769
1770         ULONG num_actors =  vresp->extractULONG();
1771         seriesinf->actors.clear();
1772         seriesinf->actors.reserve(num_actors);
1773         for (ULONG acty=0; acty < num_actors; acty++) {
1774                 Actor new_act;
1775                 new_act.name =  vresp->extractStdString();
1776                 new_act.role =  vresp->extractStdString();
1777                 new_act.thumb.width = vresp->extractULONG();
1778                 new_act.thumb.height = vresp->extractULONG();
1779                 new_act.thumb.info.setSeriesInfo(seriesinf);
1780                 new_act.thumb.info.setElement(1,acty);
1781                 seriesinf->actors.push_back(new_act);
1782         }
1783         ULONG num_posters =  vresp->extractULONG();
1784         for (ULONG medias = 0; medias < num_posters; medias++ ) {
1785                 TVMedia media;
1786                 media.info.setSeriesInfo(seriesinf);
1787                 media.info.setElement(2,medias);
1788                 media.width =  vresp->extractULONG();
1789                 media.height = vresp->extractULONG();
1790                 seriesinf->posters.push_back(media);
1791         }
1792
1793         ULONG num_banners =  vresp->extractULONG();
1794         for (ULONG medias = 0; medias < num_banners; medias++ ) {
1795                 TVMedia media;
1796                 media.info.setSeriesInfo(seriesinf);
1797                 media.info.setElement(3,medias);
1798                 media.width =  vresp->extractULONG();
1799                 media.height = vresp->extractULONG();
1800                 seriesinf->banners.push_back(media);
1801         }
1802         ULONG num_fanarts =  vresp->extractULONG();
1803         for (ULONG medias = 0; medias < num_fanarts; medias++ ) {
1804                 TVMedia media;
1805                 media.info.setSeriesInfo(seriesinf);
1806                 media.info.setElement(4,medias);
1807                 media.width =  vresp->extractULONG();
1808                 media.height = vresp->extractULONG();
1809                 seriesinf->fanart.push_back(media);
1810         }
1811         seriesinf->seasonposter.width = vresp->extractULONG();
1812         seriesinf->seasonposter.height = vresp->extractULONG();
1813         seriesinf->seasonposter.info.setSeriesInfo(seriesinf);
1814         seriesinf->seasonposter.info.setElement(5,0);
1815
1816         delete vresp;
1817         return seriesinf;
1818
1819 }
1820
1821 ULONG VDR::loadTVMedia(TVMediaInfo& tvmedia)
1822 {
1823
1824         VDR_RequestPacket vrp;
1825
1826         if (!vrp.init(VDR_LOADTVMEDIA, false, 0)) return -1;
1827         if (!vrp.addULONG(tvmedia.type)) return -1;
1828         if (!vrp.addULONG(tvmedia.primary_id)) return -1;
1829         if (!vrp.addULONG(tvmedia.secondary_id)) return -1;
1830         if (!vrp.addULONG(tvmedia.type_pict)) return -1;
1831         if (!vrp.addULONG(tvmedia.container)) return -1;
1832         if (!vrp.addULONG(tvmedia.container_member)) return -1;
1833 /*      Log::getInstance()->log("VDR", Log::DEBUG, "TVMedia with ID %d %d; %d %d %d %d;%d",
1834                         tvmedia.primary_id,tvmedia.secondary_id,tvmedia.type,tvmedia.type_pict,
1835                         tvmedia.container,tvmedia.container_member,vrp.getSerial());*/
1836
1837
1838         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1839         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1840         vdrpr->streamID = vrp.getSerial();
1841         vdrpr->streamReceiver = NULL;
1842         edRegister(vdrpr);
1843
1844
1845         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1846         //if (vresp->noResponse()) { delete vresp; return -1; }
1847         delete vresp;
1848
1849         return vrp.getSerial();
1850 }
1851
1852 ULONG VDR::loadTVMediaRecThumb(TVMediaInfo & media)
1853 {
1854
1855         VDR_RequestPacket vrp;
1856
1857         if (!vrp.init(VDR_LOADTVMEDIARECTHUMB, false, 0)) return -1;
1858         if (!vrp.addString(media.primary_name.c_str())) return NULL;
1859
1860         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1861         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1862         vdrpr->streamID = vrp.getSerial();
1863         vdrpr->streamReceiver = NULL;
1864         edRegister(vdrpr);
1865
1866
1867         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1868         //if (vresp->noResponse()) { delete vresp; return -1; }
1869         delete vresp;
1870
1871         return vrp.getSerial();
1872 }
1873
1874 ULONG VDR::loadTVMediaEventThumb(TVMediaInfo & media)
1875 {
1876
1877         VDR_RequestPacket vrp;
1878
1879         if (!vrp.init(VDR_LOADTVMEDIAEVENTTHUMB, false, 0)) return -1;
1880         if (!vrp.addULONG(media.primary_id)) return NULL;
1881         if (!vrp.addULONG(media.secondary_id)) return NULL;
1882
1883         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1884         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1885         vdrpr->streamID = vrp.getSerial();
1886         vdrpr->streamReceiver = NULL;
1887         edRegister(vdrpr);
1888
1889
1890         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1891         //if (vresp->noResponse()) { delete vresp; return -1; }
1892         delete vresp;
1893
1894         return vrp.getSerial();
1895 }
1896
1897 ULONG VDR::loadChannelLogo(TVMediaInfo & media)
1898 {
1899
1900         VDR_RequestPacket vrp;
1901
1902         if (!vrp.init(VDR_LOADCHANNELLOGO, false, 0)) return -1;
1903         if (!vrp.addULONG(media.primary_id)) return NULL;
1904
1905         VDR_PacketReceiver* vdrpr = new VDR_PacketReceiver();
1906         vdrpr->receiverChannel = VDR::CHANNEL_TVMEDIA;
1907         vdrpr->streamID = vrp.getSerial();
1908         vdrpr->streamReceiver = NULL;
1909         edRegister(vdrpr);
1910
1911
1912         VDR_ResponsePacket* vresp = RequestResponse(&vrp);
1913         //if (vresp->noResponse()) { delete vresp; return -1; }
1914         delete vresp;
1915
1916 //      Log::getInstance()->log("VDR", Log::DEBUG, "TVMedia Channel Logo %d %x",
1917 //                              media.primary_id,vrp.getSerial());
1918
1919         return vrp.getSerial();
1920 }