Revert "mediaplayer: allow playback of flv files"
[enigma2.git] / lib / dvb / pvrparse.cpp
1 #include <lib/dvb/pvrparse.h>
2 #include <lib/base/eerror.h>
3 #include <byteswap.h>
4
5 #ifndef BYTE_ORDER
6 #error no byte order defined!
7 #endif
8
9 eMPEGStreamInformation::eMPEGStreamInformation()
10         : m_structure_cache_valid(0), m_structure_read(0), m_structure_write(0)
11 {
12 }
13
14 eMPEGStreamInformation::~eMPEGStreamInformation()
15 {
16         if (m_structure_read)
17                 fclose(m_structure_read);
18         if (m_structure_write)
19                 fclose(m_structure_write);
20 }
21
22 int eMPEGStreamInformation::startSave(const char *filename)
23 {
24         m_filename = filename;
25         m_structure_write = fopen((m_filename + ".sc").c_str(), "wb");
26         return 0;
27 }
28
29 int eMPEGStreamInformation::stopSave(void)
30 {
31         if (m_structure_write)
32         {
33                 fclose(m_structure_write);
34                 m_structure_write = 0;
35         }
36         if (m_filename == "")
37                 return -1;
38         FILE *f = fopen((m_filename + ".ap").c_str(), "wb");
39         if (!f)
40                 return -1;
41         
42         for (std::map<off_t, pts_t>::const_iterator i(m_access_points.begin()); i != m_access_points.end(); ++i)
43         {
44                 unsigned long long d[2];
45 #if BYTE_ORDER == BIG_ENDIAN
46                 d[0] = i->first;
47                 d[1] = i->second;
48 #else
49                 d[0] = bswap_64(i->first);
50                 d[1] = bswap_64(i->second);
51 #endif
52                 fwrite(d, sizeof(d), 1, f);
53         }
54         fclose(f);
55         
56         return 0;
57 }
58
59 int eMPEGStreamInformation::load(const char *filename)
60 {
61         m_filename = filename;
62         if (m_structure_read)
63                 fclose(m_structure_read);
64         m_structure_read = fopen((std::string(m_filename) + ".sc").c_str(), "rb");
65         FILE *f = fopen((std::string(m_filename) + ".ap").c_str(), "rb");
66         if (!f)
67                 return -1;
68         m_access_points.clear();
69         m_pts_to_offset.clear();
70         while (1)
71         {
72                 unsigned long long d[2];
73                 if (fread(d, sizeof(d), 1, f) < 1)
74                         break;
75                 
76 #if BYTE_ORDER == LITTLE_ENDIAN
77                 d[0] = bswap_64(d[0]);
78                 d[1] = bswap_64(d[1]);
79 #endif
80                 m_access_points[d[0]] = d[1];
81                 m_pts_to_offset.insert(std::pair<pts_t,off_t>(d[1], d[0]));
82         }
83         fclose(f);
84         fixupDiscontinuties();
85         return 0;
86 }
87
88 bool eMPEGStreamInformation::empty()
89 {
90         return m_access_points.empty();
91 }
92
93 void eMPEGStreamInformation::fixupDiscontinuties()
94 {
95         m_timestamp_deltas.clear();
96         if (!m_access_points.size())
97                 return;
98                 
99 //      eDebug("Fixing discontinuities ...");
100
101                         /* if we have no delta at the beginning, extrapolate it */
102         if ((m_access_points.find(0) == m_access_points.end()) && (m_access_points.size() > 1))
103         {
104                 std::map<off_t,pts_t>::const_iterator second = m_access_points.begin();
105                 std::map<off_t,pts_t>::const_iterator first  = second++;
106                 if (first->first < second->first) /* i.e., not equal or broken */
107                 {
108                         off_t diff = second->first - first->first;
109                         pts_t tdiff = second->second - first->second;
110                         tdiff *= first->first;
111                         tdiff /= diff;
112                         m_timestamp_deltas[0] = first->second - tdiff;
113 //                      eDebug("first delta is %08llx", first->second - tdiff);
114                 }
115         }
116
117         if (m_timestamp_deltas.empty())
118                 m_timestamp_deltas[m_access_points.begin()->first] = m_access_points.begin()->second;
119
120         pts_t currentDelta = m_timestamp_deltas.begin()->second, lastpts_t = 0;
121         for (std::map<off_t,pts_t>::const_iterator i(m_access_points.begin()); i != m_access_points.end(); ++i)
122         {
123                 pts_t current = i->second - currentDelta;
124                 pts_t diff = current - lastpts_t;
125                 
126                 if (llabs(diff) > (90000*5)) // 5sec diff
127                 {
128 //                      eDebug("%llx < %llx, have discont. new timestamp is %llx (diff is %llx)!", current, lastpts_t, i->second, diff);
129                         currentDelta = i->second - lastpts_t; /* FIXME: should be the extrapolated new timestamp, based on the current rate */
130 //                      eDebug("current delta now %llx, making current to %llx", currentDelta, i->second - currentDelta);
131                         m_timestamp_deltas[i->first] = currentDelta;
132                 }
133                 lastpts_t = i->second - currentDelta;
134         }
135         
136         
137 //      eDebug("ok, found %d disconts.", m_timestamp_deltas.size());
138
139 #if 0   
140         for (off_t x=0x25807E34ULL; x < 0x25B3CF70; x+= 100000)
141         {
142                 off_t o = x;
143                 pts_t p;
144                 int r = getPTS(o, p);
145                 eDebug("%08llx -> %08llx | %08llx, %d, %08llx %08llx", x, getDelta(x), getInterpolated(x), r, o, p);
146         }
147 #endif
148 }
149
150 pts_t eMPEGStreamInformation::getDelta(off_t offset)
151 {
152         if (!m_timestamp_deltas.size())
153                 return 0;
154         std::map<off_t,pts_t>::iterator i = m_timestamp_deltas.upper_bound(offset);
155
156                 /* i can be the first when you query for something before the first PTS */
157         if (i != m_timestamp_deltas.begin())
158                 --i;
159
160         return i->second;
161 }
162
163 int eMPEGStreamInformation::fixupPTS(const off_t &offset, pts_t &ts)
164 {
165         if (!m_timestamp_deltas.size())
166                 return -1;
167
168         std::multimap<pts_t, off_t>::const_iterator 
169                 l = m_pts_to_offset.upper_bound(ts - 60 * 90000), 
170                 u = m_pts_to_offset.upper_bound(ts + 60 * 90000), 
171                 nearest = m_pts_to_offset.end();
172
173         while (l != u)
174         {
175                 if ((nearest == m_pts_to_offset.end()) || (llabs(l->first - ts) < llabs(nearest->first - ts)))
176                         nearest = l;
177                 ++l;
178         }
179         if (nearest == m_pts_to_offset.end())
180                 return 1;
181
182         ts -= getDelta(nearest->second);
183
184         return 0;
185 }
186
187 int eMPEGStreamInformation::getPTS(off_t &offset, pts_t &pts)
188 {
189         std::map<off_t,pts_t>::iterator before = m_access_points.lower_bound(offset);
190
191                 /* usually, we prefer the AP before the given offset. however if there is none, we take any. */
192         if (before != m_access_points.begin())
193                 --before;
194         
195         if (before == m_access_points.end())
196         {
197                 pts = 0;
198                 return -1;
199         }
200         
201         offset = before->first;
202         pts = before->second - getDelta(offset);
203         
204         return 0;
205 }
206
207 pts_t eMPEGStreamInformation::getInterpolated(off_t offset)
208 {
209                 /* get the PTS values before and after the offset. */
210         std::map<off_t,pts_t>::iterator before, after;
211         after = m_access_points.upper_bound(offset);
212         before = after;
213
214         if (before != m_access_points.begin())
215                 --before;
216         else    /* we query before the first known timestamp ... FIXME */
217                 return 0;
218
219                 /* empty... */
220         if (before == m_access_points.end())
221                 return 0;
222
223                 /* if after == end, then we need to extrapolate ... FIXME */
224         if ((before->first == offset) || (after == m_access_points.end()))
225                 return before->second - getDelta(offset);
226         
227         pts_t before_ts = before->second - getDelta(before->first);
228         pts_t after_ts = after->second - getDelta(after->first);
229         
230 //      eDebug("%08llx .. ? .. %08llx", before_ts, after_ts);
231 //      eDebug("%08llx .. %08llx .. %08llx", before->first, offset, after->first);
232         
233         pts_t diff = after_ts - before_ts;
234         off_t diff_off = after->first - before->first;
235         
236         diff = (offset - before->first) * diff / diff_off;
237 //      eDebug("%08llx .. %08llx .. %08llx", before_ts, before_ts + diff, after_ts);
238         return before_ts + diff;
239 }
240  
241 off_t eMPEGStreamInformation::getAccessPoint(pts_t ts, int marg)
242 {
243                 /* FIXME: more efficient implementation */
244         off_t last = 0;
245         off_t last2 = 0;
246         pts_t lastc = 0;
247         for (std::map<off_t, pts_t>::const_iterator i(m_access_points.begin()); i != m_access_points.end(); ++i)
248         {
249                 pts_t delta = getDelta(i->first);
250                 pts_t c = i->second - delta;
251                 if (c > ts) {
252                         if (marg > 0)
253                                 return (last + i->first)/376*188;
254                         else if (marg < 0)
255                                 return (last + last2)/376*188;
256                         else
257                                 return last;
258                 }
259                 lastc = c;
260                 last2 = last;
261                 last = i->first;
262         }
263         if (marg < 0)
264                 return (last + last2)/376*188;
265         else
266                 return last;
267 }
268
269 int eMPEGStreamInformation::getNextAccessPoint(pts_t &ts, const pts_t &start, int direction)
270 {
271         off_t offset = getAccessPoint(start);
272         pts_t c1, c2;
273         std::map<off_t, pts_t>::const_iterator i = m_access_points.find(offset);
274         if (i == m_access_points.end())
275         {
276                 eDebug("getNextAccessPoint: initial AP not found");
277                 return -1;
278         }
279         c1 = i->second - getDelta(i->first);
280         while (direction)
281         {
282                 if (direction > 0)
283                 {
284                         if (i == m_access_points.end())
285                                 return -1;
286                         ++i;
287                         c2 = i->second - getDelta(i->first);
288                         if (c1 == c2) { // Discontinuity
289                                 ++i;
290                                 c2 = i->second - getDelta(i->first);
291                         }
292                         c1 = c2;
293                         direction--;
294                 }
295                 if (direction < 0)
296                 {
297                         if (i == m_access_points.begin())
298                         {
299                                 eDebug("at start");
300                                 return -1;
301                         }
302                         --i;
303                         c2 = i->second - getDelta(i->first);
304                         if (c1 == c2) { // Discontinuity
305                                 --i;
306                                 c2 = i->second - getDelta(i->first);
307                         }
308                         c1 = c2;
309                         direction++;
310                 }
311         }
312         ts = i->second - getDelta(i->first);
313         eDebug("fine, at %llx - %llx = %llx", ts, i->second, getDelta(i->first));
314         eDebug("fine, at %lld - %lld = %lld", ts, i->second, getDelta(i->first));
315         return 0;
316 }
317
318 void eMPEGStreamInformation::writeStructureEntry(off_t offset, structure_data data)
319 {
320         unsigned long long d[2];
321 #if BYTE_ORDER == BIG_ENDIAN
322         d[0] = offset;
323         d[1] = data;
324 #else
325         d[0] = bswap_64(offset);
326         d[1] = bswap_64(data);
327 #endif
328         if (m_structure_write)
329                 fwrite(d, sizeof(d), 1, m_structure_write);
330 }
331
332 int eMPEGStreamInformation::getStructureEntry(off_t &offset, unsigned long long &data, int get_next)
333 {
334         if (!m_structure_read)
335         {
336                 eDebug("getStructureEntry failed because of no m_structure_read");
337                 return -1;
338         }
339
340         const int struture_cache_entries = sizeof(m_structure_cache) / 16;
341         if ((!m_structure_cache_valid) || ((off_t)m_structure_cache[0] > offset) || ((off_t)m_structure_cache[(struture_cache_entries - (get_next ? 2 : 1)) * 2] <= offset))
342         {
343                 fseek(m_structure_read, 0, SEEK_END);
344                 int l = ftell(m_structure_read);
345                 unsigned long long d[2];
346                 const int entry_size = sizeof d;
347
348                         /* do a binary search */
349                 int count = l / entry_size;
350                 int i = 0;
351                 
352                 while (count)
353                 {
354                         int step = count >> 1;
355                         
356                         fseek(m_structure_read, (i + step) * entry_size, SEEK_SET);
357                         if (!fread(d, 1, entry_size, m_structure_read))
358                         {
359                                 eDebug("read error at entry %d", i);
360                                 return -1;
361                         }
362                         
363 #if BYTE_ORDER != BIG_ENDIAN
364                         d[0] = bswap_64(d[0]);
365                         d[1] = bswap_64(d[1]);
366 #endif
367 //                      eDebug("%d: %08llx > %llx", i, d[0], d[1]);
368                         
369                         if (d[0] < (unsigned long long)offset)
370                         {
371                                 i += step + 1;
372                                 count -= step + 1;
373                         } else
374                                 count = step;
375                 }
376                 
377                 eDebug("found %d", i);
378                 
379                         /* put that in the middle */
380                 i -= struture_cache_entries / 2;
381                 if (i < 0)
382                         i = 0;
383                 eDebug("cache starts at %d", i);
384                 fseek(m_structure_read, i * entry_size, SEEK_SET);
385                 int num = fread(m_structure_cache, entry_size, struture_cache_entries, m_structure_read);
386                 eDebug("%d entries", num);
387                 for (i = 0; i < struture_cache_entries; ++i)
388                 {
389                         if (i < num)
390                         {
391 #if BYTE_ORDER != BIG_ENDIAN
392                                 m_structure_cache[i * 2] = bswap_64(m_structure_cache[i * 2]);
393                                 m_structure_cache[i * 2 + 1] = bswap_64(m_structure_cache[i * 2 + 1]);
394 #endif
395                         } else
396                         {
397                                 m_structure_cache[i * 2] = 0x7fffffffffffffffULL; /* fill with harmless content */
398                                 m_structure_cache[i * 2 + 1] = 0;
399                         }
400                 }
401                 m_structure_cache_valid = 1;
402         }
403         
404         int i = 0;
405         while ((off_t)m_structure_cache[i * 2] <= offset)
406         {
407                 ++i;
408                 if (i == struture_cache_entries)
409                 {
410                         eDebug("structure data consistency fail!, we are looking for %llx, but last entry is %llx", offset, m_structure_cache[i*2-2]);
411                         return -1;
412                 }
413         }
414         if (!i)
415         {
416                 eDebug("structure data (first entry) consistency fail!");
417                 return -1;
418         }
419         
420         if (!get_next)
421                 --i;
422
423 //      eDebug("[%d] looked for %llx, found %llx=%llx", sizeof offset, offset, m_structure_cache[i * 2], m_structure_cache[i * 2 + 1]);
424         offset = m_structure_cache[i * 2];
425         data = m_structure_cache[i * 2 + 1];
426         return 0;
427 }
428
429 eMPEGStreamParserTS::eMPEGStreamParserTS(eMPEGStreamInformation &streaminfo): m_streaminfo(streaminfo), m_pktptr(0), m_pid(-1), m_need_next_packet(0), m_skip(0), m_last_pts_valid(0)
430 {
431 }
432
433 int eMPEGStreamParserTS::processPacket(const unsigned char *pkt, off_t offset)
434 {
435         if (!wantPacket(pkt))
436                 eWarning("something's wrong.");
437
438         const unsigned char *end = pkt + 188, *begin = pkt;
439         
440         int pusi = !!(pkt[1] & 0x40);
441         
442         if (!(pkt[3] & 0x10)) /* no payload? */
443                 return 0;
444
445         if (pkt[3] & 0x20) // adaptation field present?
446                 pkt += pkt[4] + 4 + 1;  /* skip adaptation field and header */
447         else
448                 pkt += 4; /* skip header */
449
450         if (pkt > end)
451         {
452                 eWarning("[TSPARSE] dropping huge adaption field");
453                 return 0;
454         }
455
456         pts_t pts = 0;
457         int ptsvalid = 0;
458         
459         if (pusi)
460         {
461                         // ok, we now have the start of the payload, aligned with the PES packet start.
462                 if (pkt[0] || pkt[1] || (pkt[2] != 1))
463                 {
464                         eWarning("broken startcode");
465                         return 0;
466                 }
467
468                 if (pkt[7] & 0x80) // PTS present?
469                 {
470                         pts  = ((unsigned long long)(pkt[ 9]&0xE))  << 29;
471                         pts |= ((unsigned long long)(pkt[10]&0xFF)) << 22;
472                         pts |= ((unsigned long long)(pkt[11]&0xFE)) << 14;
473                         pts |= ((unsigned long long)(pkt[12]&0xFF)) << 7;
474                         pts |= ((unsigned long long)(pkt[13]&0xFE)) >> 1;
475                         ptsvalid = 1;
476                         
477                         m_last_pts = pts;
478                         m_last_pts_valid = 1;
479
480         #if 0           
481                         int sec = pts / 90000;
482                         int frm = pts % 90000;
483                         int min = sec / 60;
484                         sec %= 60;
485                         int hr = min / 60;
486                         min %= 60;
487                         int d = hr / 24;
488                         hr %= 24;
489                         
490                         eDebug("pts: %016llx %d:%02d:%02d:%02d:%05d", pts, d, hr, min, sec, frm);
491         #endif
492                 }
493                 
494                         /* advance to payload */
495                 pkt += pkt[8] + 9;
496         }
497
498         while (pkt < (end-4))
499         {
500                 int pkt_offset = pkt - begin;
501                 if (!(pkt[0] || pkt[1] || (pkt[2] != 1)))
502                 {
503 //                      eDebug("SC %02x %02x %02x %02x, %02x", pkt[0], pkt[1], pkt[2], pkt[3], pkt[4]);
504                         int sc = pkt[3];
505                         
506                         if (m_streamtype == 0) /* mpeg2 */
507                         {
508                                 if ((sc == 0x00) || (sc == 0xb3) || (sc == 0xb8)) /* picture, sequence, group start code */
509                                 {
510                                         unsigned long long data = sc | (pkt[4] << 8) | (pkt[5] << 16) | (pkt[6] << 24);
511                                         m_streaminfo.writeStructureEntry(offset + pkt_offset, data  & 0xFFFFFFFFULL);
512                                 }
513                                 if (pkt[3] == 0xb3) /* sequence header */
514                                 {
515                                         if (ptsvalid)
516                                         {
517                                                 m_streaminfo.m_access_points[offset] = pts;
518         //                                      eDebug("Sequence header at %llx, pts %llx", offset, pts);
519                                         } else
520                                                 /*eDebug("Sequence header but no valid PTS value.")*/;
521                                 }
522                         }
523
524                         if (m_streamtype == 1) /* H.264 */
525                         {
526                                 if (sc == 0x09)
527                                 {
528                                                 /* store image type */
529                                         unsigned long long data = sc | (pkt[4] << 8);
530                                         m_streaminfo.writeStructureEntry(offset + pkt_offset, data);
531                                 }
532                                 if (pkt[3] == 0x09 &&   /* MPEG4 AVC NAL unit access delimiter */
533                                          (pkt[4] >> 5) == 0) /* and I-frame */
534                                 {
535                                         if (ptsvalid)
536                                         {
537                                                 m_streaminfo.m_access_points[offset] = pts;
538         //                              eDebug("MPEG4 AVC UAD at %llx, pts %llx", offset, pts);
539                                         } else
540                                                 /*eDebug("MPEG4 AVC UAD but no valid PTS value.")*/;
541                                 }
542                         }
543                 }
544                 ++pkt;
545         }
546         return 0;
547 }
548
549 inline int eMPEGStreamParserTS::wantPacket(const unsigned char *hdr) const
550 {
551         if (hdr[0] != 0x47)
552         {
553                 eDebug("missing sync!");
554                 return 0;
555         }
556         int ppid = ((hdr[1]&0x1F) << 8) | hdr[2];
557
558         if (ppid != m_pid)
559                 return 0;
560                 
561         if (m_need_next_packet)  /* next packet (on this pid) was required? */
562                 return 1;
563         
564         if (hdr[1] & 0x40)       /* pusi set: yes. */
565                 return 1;
566
567         return m_streamtype == 0; /* we need all packets for MPEG2, but only PUSI packets for H.264 */
568 }
569
570 void eMPEGStreamParserTS::parseData(off_t offset, const void *data, unsigned int len)
571 {
572         const unsigned char *packet = (const unsigned char*)data;
573         const unsigned char *packet_start = packet;
574         
575                         /* sorry for the redundant code here, but there are too many special cases... */
576         while (len)
577         {
578                         /* emergency resync. usually, this should not happen, because the data should 
579                            be sync-aligned.
580                            
581                            to make this code work for non-strictly-sync-aligned data, (for example, bad 
582                            files) we fix a possible resync here by skipping data until the next 0x47.
583                            
584                            if this is a false 0x47, the packet will be dropped by wantPacket, and the
585                            next time, sync will be re-established. */
586                 int skipped = 0;
587                 while (!m_pktptr && len)
588                 {
589                         if (packet[0] == 0x47)
590                                 break;
591                         len--;
592                         packet++;
593                         skipped++;
594                 }
595                 
596                 if (skipped)
597                         eDebug("SYNC LOST: skipped %d bytes.", skipped);
598                 
599                 if (!len)
600                         break;
601                 
602                 if (m_pktptr)
603                 {
604                                 /* skip last packet */
605                         if (m_pktptr < 0)
606                         {
607                                 unsigned int skiplen = -m_pktptr;
608                                 if (skiplen > len)
609                                         skiplen = len;
610                                 packet += skiplen;
611                                 len -= skiplen;
612                                 m_pktptr += skiplen;
613                                 continue;
614                         } else if (m_pktptr < 4) /* header not complete, thus we don't know if we want this packet */
615                         {
616                                 unsigned int storelen = 4 - m_pktptr;
617                                 if (storelen > len)
618                                         storelen = len;
619                                 memcpy(m_pkt + m_pktptr, packet,  storelen);
620                                 
621                                 m_pktptr += storelen;
622                                 len -= storelen;
623                                 packet += storelen;
624                                 
625                                 if (m_pktptr == 4)
626                                         if (!wantPacket(m_pkt))
627                                         {
628                                                         /* skip packet */
629                                                 packet += 184;
630                                                 len -= 184;
631                                                 m_pktptr = 0;
632                                                 continue;
633                                         }
634                         }
635                                 /* otherwise we complete up to the full packet */
636                         unsigned int storelen = 188 - m_pktptr;
637                         if (storelen > len)
638                                 storelen = len;
639                         memcpy(m_pkt + m_pktptr, packet,  storelen);
640                         m_pktptr += storelen;
641                         len -= storelen;
642                         packet += storelen;
643                         
644                         if (m_pktptr == 188)
645                         {
646                                 m_need_next_packet = processPacket(m_pkt, offset + (packet - packet_start));
647                                 m_pktptr = 0;
648                         }
649                 } else if (len >= 4)  /* if we have a full header... */
650                 {
651                         if (wantPacket(packet))  /* decide wheter we need it ... */
652                         {
653                                 if (len >= 188)          /* packet complete? */
654                                 {
655                                         m_need_next_packet = processPacket(packet, offset + (packet - packet_start)); /* process it now. */
656                                 } else
657                                 {
658                                         memcpy(m_pkt, packet, len);  /* otherwise queue it up */
659                                         m_pktptr = len;
660                                 }
661                         }
662
663                                 /* skip packet */
664                         int sk = len;
665                         if (sk >= 188)
666                                 sk = 188;
667                         else if (!m_pktptr) /* we dont want this packet, otherwise m_pktptr = sk (=len) > 4 */
668                                 m_pktptr = sk - 188;
669
670                         len -= sk;
671                         packet += sk;
672                 } else             /* if we don't have a complete header */
673                 {
674                         memcpy(m_pkt, packet, len);   /* complete header next time */
675                         m_pktptr = len;
676                         packet += len;
677                         len = 0;
678                 }
679         }
680 }
681
682 void eMPEGStreamParserTS::setPid(int _pid, int type)
683 {
684         m_pktptr = 0;
685         m_pid = _pid;
686         m_streamtype = type;
687 }
688
689 int eMPEGStreamParserTS::getLastPTS(pts_t &last_pts)
690 {
691         if (!m_last_pts_valid)
692         {
693                 last_pts = 0;
694                 return -1;
695         }
696         last_pts = m_last_pts;
697         return 0;
698 }
699