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