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