5b7e790e98532f5437ffc51eb8b7a6ae4e1d3851
[vuplus_dvbapp] / 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_entries(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
37         if (m_access_points.empty())
38                 return 0;
39
40         if (m_filename == "")
41                 return -1;
42         FILE *f = fopen((m_filename + ".ap").c_str(), "wb");
43         if (!f)
44                 return -1;
45         
46         for (std::map<off_t, pts_t>::const_iterator i(m_access_points.begin()); i != m_access_points.end(); ++i)
47         {
48                 unsigned long long d[2];
49 #if BYTE_ORDER == BIG_ENDIAN
50                 d[0] = i->first;
51                 d[1] = i->second;
52 #else
53                 d[0] = bswap_64(i->first);
54                 d[1] = bswap_64(i->second);
55 #endif
56                 fwrite(d, sizeof(d), 1, f);
57         }
58         fclose(f);
59         
60         return 0;
61 }
62
63 int eMPEGStreamInformation::load(const char *filename)
64 {
65         m_filename = filename;
66         if (m_structure_read)
67                 fclose(m_structure_read);
68         m_structure_read = fopen((std::string(m_filename) + ".sc").c_str(), "rb");
69         m_access_points.clear();
70         m_pts_to_offset.clear();
71         m_timestamp_deltas.clear();
72         FILE *f = fopen((std::string(m_filename) + ".ap").c_str(), "rb");
73         if (!f)
74                 return -1;
75         while (1)
76         {
77                 unsigned long long d[2];
78                 if (fread(d, sizeof(d), 1, f) < 1)
79                         break;
80                 
81 #if BYTE_ORDER == LITTLE_ENDIAN
82                 d[0] = bswap_64(d[0]);
83                 d[1] = bswap_64(d[1]);
84 #endif
85                 m_access_points[d[0]] = d[1];
86                 m_pts_to_offset.insert(std::pair<pts_t,off_t>(d[1], d[0]));
87         }
88         fclose(f);
89         fixupDiscontinuties();
90         return 0;
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*10)) // 10sec 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         ts += 1; // Add rounding error margin
248         for (std::map<off_t, pts_t>::const_iterator i(m_access_points.begin()); i != m_access_points.end(); ++i)
249         {
250                 pts_t delta = getDelta(i->first);
251                 pts_t c = i->second - delta;
252                 if (c > ts) {
253                         if (marg > 0)
254                                 return (last + i->first)/376*188;
255                         else if (marg < 0)
256                                 return (last + last2)/376*188;
257                         else
258                                 return last;
259                 }
260                 lastc = c;
261                 last2 = last;
262                 last = i->first;
263         }
264         if (marg < 0)
265                 return (last + last2)/376*188;
266         else
267                 return last;
268 }
269
270 int eMPEGStreamInformation::getNextAccessPoint(pts_t &ts, const pts_t &start, int direction)
271 {
272         off_t offset = getAccessPoint(start);
273         pts_t c1, c2;
274         std::map<off_t, pts_t>::const_iterator i = m_access_points.find(offset);
275         if (i == m_access_points.end())
276         {
277                 eDebug("getNextAccessPoint: initial AP not found");
278                 return -1;
279         }
280         c1 = i->second - getDelta(i->first);
281         while (direction)
282         {
283                 if (direction > 0)
284                 {
285                         if (i == m_access_points.end())
286                                 return -1;
287                         ++i;
288                         c2 = i->second - getDelta(i->first);
289                         if (c1 == c2) { // Discontinuity
290                                 ++i;
291                                 c2 = i->second - getDelta(i->first);
292                         }
293                         c1 = c2;
294                         direction--;
295                 }
296                 if (direction < 0)
297                 {
298                         if (i == m_access_points.begin())
299                         {
300                                 eDebug("at start");
301                                 return -1;
302                         }
303                         --i;
304                         c2 = i->second - getDelta(i->first);
305                         if (c1 == c2) { // Discontinuity
306                                 --i;
307                                 c2 = i->second - getDelta(i->first);
308                         }
309                         c1 = c2;
310                         direction++;
311                 }
312         }
313         ts = i->second - getDelta(i->first);
314         eDebug("fine, at %llx - %llx = %llx", ts, i->second, getDelta(i->first));
315         eDebug("fine, at %lld - %lld = %lld", ts, i->second, getDelta(i->first));
316         return 0;
317 }
318
319 void eMPEGStreamInformation::writeStructureEntry(off_t offset, structure_data data)
320 {
321         unsigned long long d[2];
322 #if BYTE_ORDER == BIG_ENDIAN
323         d[0] = offset;
324         d[1] = data;
325 #else
326         d[0] = bswap_64(offset);
327         d[1] = bswap_64(data);
328 #endif
329         if (m_structure_write)
330                 fwrite(d, sizeof(d), 1, m_structure_write);
331 }
332
333 int eMPEGStreamInformation::getStructureEntry(off_t &offset, unsigned long long &data, int get_next)
334 {
335         if (!m_structure_read)
336         {
337                 eDebug("getStructureEntry failed because of no m_structure_read");
338                 return -1;
339         }
340
341         off_t _offset = offset;
342         const int struture_cache_size = sizeof(m_structure_cache) / 16;
343         if ((m_structure_cache_entries == 0) || ((off_t)m_structure_cache[0] > offset) || ((off_t)m_structure_cache[(m_structure_cache_entries - (get_next ? 2 : 1)) * 2] <= offset))
344         {
345                 if(update_structure_cache_entries(_offset))
346                 {
347                         return -1;
348                 }
349         }
350         
351         int i = 0;
352         while ((off_t)m_structure_cache[i * 2] <= offset)
353         {
354                 ++i;
355                 if (i == m_structure_cache_entries)
356                 {
357                         eDebug("structure data consistency fail!, we are looking for %llx, but last entry is %llx", offset, m_structure_cache[i*2-2]);
358                         return -1;
359                 }
360         }
361         if (!i)
362         {
363                 eDebug("structure data (first entry) consistency fail!");
364                 return -1;
365         }
366         
367         if (!get_next)
368                 --i;
369
370 //      eDebug("[%d] looked for %lld, found %llu=%llx", sizeof offset, offset, m_structure_cache[i * 2], m_structure_cache[i * 2 + 1]);
371         offset = m_structure_cache[i * 2];
372         data = m_structure_cache[i * 2 + 1];
373         return 0;
374 }
375
376 int eMPEGStreamInformation::getStructureEntry_next(off_t &offset, unsigned long long &data)
377 {
378         if (!m_structure_read)
379         {
380                 eDebug("getStructureEntry failed because of no m_structure_read");
381                 return -1;
382         }
383
384         off_t _offset = offset;
385         if ((m_structure_cache_entries == 0) || ((off_t)m_structure_cache[0] > offset) || ((off_t)m_structure_cache[(m_structure_cache_entries - 1)*2] <= offset))
386         {
387                 if(update_structure_cache_entries(_offset))
388                 {
389                         return -1;
390                 }
391         }
392
393         int i = 0;
394         while ((off_t)m_structure_cache[i * 2] <= offset)
395         {
396                 ++i;
397                 if (i == m_structure_cache_entries)
398                 {
399                         eDebug("structure data consistency fail!, we are looking for %llu, but last entry is %llu", offset, m_structure_cache[(m_structure_cache_entries-1)*2]);
400                         return -1;
401                 }
402         }
403         if (!i)
404         {
405                 eDebug("structure data (first entry) consistency fail!");
406                 return -1;
407         }
408
409 //      eDebug("[%d] looked for %llu, found data %llu=%llx",sizeof offset, offset, m_structure_cache[i * 2], m_structure_cache[i * 2 + 1]);
410         offset = m_structure_cache[i * 2];
411         data = m_structure_cache[i * 2 + 1];
412         return 0;
413 }
414
415 int eMPEGStreamInformation::getStructureEntry_prev(off_t &offset, unsigned long long &data)
416 {
417         if (!m_structure_read)
418         {
419                 eDebug("getStructureEntry failed because of no m_structure_read");
420                 return -1;
421         }
422
423         off_t _offset = offset;
424         if ((m_structure_cache_entries == 0) || ((off_t)m_structure_cache[0] >= offset) || ((off_t)m_structure_cache[(m_structure_cache_entries - 1)*2] < offset))
425         {
426                 if(update_structure_cache_entries(_offset))
427                 {
428                         return -1;
429                 }
430         }
431
432         int i = m_structure_cache_entries-1;
433         while ((off_t)m_structure_cache[i * 2] >= offset)
434         {
435                 if (i <= 0)
436                 {
437                         eDebug("structure data consistency fail!, we are looking for %llu, but last entry is %llu", offset, m_structure_cache[i * 2]);
438                         return -1;
439                 }
440                 --i;
441         }
442         if (i == m_structure_cache_entries-1)
443         {
444                 eDebug("structure data (first entry) consistency fail!");
445                 return -1;
446         }
447
448 //      eDebug("[%d] looked for %llu, found data %llu=%llx",sizeof offset, offset, m_structure_cache[i * 2], m_structure_cache[i * 2 + 1]);
449         offset = m_structure_cache[i * 2];
450         data = m_structure_cache[i * 2 + 1];
451         return 0;
452 }
453
454 int eMPEGStreamInformation::update_structure_cache_entries(off_t offset)
455 {
456         const int struture_cache_size = sizeof(m_structure_cache) / 16;
457         fseek(m_structure_read, 0, SEEK_END);
458         int l = ftell(m_structure_read);
459         unsigned long long d[2];
460         const int entry_size = sizeof d;
461
462                 /* do a binary search */
463         int count = l / entry_size;
464         int i = 0;
465
466         while (count)
467         {
468                 int step = count >> 1;
469                 fseek(m_structure_read, (i + step) * entry_size, SEEK_SET);
470                 if (!fread(d, 1, entry_size, m_structure_read))
471                 {
472                         eDebug("read error at entry %d", i);
473                         return -1;
474                 }
475 #if BYTE_ORDER != BIG_ENDIAN
476                 d[0] = bswap_64(d[0]);
477                 d[1] = bswap_64(d[1]);
478 #endif
479 //              eDebug("%d: %08llx > %llx", i, d[0], d[1]);
480                 if (d[0] < (unsigned long long)offset)
481                 {
482                         i += step + 1;
483                         count -= step + 1;
484                 } else
485                         count = step;
486         }
487         eDebug("found %d", i);
488
489         /* put that in the middle */
490         i -= struture_cache_size / 2;
491         if (i < 0)
492                 i = 0;
493         eDebug("cache starts at %d", i);
494         fseek(m_structure_read, i * entry_size, SEEK_SET);
495         int num = fread(m_structure_cache, entry_size, struture_cache_size, m_structure_read);
496         eDebug("%d entries", num);
497         for (i = 0; i < struture_cache_size; ++i)
498         {
499                 if (i < num)
500                 {
501 #if BYTE_ORDER != BIG_ENDIAN
502                         m_structure_cache[i * 2] = bswap_64(m_structure_cache[i * 2]);
503                         m_structure_cache[i * 2 + 1] = bswap_64(m_structure_cache[i * 2 + 1]);
504 #endif
505                 } else
506                 {
507                         m_structure_cache[i * 2] = 0x7fffffffffffffffULL; /* fill with harmless content */
508                         m_structure_cache[i * 2 + 1] = 0x7fffffffffffffffULL;
509                 }
510         }
511         m_structure_cache_entries = num;
512         return 0;
513 }
514
515 eMPEGStreamParserTS::eMPEGStreamParserTS(eMPEGStreamInformation &streaminfo):
516         m_streaminfo(streaminfo),
517         m_pktptr(0),
518         m_pid(-1),
519         m_need_next_packet(0),
520         m_skip(0),
521         m_last_pts_valid(0),
522         m_enable_accesspoints(true)
523 {
524 }
525
526 int eMPEGStreamParserTS::processPacket(const unsigned char *pkt, off_t offset)
527 {
528         if (!wantPacket(pkt))
529                 eWarning("something's wrong.");
530
531         const unsigned char *end = pkt + 188, *begin = pkt;
532         
533         int pusi = !!(pkt[1] & 0x40);
534         
535         if (!(pkt[3] & 0x10)) /* no payload? */
536                 return 0;
537
538         if (pkt[3] & 0xc0)
539         {
540                 /* scrambled stream, we cannot parse pts */
541                 return 0;
542         }
543
544         if (pkt[3] & 0x20) // adaptation field present?
545                 pkt += pkt[4] + 4 + 1;  /* skip adaptation field and header */
546         else
547                 pkt += 4; /* skip header */
548
549         if (pkt > end)
550         {
551                 eWarning("[TSPARSE] dropping huge adaption field");
552                 return 0;
553         }
554
555         pts_t pts = 0;
556         int ptsvalid = 0;
557         
558         if (pusi)
559         {
560                         // ok, we now have the start of the payload, aligned with the PES packet start.
561                 if (pkt[0] || pkt[1] || (pkt[2] != 1))
562                 {
563                         eWarning("broken startcode");
564                         return 0;
565                 }
566
567                 if (pkt[7] & 0x80) // PTS present?
568                 {
569                         pts  = ((unsigned long long)(pkt[ 9]&0xE))  << 29;
570                         pts |= ((unsigned long long)(pkt[10]&0xFF)) << 22;
571                         pts |= ((unsigned long long)(pkt[11]&0xFE)) << 14;
572                         pts |= ((unsigned long long)(pkt[12]&0xFF)) << 7;
573                         pts |= ((unsigned long long)(pkt[13]&0xFE)) >> 1;
574                         ptsvalid = 1;
575                         
576                         m_last_pts = pts;
577                         m_last_pts_valid = 1;
578
579         #if 0           
580                         int sec = pts / 90000;
581                         int frm = pts % 90000;
582                         int min = sec / 60;
583                         sec %= 60;
584                         int hr = min / 60;
585                         min %= 60;
586                         int d = hr / 24;
587                         hr %= 24;
588                         
589                         eDebug("pts: %016llx %d:%02d:%02d:%02d:%05d", pts, d, hr, min, sec, frm);
590         #endif
591                 }
592                 
593                         /* advance to payload */
594                 pkt += pkt[8] + 9;
595         }
596
597         while (pkt < (end-4))
598         {
599                 int pkt_offset = pkt - begin;
600                 if (!(pkt[0] || pkt[1] || (pkt[2] != 1)))
601                 {
602 //                      eDebug("SC %02x %02x %02x %02x, %02x", pkt[0], pkt[1], pkt[2], pkt[3], pkt[4]);
603                         int sc = pkt[3];
604                         
605                         if (m_streamtype == 0) /* mpeg2 */
606                         {
607                                 if ((sc == 0x00) || (sc == 0xb3) || (sc == 0xb8)) /* picture, sequence, group start code */
608                                 {
609                                         unsigned long long data = sc | (pkt[4] << 8) | (pkt[5] << 16) | (pkt[6] << 24);
610                                         m_streaminfo.writeStructureEntry(offset + pkt_offset, data  & 0xFFFFFFFFULL);
611                                 }
612                                 if (m_enable_accesspoints)
613                                 {
614                                         if (pkt[3] == 0xb3) /* sequence header */
615                                         {
616                                                 if (ptsvalid)
617                                                 {
618                                                         m_streaminfo.m_access_points[offset] = pts;
619                 //                                      eDebug("Sequence header at %llx, pts %llx", offset, pts);
620                                                 } else
621                                                         /*eDebug("Sequence header but no valid PTS value.")*/;
622                                         }
623                                 }
624                         }
625
626                         if (m_streamtype == 1) /* H.264 */
627                         {
628                                 if (sc == 0x09)
629                                 {
630                                                 /* store image type */
631                                         unsigned long long data = sc | (pkt[4] << 8);
632                                         m_streaminfo.writeStructureEntry(offset + pkt_offset, data);
633                                 }
634                                 if (m_enable_accesspoints)
635                                 {
636                                         if (pkt[3] == 0x09 &&   /* MPEG4 AVC NAL unit access delimiter */
637                                                  (pkt[4] >> 5) == 0) /* and I-frame */
638                                         {
639                                                 if (ptsvalid)
640                                                 {
641                                                         m_streaminfo.m_access_points[offset] = pts;
642                 //                              eDebug("MPEG4 AVC UAD at %llx, pts %llx", offset, pts);
643                                                 } else
644                                                         /*eDebug("MPEG4 AVC UAD but no valid PTS value.")*/;
645                                         }
646                                 }
647                         }
648                         if (m_streamtype == 6) /* H.265 */
649                         {
650                                 int nal_unit_type = (sc >> 1);
651                                 if (nal_unit_type == 35) /* H265 NAL unit access delimiter */
652                                 {
653                                         unsigned long long data = sc | (pkt[5] << 8);
654                                         m_streaminfo.writeStructureEntry(offset + pkt_offset, data);
655
656                                         if (m_enable_accesspoints)
657                                         {
658                                                 if ((pkt[5] >> 5) == 0) /* check pic_type for I-frame */
659                                                 {
660                                                         if (ptsvalid)
661                                                         {
662                                                                 m_streaminfo.m_access_points[offset] = pts;
663                                                         }
664                                                 }
665                                         }
666                                 }
667                         }
668                 }
669                 ++pkt;
670         }
671         return 0;
672 }
673
674 inline int eMPEGStreamParserTS::wantPacket(const unsigned char *hdr) const
675 {
676         if (hdr[0] != 0x47)
677         {
678                 eDebug("missing sync!");
679                 return 0;
680         }
681         int ppid = ((hdr[1]&0x1F) << 8) | hdr[2];
682
683         if (ppid != m_pid)
684                 return 0;
685                 
686         if (m_need_next_packet)  /* next packet (on this pid) was required? */
687                 return 1;
688         
689         if (hdr[1] & 0x40)       /* pusi set: yes. */
690                 return 1;
691
692         return m_streamtype == 0; /* we need all packets for MPEG2, but only PUSI packets for H.264 */
693 }
694
695 void eMPEGStreamParserTS::parseData(off_t offset, const void *data, unsigned int len)
696 {
697         const unsigned char *packet = (const unsigned char*)data;
698         const unsigned char *packet_start = packet;
699         
700                         /* sorry for the redundant code here, but there are too many special cases... */
701         while (len)
702         {
703                         /* emergency resync. usually, this should not happen, because the data should 
704                            be sync-aligned.
705                            
706                            to make this code work for non-strictly-sync-aligned data, (for example, bad 
707                            files) we fix a possible resync here by skipping data until the next 0x47.
708                            
709                            if this is a false 0x47, the packet will be dropped by wantPacket, and the
710                            next time, sync will be re-established. */
711                 int skipped = 0;
712                 while (!m_pktptr && len)
713                 {
714                         if (packet[0] == 0x47)
715                                 break;
716                         len--;
717                         packet++;
718                         skipped++;
719                 }
720                 
721                 if (skipped)
722                         eDebug("SYNC LOST: skipped %d bytes.", skipped);
723                 
724                 if (!len)
725                         break;
726                 
727                 if (m_pktptr)
728                 {
729                                 /* skip last packet */
730                         if (m_pktptr < 0)
731                         {
732                                 unsigned int skiplen = -m_pktptr;
733                                 if (skiplen > len)
734                                         skiplen = len;
735                                 packet += skiplen;
736                                 len -= skiplen;
737                                 m_pktptr += skiplen;
738                                 continue;
739                         } else if (m_pktptr < 4) /* header not complete, thus we don't know if we want this packet */
740                         {
741                                 unsigned int storelen = 4 - m_pktptr;
742                                 if (storelen > len)
743                                         storelen = len;
744                                 memcpy(m_pkt + m_pktptr, packet,  storelen);
745                                 
746                                 m_pktptr += storelen;
747                                 len -= storelen;
748                                 packet += storelen;
749                                 
750                                 if (m_pktptr == 4)
751                                         if (!wantPacket(m_pkt))
752                                         {
753                                                         /* skip packet */
754                                                 packet += 184;
755                                                 len -= 184;
756                                                 m_pktptr = 0;
757                                                 continue;
758                                         }
759                         }
760                                 /* otherwise we complete up to the full packet */
761                         unsigned int storelen = 188 - m_pktptr;
762                         if (storelen > len)
763                                 storelen = len;
764                         memcpy(m_pkt + m_pktptr, packet,  storelen);
765                         m_pktptr += storelen;
766                         len -= storelen;
767                         packet += storelen;
768                         
769                         if (m_pktptr == 188)
770                         {
771                                 m_need_next_packet = processPacket(m_pkt, offset + (packet - packet_start));
772                                 m_pktptr = 0;
773                         }
774                 } else if (len >= 4)  /* if we have a full header... */
775                 {
776                         if (wantPacket(packet))  /* decide wheter we need it ... */
777                         {
778                                 if (len >= 188)          /* packet complete? */
779                                 {
780                                         m_need_next_packet = processPacket(packet, offset + (packet - packet_start)); /* process it now. */
781                                 } else
782                                 {
783                                         memcpy(m_pkt, packet, len);  /* otherwise queue it up */
784                                         m_pktptr = len;
785                                 }
786                         }
787
788                                 /* skip packet */
789                         int sk = len;
790                         if (sk >= 188)
791                                 sk = 188;
792                         else if (!m_pktptr) /* we dont want this packet, otherwise m_pktptr = sk (=len) > 4 */
793                                 m_pktptr = sk - 188;
794
795                         len -= sk;
796                         packet += sk;
797                 } else             /* if we don't have a complete header */
798                 {
799                         memcpy(m_pkt, packet, len);   /* complete header next time */
800                         m_pktptr = len;
801                         packet += len;
802                         len = 0;
803                 }
804         }
805 }
806
807 void eMPEGStreamParserTS::setPid(int _pid, int type)
808 {
809         m_pktptr = 0;
810         m_pid = _pid;
811         m_streamtype = type;
812 }
813
814 int eMPEGStreamParserTS::getLastPTS(pts_t &last_pts)
815 {
816         if (!m_last_pts_valid)
817         {
818                 last_pts = 0;
819                 return -1;
820         }
821         last_pts = m_last_pts;
822         return 0;
823 }
824