Debian Codegraph @

src/index.cpp

raw
1 /* dvbcut
2 Copyright (c) 2005 Sven Over <[email protected]>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19 /* $Id$ */
20
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <cstdlib>
26 #include <cerrno>
27 #include <cstring>
28 #include <list>
29 #include <utility>
30 #include <set>
31 #include <vector>
32 #include <string>
33 #include <QCoreApplication>
34
35 #include "port.h"
36 #include "index.h"
37 #include "mpgfile.h"
38 #include "streamhandle.h"
39 #include "types.h"
40 #include "logoutput.h"
41
42 #ifndef O_BINARY
43 #define O_BINARY 0
44 #endif /* O_BINARY */
45
46 #define WRITE_FAKE_PICTURES // #undef to disable writing fake pictures
47
48 static inline ssize_t writer(int fd, const void *buf, size_t count)
49 {
50 int written=0;
51
52 while (count>0) {
53 int wr=write(fd,buf,count);
54 if (wr<0)
55 return wr;
56
57 written+=wr;
58 count-=wr;
59 buf=(const void*)((const char*)buf+wr);
60 }
61
62 return written;
63 }
64
65 index::~index()
66 {
67 if (p) {
68 free(p);
69 // delete read resolutions
70 WIDTH.clear();
71 HEIGHT.clear();
72 }
73 }
74
75 int index::generate(const char *savefilename, std::string *errorstring, logoutput *log)
76 {
77 int fd=-1;
78 bool usestdout=false;
79 int pictureswritten=0;
80 dvbcut_off_t filesize=0;
81
82 if (savefilename && savefilename[0]) {
83 if (savefilename[0]=='-' && savefilename[1]==0) // use stdout
84 {
85 fd=STDOUT_FILENO;
86 usestdout=true;
87 } else
88 if ((fd=::open(savefilename,O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,0666))<0) {
89 if (errorstring) {
90 //: 1% will be replaced with filename, %2 with error description
91 *errorstring += QCoreApplication::translate("index", "Open (%1): %2\n").arg(savefilename, strerror(errno)).toStdString();
92 }
93 return fd;
94 }
95 }
96
97 int size=90000;
98
99 if (p) {
100 if (pictures>0)
101 size=pictures;
102 else {
103 free(p);
104 p=0;
105 }
106 }
107
108 if (!p)
109 p=(picture*)malloc(size*sizeof(picture));
110
111 pictures=0;
112
113 if (log)
114 filesize=mpg.getfilesize();
115 streamhandle s(mpg.getinitialoffset());
116 streamdata *sd=s.newstream(VIDEOSTREAM,streamtype::mpeg2video,mpg.istransportstream());
117
118 bool foundseqheader=false;
119 bool waitforfirstsequenceheader=true;
120 int aspectratio=0,framerate=0;
121 double maxbitrate=0., bitrate;
122 long int bits=0;
123 pts_t maxbitratepts=0, dt;
124 int nres = 0;
125 filepos_t seqheaderpos=0, lastseqheaderpos=0;
126 int seqheaderpic=0;
127 pts_t referencepts=0; // pts of picture #0 in current sequence
128 int maxseqnr=-1; // maximum sequence number in current sequence
129 pts_t lastpts=1ll<<31, lastseqheaderpts=0, firstseqheaderpts=0;
130 int last_non_b_pic = -1;
131 int last_non_b_seqnr = -1;
132 int last_seqnr = -1;
133 int ptsmod = -1;
134 int errcnt = 0;
135 int err1cnt = 0;
136 int lasterr = 0;
137 int lastiframe = -1;
138
139 while (mpg.streamreader(s)>0) {
140 while (sd->getbuffer().inbytes()< (sd->getbuffer().getsize()/2))
141 if (mpg.streamreader(s)<=0)
142 break;
143
144 if (log) {
145 log->setprogress( (filesize>0)?(mpg.getfilepos()*1000/filesize):((mpg.getfilepos()/104753)%1001) );
146 if (log->cancelled()) {
147 if (p)
148 free(p);
149 p=0;
150 pictures=realpictures=0;
151 return 0;
152 }
153 }
154
155 // flush data to file
156 if (fd>=0 && pictureswritten<seqheaderpic) {
157 int len=(seqheaderpic-pictureswritten)*sizeof(picture);
158 if (::writer(fd,(void*)&p[pictureswritten],len)<0) {
159 if (errorstring) {
160 //: 1% will be replaced with filename, %2 with error description
161 *errorstring += QCoreApplication::translate("index", "Write (%1): %2\n").arg(savefilename, strerror(errno)).toStdString();
162 }
163 if (!usestdout)
164 ::close(fd);
165 fd=-1;
166 } else
167 pictureswritten=seqheaderpic;
168 }
169
170 const uint8_t *data=(const uint8_t*) sd->getdata();
171 unsigned int inbytes=sd->inbytes();
172 unsigned int skip=0;
173 while(skip+11<inbytes) {
174 if (data[skip+2]&0xfe) {
175 skip+=3;
176 continue;
177 }
178 if (data[skip+1]!=0) {
179 skip+=2;
180 continue;
181 }
182
183 uint32_t n;
184 memcpy(&n, data+skip, sizeof(n));
185 /* do a memcpy here because unaligned accesses are not sure to succeed on all platforms */
186 if (n == mbo32(0x000001b3)) // sequence header
187 {
188 if (last_non_b_pic >= 0) {
189 p[last_non_b_pic].setsequencenumber(++maxseqnr);
190 last_non_b_pic = -1;
191 }
192 last_seqnr = -1;
193
194 waitforfirstsequenceheader=false;
195 foundseqheader=true;
196 sd->discard(skip);
197 data=(const uint8_t*) sd->getdata();
198
199 // store found resolutions in lookup table
200 std::pair<int,int> res;
201 res.first=(data[4]<<4)|((data[5]>>4)&0xf); // width
202 res.second=((data[5]&0xf)<<8)|data[6]; // height
203 if (resolutions.find(res)==resolutions.end() && nres<7) {
204 nres++;
205 resolutions.insert(res); // a set helps checking already read resolutions
206 WIDTH.push_back(res.first);
207 HEIGHT.push_back(res.second);
208 //fprintf(stderr, "RESOLUTION[%d]: %d x %d\n", nres, res.first, res.second);
209 }
210
211 // that's always the same preset value and thus not very usefull (in 400 bps)!!!
212 //bitrate = ((data[8]<<10)|(data[9]<<2)|((data[10]>>6)&0x3))*400;
213 //if (bitrate>maxbitrate) maxbitrate=bitrate;
214
215 aspectratio=(data[7]>>4)&0xf;
216 framerate=data[7]&0xf;
217 referencepts+=((maxseqnr+1)*mpgfile::frameratescr[framerate])/300;
218 seqheaderpos=sd->itemlist().front().fileposition;
219 seqheaderpic=pictures;
220 maxseqnr=-1;
221
222 sd->discard(12);
223 data=(const uint8_t*) sd->getdata();
224 inbytes=sd->inbytes();
225 skip=0;
226
227 } else if ((n == mbo32(0x00000100)) && !waitforfirstsequenceheader) // picture header
228 {
229 sd->discard(skip);
230 data=(const uint8_t*) sd->getdata();
231
232 filepos_t picpos=sd->itemlist().front().fileposition;
233 int seqnr=(data[4]<<2)|((data[5]>>6)&3);
234 int frametype=(data[5]>>3)&7;
235 if (frametype>3)
236 frametype=0;
237
238 pts_t pts=sd->itemlist().front().headerpts();
239 if (pts>=0)
240 {
241 pts=ptsreference(pts,lastpts);
242 lastpts = pts;
243 int ptsdelta = mpgfile::frameratescr[framerate] / 300;
244 int epsilon = ptsdelta / 100; /* allow at most 1% deviation */
245 int mod = pts % ptsdelta;
246 if (ptsmod == -1)
247 ptsmod = mod;
248 else if (mod != ptsmod) {
249 int error = (mod - ptsmod + ptsdelta) % ptsdelta;
250 if (error > ptsdelta / 2)
251 error -= ptsdelta;
252 bool complain = false;
253 if (lasterr != error) {
254 if (err1cnt > 0) {
255 fprintf(stderr, "last video PTS error repeated %d times\n", err1cnt);
256 err1cnt = 0;
257 }
258 complain = true;
259 lasterr = error;
260 }
261 else
262 ++err1cnt;
263 ++errcnt;
264 if (-epsilon <= error && error <= epsilon) {
265 if (complain)
266 fprintf(stderr, "inconsistent video PTS (%+d), correcting\n", error);
267 pts -= error;
268 } else {
269 if (complain)
270 fprintf(stderr, "inconsistent video PTS (%+d) in %c frame %d, NOT correcting\n",
271 error, frametype["?IPB"], pictures);
272 }
273 }
274 referencepts=pts-(seqnr*mpgfile::frameratescr[framerate])/300;
275 sd->discardheader();
276 } else
277 pts=referencepts+(seqnr*mpgfile::frameratescr[framerate])/300;
278
279 if (pictures>=size)
280 {
281 size+=90000;
282 p=(picture*)realloc((void*)p,size*sizeof(picture));
283 }
284
285 #ifdef WRITE_FAKE_PICTURES
286 p[pictures]=picture(foundseqheader?seqheaderpos:picpos,pts,framerate,
287 aspectratio,seqnr,frametype,foundseqheader,nres);
288 #else
289 p[pictures]=picture(foundseqheader?seqheaderpos:picpos,pts,framerate,
290 aspectratio,seqnr,frametype,foundseqheader,0);
291 #endif
292
293 // try to determine bitrate per GOP manually since the read one is not very usefull
294 if (foundseqheader) {
295 if (firstseqheaderpts && lastseqheaderpos<seqheaderpos && lastseqheaderpts<pts) {
296 dt = (pts-lastseqheaderpts)/90;
297 bits = (seqheaderpos-lastseqheaderpos)*8;
298 // avergage (input) bitrate per GOP
299 bitrate=1000*double(bits)/double(dt);
300 if (maxbitrate<bitrate) {
301 maxbitrate=bitrate;
302 maxbitratepts=lastseqheaderpts;
303 }
304 //fprintf(stderr, "%s: BITRATE = %d kbps over next %d ms\n",
305 // ptsstring(lastseqheaderpts-firstseqheaderpts).c_str(), int(bitrate/1024.), int(dt));
306 } else {
307 firstseqheaderpts=pts;
308 }
309 lastseqheaderpos=seqheaderpos;
310 lastseqheaderpts=pts;
311 }
312
313 if (frametype == IDX_PICTYPE_I) {
314 if (lastiframe >= 0) {
315 int framepts = mpgfile::frameratescr[framerate] / 300;
316 pts_t ptsdelta = pts - p[lastiframe].getpts();
317 int pdelta = pictures - lastiframe + seqnr - p[lastiframe].getsequencenumber();
318 if (pdelta * framepts < ptsdelta)
319 fprintf(stderr, "missing frames in GOP (%d, %d): %ld\n",
320 lastiframe, pictures, ptsdelta / framepts - pdelta);
321 }
322 lastiframe = pictures;
323 }
324
325 if (frametype == IDX_PICTYPE_B) {
326 /* check sequence number */
327 if (seqnr != last_seqnr + 1) {
328 fprintf(stderr,
329 "missing frame(s) before B frame %d (%d != %d)\n",
330 pictures, seqnr, last_seqnr + 1);
331 if (seqnr <= last_seqnr) {
332 fprintf(stderr, "=> sequence number reset (%d => %d)\n", last_seqnr + 1, seqnr);
333 if (last_non_b_pic >= 0 && last_non_b_seqnr > last_seqnr) {
334 fprintf(stderr, "=> inserting delayed picture (%d)\n", last_non_b_seqnr);
335 p[last_non_b_pic].setsequencenumber(++maxseqnr);
336 last_non_b_pic = -1;
337 }
338 }
339 else if (last_non_b_pic >= 0 && last_non_b_seqnr < seqnr) {
340 fprintf(stderr, "=> inserting delayed picture (%d)\n", last_non_b_seqnr);
341 p[last_non_b_pic].setsequencenumber(++maxseqnr);
342 last_non_b_pic = -1;
343 }
344 }
345 p[pictures].setsequencenumber(++maxseqnr);
346 last_seqnr = seqnr;
347 } else {
348 /* I and P frames are delayed */
349 if (last_non_b_pic >= 0) {
350 /* check sequence number */
351 if (last_non_b_seqnr != last_seqnr + 1) {
352 fprintf(stderr,
353 "missing frame(s) before %c frame %d (%d != %d)\n",
354 p[last_non_b_pic].isiframe() ? 'I' : 'P',
355 pictures, last_non_b_seqnr, last_seqnr + 1);
356 }
357 p[last_non_b_pic].setsequencenumber(++maxseqnr);
358 last_seqnr = last_non_b_seqnr;
359 }
360 last_non_b_pic = pictures;
361 last_non_b_seqnr = seqnr;
362 if (frametype == IDX_PICTYPE_I)
363 last_seqnr = -1;
364 }
365
366 ++pictures;
367
368 foundseqheader=false;
369 sd->discard(8);
370 data=(const uint8_t*) sd->getdata();
371 inbytes=sd->inbytes();
372 skip=0;
373 } else
374 ++skip;
375 }
376 sd->discard(skip);
377 }
378
379 if (err1cnt > 0)
380 fprintf(stderr, "last video PTS error repeated %d times\n", err1cnt);
381 if (errcnt > 0)
382 fprintf(stderr, "found %d video PTS errors\n", errcnt);
383
384 if (last_non_b_pic >= 0) {
385 p[last_non_b_pic].setsequencenumber(++maxseqnr);
386 last_non_b_pic = -1;
387 }
388
389 if (pictures==0) {
390 free(p);
391 p=0;
392 } else {
393 #ifdef WRITE_FAKE_PICTURES
394 if (size < pictures + 7) {
395 size = pictures + 7;
396 p=(picture*)realloc((void*)p,size*sizeof(picture));
397 }
398 // create fake pictures containing read resolutions (pos: width, pts: height)
399 for (int i=0; i<7; i++) {
400 int w = i < nres ? WIDTH[i] : 0;
401 int h = i < nres ? HEIGHT[i] : 0;
402 p[pictures]=picture(filepos_t(w),pts_t(h),0,0,0,0,false,i+1);
403 ++pictures;
404 }
405 #endif
406 if (size != pictures) {
407 p=(picture*)realloc((void*)p,pictures*sizeof(picture));
408 }
409 }
410
411 if (fd>=0 && pictureswritten<pictures) {
412 int len=(pictures-pictureswritten)*sizeof(picture);
413 if (::writer(fd,(void*)&p[pictureswritten],len)<0) {
414 if (errorstring)
415 *errorstring += QCoreApplication::translate("index", "Write (%1): %2\n").arg(savefilename, strerror(errno)).toStdString();
416 if (!usestdout)
417 ::close(fd);
418 fd=-1;
419 } else
420 pictureswritten=pictures;
421 }
422
423 if (!usestdout && fd>=0)
424 ::close(fd);
425
426 #ifdef WRITE_FAKE_PICTURES
427 if (pictures != 0)
428 pictures-=7; // subtract fake pictures
429 #endif
430 fprintf(stderr, "Max. input bitrate of %d kbps detected at %s\n", int(maxbitrate/1024), ptsstring(maxbitratepts-firstseqheaderpts).c_str());
431
432 return check();
433 }
434
435 int
436 index::save(int fd, std::string *errorstring, bool closeme) {
437 #ifdef WRITE_FAKE_PICTURES
438 int len = (pictures + 7) * sizeof(picture);
439 #else
440 int len = pictures * sizeof(picture);
441 #endif
442 int res = 0;
443 int save = 0;
444
445 if (isatty(fd)) {
446 if (errorstring)
447 *errorstring += QCoreApplication::translate("index", "refusing to write index to a tty\n").toStdString();
448 errno = EINVAL;
449 // Note: do NOT close it even if the caller said so
450 return -1;
451 }
452 if (::writer(fd, (void*)p, len) < 0) {
453 save = errno;
454 if (errorstring) {
455 //: Placeholder will be replaced with error description
456 *errorstring += QCoreApplication::translate("index", "write: %1\n").arg(strerror(errno)).toStdString();
457 }
458 res = -1;
459 }
460 if (closeme)
461 ::close(fd);
462 errno = save;
463 return res;
464 }
465
466 int
467 index::save(const char *filename, std::string *errorstring) {
468 int fd;
469
470 fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
471 if (fd == -1) {
472 if (errorstring) {
473 //: %1 will be replaced with filename, %2 with error description
474 *errorstring += QCoreApplication::translate("index", "%1: open: %2\n").arg(filename, strerror(errno)).toStdString();
475 }
476 return -1;
477 }
478 std::string tmp;
479 if (save(fd, &tmp, true) == -1) {
480 if (errorstring)
481 *errorstring += std::string(filename) + ": " + tmp;
482 return -1;
483 }
484 return 0;
485 }
486
487 int index::load(const char *filename, std::string *errorstring)
488 {
489 int fd=::open(filename,O_RDONLY|O_BINARY,0666);
490 if (fd<0) {
491 if (errorstring) {
492 int serrno=errno;
493 *errorstring += QCoreApplication::translate("index", "Open (%1): %2\n").arg(filename, strerror(errno)).toStdString();
494 errno=serrno;
495 }
496 return fd;
497 }
498
499 int size=0;
500 int len=0;
501 uint8_t *data=0;
502
503 for(;;) {
504 if (len>=size) {
505 size+=90000*sizeof(picture);
506 data=(uint8_t*)realloc((void*)data,size);
507 }
508
509 int rd=::read(fd,data+len,size-len);
510
511 if (rd<0) {
512 int save_errno=errno;
513 if (errorstring) {
514 //: %1 will be replaced with filename, %2 with error description
515 *errorstring += QCoreApplication::translate("index", "Read (%1): %2\n").arg(filename, strerror(errno)).toStdString();
516 }
517 if (data)
518 free(data);
519 ::close(fd);
520 errno=save_errno;
521 return -1;
522 }
523
524 if (rd==0)
525 break;
526
527 len+=rd;
528 }
529
530 ::close(fd);
531
532 pictures=len/sizeof(picture);
533 if (pictures==0) {
534 free(p);
535 p=0;
536 realpictures=0;
537 return 0;
538 }
539 if (!((picture*)data)->getseqheader()) {
540 free(p);
541 p=0;
542 pictures=0;
543 realpictures=0;
544 if (errorstring) {
545 //: Placeholder will be replaced with filename
546 *errorstring += QCoreApplication::translate("index", "Invalid index file '%1'\n").arg(filename).toStdString();
547 }
548 fprintf(stderr,"Invalid index file: first frame no sequence header\n");
549 return -2;
550 }
551 p=(picture*)realloc((void*)data,pictures*sizeof(picture));
552
553 // 7 fake pictures at end contain resolution lookup table
554 // (if new type of index file, after svn-revision 131)
555 if (p[0].getresolution()>0) {
556 pictures-=7;
557 int w, h, nres=0;
558 for (int i=pictures; nres<7; i++) {
559 w=int(p[i].getpos());
560 h=int(p[i].getpts());
561 if (w==0 || h==0)
562 break;
563 nres++;
564 WIDTH.push_back(w);
565 HEIGHT.push_back(h);
566 //fprintf(stderr, "RESOLUTION[%d]: %d x %d\n", nres, w, h);
567 }
568 }
569
570 int seqnr[1<<10]={0};
571 int seqpics=0;
572 for(int i=0;;++i) {
573 if (i==pictures || p[i].getseqheader()) {
574 for(int j=0;j<seqpics;++j) {
575 if (seqnr[j]!=1) // this sequence-number did not appear exactly once
576 {
577 if (errorstring) {
578 //: Placeholder will be replaced with filename
579 *errorstring += QCoreApplication::translate("index", "Invalid index file (%1)\n").arg(filename).toStdString();
580 }
581 fprintf(stderr,"Invalid index file: sequence number %u appears %u times\n",
582 j, seqnr[j]);
583 fprintf(stderr, "Picture %u/%u, %u seqpics\n", i, pictures, seqpics);
584 free(p);
585 p=0;
586 pictures=0;
587 realpictures=0;
588 return -2;
589 }
590 seqnr[j]=0;
591 }
592 if (i==pictures)
593 break;
594 seqpics=0;
595 }
596 ++seqnr[p[i].getsequencenumber()];
597 ++seqpics;
598 }
599
600 for(int i=1;i<pictures;i<<=1) {
601 while(i<pictures && !p[i].getseqheader())
602 ++i;
603 if (i==pictures)
604 break;
605 streamhandle s(p[i].getpos().packetposition());
606 streamdata *sd=s.newstream(VIDEOSTREAM,streamtype::mpeg2video,mpg.istransportstream());
607 unsigned int po=p[i].getpos().packetoffset();
608 while (sd->inbytes()<po+4)
609 if (mpg.streamreader(s)<=0)
610 break;
611 if ( (sd->inbytes()<po+4) || (*(const uint32_t*)((const uint8_t*)sd->getdata()+po) != mbo32(0x000001b3)) ) {
612 fprintf(stderr,"index does not match (%08x)\n",(*(const uint32_t*)((const uint8_t*)sd->getdata()+po)));
613 free(p);
614 p=0;
615 pictures=0;
616 realpictures=0;
617 if (errorstring) {
618 //: Placeholder will be replaced with filename
619 *errorstring += QCoreApplication::translate("index", "Index file (%1) does not correspond to MPEG file\n").arg(filename).toStdString();
620 }
621 return -3;
622 }
623 }
624
625 return check();
626 }
627
628 int index::check()
629 {
630 int firstiframe;
631
632 for(firstiframe=0;firstiframe<pictures;++firstiframe)
633 if (p[firstiframe].isiframe())
634 break;
635
636 if (firstiframe>=pictures) {
637 realpictures=0;
638 skipfirst=0;
639 return 0;
640 }
641
642 int sequencebegin=0;
643 for (int i=firstiframe;i>0;--i)
644 if (p[i].getseqheader()) {
645 sequencebegin=i;
646 break;
647 }
648
649 skipfirst=sequencebegin;
650 if (p[firstiframe].getsequencenumber()>0) {
651 int fifseqnr=p[firstiframe].getsequencenumber();
652
653 for(int i=sequencebegin;(i<pictures)&&(!p[i].getseqheader()||i==sequencebegin);++i)
654 if (p[i].getsequencenumber()<fifseqnr)
655 ++skipfirst;
656 }
657
658 realpictures=pictures-skipfirst;
659 if (realpictures<1)
660 return 0;
661
662 while (realpictures>0)
663 if (p[indexnr(realpictures-1)].isbframe())
664 --realpictures;
665 else
666 break;
667
668 return realpictures;
669 }
670