cache movie filelengths in .meta file, by luke_s
[enigma2.git] / lib / service / servicedvbrecord.cpp
1 #include <lib/service/servicedvbrecord.h>
2 #include <lib/base/eerror.h>
3 #include <lib/dvb/epgcache.h>
4 #include <fcntl.h>
5
6         /* for cutlist */
7 #include <byteswap.h>
8 #include <netinet/in.h>
9
10 #ifndef BYTE_ORDER
11 #error no byte order defined!
12 #endif
13
14 DEFINE_REF(eDVBServiceRecord);
15
16 eDVBServiceRecord::eDVBServiceRecord(const eServiceReferenceDVB &ref): m_ref(ref)
17 {
18         CONNECT(m_service_handler.serviceEvent, eDVBServiceRecord::serviceEvent);
19         CONNECT(m_event_handler.m_eit_changed, eDVBServiceRecord::gotNewEvent);
20         m_state = stateIdle;
21         m_want_record = 0;
22         m_tuned = 0;
23         m_target_fd = -1;
24         m_error = 0;
25         m_streaming = 0;
26         m_simulate = false;
27         m_last_event_id = -1;
28 }
29
30 void eDVBServiceRecord::serviceEvent(int event)
31 {
32         eDebug("RECORD service event %d", event);
33         switch (event)
34         {
35         case eDVBServicePMTHandler::eventTuned:
36         {
37                 eDebug("tuned..");
38                 m_tuned = 1;
39
40                         /* start feeding EIT updates */
41                 ePtr<iDVBDemux> m_demux;
42                 if (!m_service_handler.getDataDemux(m_demux))
43                 {
44                         eServiceReferenceDVB &ref = (eServiceReferenceDVB&) m_ref;
45                         int sid = ref.getParentServiceID().get();
46                         if (!sid)
47                                 sid = ref.getServiceID().get();
48                         if ( ref.getParentTransportStreamID().get() &&
49                                 ref.getParentTransportStreamID() != ref.getTransportStreamID() )
50                                 m_event_handler.startOther(m_demux, sid);
51                         else
52                                 m_event_handler.start(m_demux, sid);
53                 }
54
55                 if (m_state == stateRecording && m_want_record)
56                         doRecord();
57                 m_event((iRecordableService*)this, evTunedIn);
58                 break;
59         }
60         case eDVBServicePMTHandler::eventTuneFailed:
61         {
62                 eDebug("record failed to tune");
63                 m_event((iRecordableService*)this, evTuneFailed);
64                 break;
65         }
66         case eDVBServicePMTHandler::eventNewProgramInfo:
67         {
68                 if (m_state == stateIdle)
69                         doPrepare();
70                 else if (m_want_record) /* doRecord can be called from Prepared and Recording state */
71                         doRecord();
72                 m_event((iRecordableService*)this, evNewProgramInfo);
73                 break;
74         }
75         case eDVBServicePMTHandler::eventMisconfiguration:
76                 m_error = errMisconfiguration;
77                 m_event((iRecordableService*)this, evTuneFailed);
78                 break;
79         case eDVBServicePMTHandler::eventNoResources:
80                 m_error = errNoResources;
81                 m_event((iRecordableService*)this, evTuneFailed);
82                 break;
83         }
84 }
85
86 RESULT eDVBServiceRecord::prepare(const char *filename, time_t begTime, time_t endTime, int eit_event_id)
87 {
88         m_filename = filename;
89         m_streaming = 0;
90         
91         if (m_state == stateIdle)
92         {
93                 int ret = doPrepare();
94                 if (!ret)
95                 {
96                         eEPGCache::getInstance()->Lock();
97                         const eit_event_struct *event = 0;
98                         eServiceReferenceDVB ref = m_ref.getParentServiceReference();
99                         if (!ref.valid())
100                                 ref = m_ref;
101                         if ( eit_event_id != -1 )
102                         {
103                                 eDebug("query epg event id %d", eit_event_id);
104                                 eEPGCache::getInstance()->lookupEventId(ref, eit_event_id, event);
105                         }
106                         if ( !event && (begTime != -1 && endTime != -1) )
107                         {
108                                 time_t queryTime = begTime + ((endTime-begTime)/2);
109                                 tm beg, end, query;
110                                 localtime_r(&begTime, &beg);
111                                 localtime_r(&endTime, &end);
112                                 localtime_r(&queryTime, &query);
113                                 eDebug("query stime %d:%d:%d, etime %d:%d:%d, qtime %d:%d:%d",
114                                         beg.tm_hour, beg.tm_min, beg.tm_sec,
115                                         end.tm_hour, end.tm_min, end.tm_sec,
116                                         query.tm_hour, query.tm_min, query.tm_sec);
117                                 eEPGCache::getInstance()->lookupEventTime(ref, queryTime, event);
118                         }
119                         if ( event )
120                         {
121                                 eDebug("found event.. store to disc");
122                                 std::string fname = filename;
123                                 fname.erase(fname.length()-2, 2);
124                                 fname+="eit";
125                                 int fd = open(fname.c_str(), O_CREAT|O_WRONLY, 0777);
126                                 if (fd>-1)
127                                 {
128                                         int evLen=HILO(event->descriptors_loop_length)+12/*EIT_LOOP_SIZE*/;
129                                         int wr = ::write( fd, (unsigned char*)event, evLen );
130                                         if ( wr != evLen )
131                                                 eDebug("eit write error (%m)");
132                                         ::close(fd);
133                                 }
134                         }
135                         eEPGCache::getInstance()->Unlock();
136                 }
137                 return ret;
138         }
139         else
140                 return -1;
141 }
142
143 RESULT eDVBServiceRecord::prepareStreaming()
144 {
145         m_filename = "";
146         m_streaming = 1;
147         if (m_state == stateIdle)
148                 return doPrepare();
149         return -1;
150 }
151
152 RESULT eDVBServiceRecord::start(bool simulate)
153 {
154         m_simulate = simulate;
155         m_want_record = 1;
156                 /* when tune wasn't yet successfully, doRecord stays in "prepared"-state which is fine. */
157         m_event((iRecordableService*)this, evStart);
158         return doRecord();
159 }
160
161 RESULT eDVBServiceRecord::stop()
162 {
163         if (!m_simulate)
164                 eDebug("stop recording!");
165         if (m_state == stateRecording)
166         {
167                 if (m_record)
168                         m_record->stop();
169                 if (m_target_fd >= 0)
170                 {
171                         ::close(m_target_fd);
172                         m_target_fd = -1;
173                 }
174                 
175                 saveCutlist();
176                 
177                 m_state = statePrepared;
178         } else if (!m_simulate)
179                 eDebug("(was not recording)");
180         if (m_state == statePrepared)
181         {
182                 m_record = 0;
183                 m_state = stateIdle;
184         }
185         m_event((iRecordableService*)this, evRecordStopped);
186         return 0;
187 }
188
189 int eDVBServiceRecord::doPrepare()
190 {
191                 /* allocate a ts recorder if we don't already have one. */
192         if (m_state == stateIdle)
193         {
194                 m_pids_active.clear();
195                 m_state = statePrepared;
196                 return m_service_handler.tune(m_ref, 0, 0, m_simulate);
197         }
198         return 0;
199 }
200
201 int eDVBServiceRecord::doRecord()
202 {
203         int err = doPrepare();
204         if (err)
205         {
206                 m_error = errTuneFailed;
207                 m_event((iRecordableService*)this, evRecordFailed);
208                 return err;
209         }
210         
211         if (!m_tuned)
212                 return 0; /* try it again when we are tuned in */
213         
214         if (!m_record && m_tuned && !m_streaming && !m_simulate)
215         {
216                 eDebug("Recording to %s...", m_filename.c_str());
217                 ::remove(m_filename.c_str());
218                 int fd = ::open(m_filename.c_str(), O_WRONLY|O_CREAT|O_LARGEFILE, 0644);
219                 if (fd == -1)
220                 {
221                         eDebug("eDVBServiceRecord - can't open recording file!");
222                         m_error = errOpenRecordFile;
223                         m_event((iRecordableService*)this, evRecordFailed);
224                         return errOpenRecordFile;
225                 }
226
227                         /* turn off kernel caching strategies */
228                 posix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM);
229
230                 ePtr<iDVBDemux> demux;
231                 if (m_service_handler.getDataDemux(demux))
232                 {
233                         eDebug("eDVBServiceRecord - NO DEMUX available!");
234                         m_error = errNoDemuxAvailable;
235                         m_event((iRecordableService*)this, evRecordFailed);
236                         return errNoDemuxAvailable;
237                 }
238                 demux->createTSRecorder(m_record);
239                 if (!m_record)
240                 {
241                         eDebug("eDVBServiceRecord - no ts recorder available.");
242                         m_error = errNoTsRecorderAvailable;
243                         m_event((iRecordableService*)this, evRecordFailed);
244                         return errNoTsRecorderAvailable;
245                 }
246                 m_record->setTargetFD(fd);
247                 m_record->setTargetFilename(m_filename.c_str());
248                 m_record->connectEvent(slot(*this, &eDVBServiceRecord::recordEvent), m_con_record_event);
249
250                 m_target_fd = fd;
251         }
252         
253         if (m_streaming)
254         {
255                 m_state = stateRecording;
256                 eDebug("start streaming...");
257         } else
258         {
259                 eDebug("start recording...");
260
261                 eDVBServicePMTHandler::program program;
262                 if (m_service_handler.getProgramInfo(program))
263                         eDebug("getting program info failed.");
264                 else
265                 {
266                         std::set<int> pids_to_record;
267
268                         pids_to_record.insert(0); // PAT
269
270                         if (program.pmtPid != -1)
271                                 pids_to_record.insert(program.pmtPid); // PMT
272
273                         int timing_pid = -1;
274
275                         eDebugNoNewLine("RECORD: have %d video stream(s)", program.videoStreams.size());
276                         if (!program.videoStreams.empty())
277                         {
278                                 eDebugNoNewLine(" (");
279                                 for (std::vector<eDVBServicePMTHandler::videoStream>::const_iterator
280                                         i(program.videoStreams.begin()); 
281                                         i != program.videoStreams.end(); ++i)
282                                 {
283                                         pids_to_record.insert(i->pid);
284                                         
285                                         if (timing_pid == -1)
286                                                 timing_pid = i->pid;
287                                         
288                                         if (i != program.videoStreams.begin())
289                                                         eDebugNoNewLine(", ");
290                                         eDebugNoNewLine("%04x", i->pid);
291                                 }
292                                 eDebugNoNewLine(")");
293                         }
294                         eDebugNoNewLine(", and %d audio stream(s)", program.audioStreams.size());
295                         if (!program.audioStreams.empty())
296                         {
297                                 eDebugNoNewLine(" (");
298                                 for (std::vector<eDVBServicePMTHandler::audioStream>::const_iterator
299                                         i(program.audioStreams.begin()); 
300                                         i != program.audioStreams.end(); ++i)
301                                 {
302                                         pids_to_record.insert(i->pid);
303         
304                                         if (timing_pid == -1)
305                                                 timing_pid = i->pid;
306                                 
307                                         if (i != program.audioStreams.begin())
308                                                 eDebugNoNewLine(", ");
309                                         eDebugNoNewLine("%04x", i->pid);
310                                 }
311                                 eDebugNoNewLine(")");
312                         }
313                         if (!program.subtitleStreams.empty())
314                         {
315                                 eDebugNoNewLine(" (");
316                                 for (std::vector<eDVBServicePMTHandler::subtitleStream>::const_iterator
317                                         i(program.subtitleStreams.begin());
318                                         i != program.subtitleStreams.end(); ++i)
319                                 {
320                                         pids_to_record.insert(i->pid);
321         
322                                         if (i != program.subtitleStreams.begin())
323                                                 eDebugNoNewLine(", ");
324                                         eDebugNoNewLine("%04x", i->pid);
325                                 }
326                                 eDebugNoNewLine(")");
327                         }
328                         eDebugNoNewLine(", and the pcr pid is %04x", program.pcrPid);
329                         if (program.pcrPid != 0x1fff)
330                                 pids_to_record.insert(program.pcrPid);
331                         eDebug(", and the text pid is %04x", program.textPid);
332                         if (program.textPid != -1)
333                                 pids_to_record.insert(program.textPid); // Videotext
334
335                                 /* find out which pids are NEW and which pids are obsolete.. */
336                         std::set<int> new_pids, obsolete_pids;
337
338                         std::set_difference(pids_to_record.begin(), pids_to_record.end(), 
339                                         m_pids_active.begin(), m_pids_active.end(),
340                                         std::inserter(new_pids, new_pids.begin()));
341
342                         std::set_difference(
343                                         m_pids_active.begin(), m_pids_active.end(),
344                                         pids_to_record.begin(), pids_to_record.end(), 
345                                         std::inserter(new_pids, new_pids.begin())
346                                         );
347                         
348                         for (std::set<int>::iterator i(new_pids.begin()); i != new_pids.end(); ++i)
349                         {
350                                 eDebug("ADD PID: %04x", *i);
351                                 m_record->addPID(*i);
352                         }
353
354                         for (std::set<int>::iterator i(obsolete_pids.begin()); i != obsolete_pids.end(); ++i)
355                         {
356                                 eDebug("REMOVED PID: %04x", *i);
357                                 m_record->removePID(*i);
358                         }
359
360                         if (timing_pid != -1)
361                                 m_record->setTimingPID(timing_pid);
362
363                         m_pids_active = pids_to_record;
364
365                         if (m_state != stateRecording)
366                         {
367                                 m_record->start();
368                                 m_state = stateRecording;
369                         }
370                 }
371         }
372         m_error = 0;
373         m_event((iRecordableService*)this, evRecordRunning);
374         return 0;
375 }
376
377 RESULT eDVBServiceRecord::frontendInfo(ePtr<iFrontendInformation> &ptr)
378 {
379         ptr = this;
380         return 0;
381 }
382
383 RESULT eDVBServiceRecord::connectEvent(const Slot2<void,iRecordableService*,int> &event, ePtr<eConnection> &connection)
384 {
385         connection = new eConnection((iRecordableService*)this, m_event.connect(event));
386         return 0;
387 }
388
389 RESULT eDVBServiceRecord::stream(ePtr<iStreamableService> &ptr)
390 {
391         ptr = this;
392         return 0;
393 }
394
395 extern void PutToDict(ePyObject &dict, const char*key, long val);  // defined in dvb/frontend.cpp
396
397 PyObject *eDVBServiceRecord::getStreamingData()
398 {
399         eDVBServicePMTHandler::program program;
400         if (!m_tuned || m_service_handler.getProgramInfo(program))
401         {
402                 Py_RETURN_NONE;
403         }
404
405         ePyObject r = program.createPythonObject();
406         ePtr<iDVBDemux> demux;
407         if (!m_service_handler.getDataDemux(demux))
408         {
409                 uint8_t demux_id;
410                 if (!demux->getCADemuxID(demux_id))
411                         PutToDict(r, "demux", demux_id);
412         }
413
414         return r;
415 }
416
417 void eDVBServiceRecord::recordEvent(int event)
418 {
419         switch (event)
420         {
421         case iDVBTSRecorder::eventWriteError:
422                 eWarning("[eDVBServiceRecord] record write error");
423                 stop();
424                 m_event((iRecordableService*)this, evRecordWriteError);
425                 return;
426         default:
427                 eDebug("unhandled record event %d", event);
428         }
429 }
430
431 void eDVBServiceRecord::gotNewEvent()
432 {
433         ePtr<eServiceEvent> event_now;
434         m_event_handler.getEvent(event_now, 0);
435
436         if (!event_now)
437                 return;
438
439         int event_id = event_now->getEventId();
440
441         pts_t p;
442         
443         if (m_record)
444         {
445                 if (m_record->getCurrentPCR(p))
446                         eDebug("getting PCR failed!");
447                 else
448                 {
449                         static int i;
450                         m_event_timestamps[/* event_id*/ ++i] = p;
451                         eDebug("pcr of eit change: %llx", p);
452                 }
453         }
454
455         if (event_id != m_last_event_id)
456                 eDebug("[eDVBServiceRecord] now running: %s (%d seconds)", event_now->getEventName().c_str(), event_now->getDuration());
457         
458         m_last_event_id = event_id;
459 }
460
461 void eDVBServiceRecord::saveCutlist()
462 {
463                         /* XXX: dupe of eDVBServicePlay::saveCuesheet, refactor plz */
464         std::string filename = m_filename + ".cuts";
465
466         eDVBTSTools tstools;
467         
468         if (tstools.openFile(m_filename.c_str()))
469         {
470                 eDebug("[eDVBServiceRecord] saving cutlist failed because tstools failed");
471                 return;
472         }
473         
474         FILE *f = fopen(filename.c_str(), "wb");
475
476         if (f)
477         {
478                 unsigned long long where;
479                 int what;
480
481                 for (std::map<int,pts_t>::iterator i(m_event_timestamps.begin()); i != m_event_timestamps.end(); ++i)
482                 {
483                         pts_t p = i->second;
484                         off_t offset = 0; // fixme, we need to note down both
485                         if (tstools.fixupPTS(offset, p))
486                         {
487                                 eDebug("[eDVBServiceRecord] fixing up PTS failed, not saving");
488                                 continue;
489                         }
490                         eDebug("fixed up %llx to %llx (offset %llx)", i->second, p, offset);
491 #if BYTE_ORDER == BIG_ENDIAN
492                         where = p;
493 #else
494                         where = bswap_64(p);
495 #endif
496                         what = htonl(2); /* mark */
497                         fwrite(&where, sizeof(where), 1, f);
498                         fwrite(&what, sizeof(what), 1, f);
499                 }
500                 fclose(f);
501         }
502         
503 }