Debian Codegraph @

src/mpgfile.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 <cstdlib>
22 #include <cstring>
23 #include <stdint.h>
24 #include <cerrno>
25 #include <unistd.h>
26 #include <cmath>
27
28 #include <list>
29 #include <utility>
30 #include <QCoreApplication>
31
32 #include "port.h"
33 #include "mpgfile.h"
34 #include "tsfile.h"
35 #include "psfile.h"
36 #include "index.h"
37 #include "avframe.h"
38 #include "streamhandle.h"
39 #include "playaudio.h"
40 #include "muxer.h"
41 #include "logoutput.h"
42
43 #include <stdio.h>
44
45 const int mpgfile::frameratescr[16]=
46 {
47 1080000,1126125,1125000,1080000,900900,900000,540000,450450,450000,
48 1080000,1080000,1080000,1080000,1080000,1080000,1080000
49 };
50
51 mpgfile::mpgfile(inbuffer &b, int initial_offset)
52 : buf(b),
53 videostreams(0),audiostreams(0),
54 initialoffset(initial_offset),idx(*this),pictures(0),
55 time_base_num(1), time_base_den(25)
56 {}
57
58 mpgfile::~mpgfile()
59 {}
60
61 /// Factory function
62 mpgfile*
63 mpgfile::open(inbuffer &b, std::string *errormessage) {
64 if (errormessage)
65 errormessage->clear();
66
67 if (b.providedata(64 << 10) < (64 << 10)) {
68 if (errormessage)
69 *errormessage = QCoreApplication::translate("mpgfile", "File too short").toStdString();
70 return 0;
71 }
72
73 int initialoffset;
74 // 2011-04-24: check packet sizes from 188 up to 208. --mr
75 for (int stride = TSPACKETSIZE; stride <= MAXPACKETSIZE; stride += 4)
76 if ((initialoffset=tsfile::probe(b, stride))>=0) // is this an mpeg transport stream?
77 return new tsfile(b, initialoffset, stride);
78 if ((initialoffset=psfile::probe(b))>=0) // is this an mpeg program stream?
79 return new psfile(b, initialoffset);
80
81 if (errormessage)
82 *errormessage = QCoreApplication::translate("mpgfile", "Unknown file type").toStdString();
83 return 0;
84 }
85
86 void mpgfile::decodegop(int start, int stop, std::list<avframe*> &framelist)
87 {
88 stream *S=&s[videostream()];
89 if (!S->avcc)
90 return;
91
92 if (start<0)
93 start=0;
94 if (stop<0)
95 stop=nextiframe(start+1)+1;
96 else if (stop<=start)
97 stop=start+1;
98 if (stop>pictures)
99 stop=pictures;
100
101 if (stop<=start)
102 return;
103 int pic=lastseqheader(lastiframe(start));
104 int streampic=idx.indexnr(pic);
105 int seqnr=idx[streampic].getsequencenumber();
106
107 streamhandle s(idx[streampic].getpos().packetposition());
108 streamdata *sd=s.newstream(VIDEOSTREAM,streamtype::mpeg2video,istransportstream());
109
110 if (idx[streampic].getpos().packetoffset()>0)
111 {
112 while( sd->inbytes()<idx[streampic].getpos().packetoffset() )
113 {
114 if (streamreader(s)<=0)
115 return;
116 }
117 sd->discard(idx[streampic].getpos().packetoffset());
118 }
119
120 if (int rv=avcodec_open2(S->avcc, S->dec, NULL))
121 {
122 fprintf(stderr,"avcodec_open returned %d\n",rv);
123 return;
124 }
125 avframe avf;
126 int last_cpn=-1;
127 bool firstframe=true, firstsequence=true;
128
129 while (pic<stop && streampic<idx.getpictures())
130 {
131 filepos_t tp(getfilesize(),0);
132 if ((streampic+1)<idx.getpictures())
133 tp=idx[streampic+1].getpos();
134 while (sd->itemlist().empty() || s.fileposition<tp.fileposition())
135 if (streamreader(s)<=0)
136 break;
137
138 int bytes=sd->inbytes();
139
140 for(streamdata::itemlisttype::const_iterator it=sd->itemlist().begin();it!=sd->itemlist().end();++it)
141 if (it->fileposition.packetposition()==tp.packetposition())
142 {
143 bytes=it->bufferposition-sd->getoffset()+tp.packetoffset()-it->fileposition.packetoffset();
144 break;
145 }
146 else
147 if (it->fileposition.packetposition()>tp.packetposition())
148 {
149 bytes=it->bufferposition-sd->getoffset();
150 break;
151 }
152
153 if (!firstframe && idx[streampic].getseqheader())
154 firstsequence=false;
155 firstframe=false;
156
157 if (!firstsequence || idx[streampic].getsequencenumber()>=seqnr)
158 {
159 const uint8_t *data=(const uint8_t*)sd->getdata();
160
161 AVPacket* pkt = av_packet_alloc();
162 pkt->data = (uint8_t*) data;
163 pkt->size = bytes;
164 avcodec_send_packet(S->avcc, pkt);
165 while (avcodec_receive_frame(S->avcc, avf) == 0)
166 {
167 //fprintf(stderr, "* decoded frame %5d ilace:%d typ:%d pts=%f\n", pic, avf->interlaced_frame, avf->pict_type, (double)avf->pts/90000.0);
168 if (last_cpn!=avf->coded_picture_number) {
169 last_cpn=avf->coded_picture_number;
170 if (pic>=start) {
171 framelist.push_back(new avframe(avf,S->avcc));
172 }
173 ++pic;
174 if (pic>=stop) {
175 break;
176 }
177 }
178 }
179 av_packet_free(&pkt);
180 }
181
182 sd->discard(bytes);
183 ++streampic;
184 }
185
186 if (pic < stop)
187 {
188 AVPacket* pkt = av_packet_alloc();
189 pkt->data = NULL;
190 pkt->size = 0;
191 avcodec_send_packet(S->avcc, pkt);
192 while (avcodec_receive_frame(S->avcc, avf) == 0)
193 {
194 if (last_cpn!=avf->coded_picture_number)
195 {
196 last_cpn=avf->coded_picture_number;
197 if (pic>=start)
198 framelist.push_back(new avframe(avf,S->avcc));
199 }
200 }
201 av_packet_free(&pkt);
202 }
203
204 time_base_num = S->avcc->time_base.num;
205 time_base_den = S->avcc->time_base.den;
206 if (S->avcc->ticks_per_frame > 0) {
207 //fprintf(stderr, "field rate -> frame rate\n");
208 time_base_num *= S->avcc->ticks_per_frame;
209 }
210
211 avcodec_close(S->avcc);
212 }
213
214 void mpgfile::initaudiocodeccontext(int aud)
215 {
216 stream &S=s[audiostream(aud)];
217 S.infostring="Audio ";
218
219 {
220 char number[16];
221 snprintf(number,16,"%d",aud);
222 S.infostring+=number;
223 }
224
225 switch (S.type)
226 {
227 case streamtype::mpegaudio:
228 S.infostring+=" (MPEG)";
229 break;
230 case streamtype::ac3audio:
231 S.infostring+=" (AC3)";
232 break;
233 default:
234 S.infostring+=" (unknown)";
235 break;
236 }
237 }
238
239 void mpgfile::initcodeccontexts(int vid)
240 {
241 if (vid>=0) {
242 videostreams=1;
243 stream *S=&s[VIDEOSTREAM];
244 S->id=vid;
245 S->allocavcc();
246 S->avcc->codec_type=AVMEDIA_TYPE_VIDEO;
247 S->avcc->codec_id=AV_CODEC_ID_MPEG2VIDEO;
248 S->dec=avcodec_find_decoder(AV_CODEC_ID_MPEG2VIDEO);
249 S->enc=avcodec_find_encoder(AV_CODEC_ID_MPEG2VIDEO);
250 S->type=streamtype::mpeg2video;
251 }
252
253 for (int i=0;i<audiostreams;++i)
254 initaudiocodeccontext(i);
255 }
256
257 #ifdef HAVE_LIB_AO
258 void mpgfile::playaudio(int aud, int picture, int ms)
259 {
260 if (aud>=audiostreams || ms==0)
261 return;
262
263 pts_t startpts=idx[idx.indexnr(picture)].getpts();
264 pts_t stoppts=startpts;
265
266 if (ms<0)
267 startpts+=ms*90;
268 else
269 stoppts+=ms*90;
270
271 int seekpic=idx.indexnr(picture);
272 while (seekpic>0 && idx[seekpic].getpts()>=startpts-180000)
273 --seekpic;
274 int stopreadpic=idx.indexnr(picture);
275 while (stopreadpic<pictures-1 && idx[stopreadpic].getpts()<stoppts+180000)
276 ++stopreadpic;
277 dvbcut_off_t stopreadpos=idx[stopreadpic].getpos().packetposition();
278
279 streamhandle sh(idx[seekpic].getpos().packetposition());
280 streamdata *sd=sh.newstream(audiostream(aud),s[audiostream(aud)].type,istransportstream());
281
282 while (sd->empty())
283 {
284 if (sh.fileposition > stopreadpos || streamreader(sh)<=0)
285 return; // data does not reach the point in time from which we like to start playing
286 while (!sd->empty() && !sd->itemlist().begin()->headerhaspts())
287 sd->pop();
288 }
289
290 for(;;)
291 {
292 if (sh.fileposition > stopreadpos || streamreader(sh)<=0)
293 return; // data does not reach the point in time from which we like to start playing
294 if (sd->empty())
295 continue;
296
297 streamdata::itemlisttype::const_iterator it=sd->itemlist().begin();
298 int pop=1;
299 pts_t pts=AV_NOPTS_VALUE;
300 for(++it;it!=sd->itemlist().end();++it,++pop)
301 if (it->headerhaspts()) //if (streamdata::headerhaspts(it->header))
302 {
303 pts=it->headerpts(startpts);
304 break;
305 }
306 if (pts==(pts_t)AV_NOPTS_VALUE)
307 continue;
308 if (pts<=startpts)
309 sd->pop(pop);
310 if (pts>=startpts)
311 break;
312 }
313
314 while (streamreader(sh)>0)
315 {
316 streamdata::itemlisttype::const_reverse_iterator it=sd->itemlist().rbegin();
317 while(it!=sd->itemlist().rend())
318 if (it->headerhaspts())
319 break;
320 else
321 --it;
322
323 if (it==sd->itemlist().rend())
324 continue;
325
326 if (it->headerpts(stoppts)>stoppts)
327 break;
328 }
329
330 sd->audio_addpts();
331
332 uint32_t startbufferpos=sd->closestptsbufferpos(startpts);
333 uint32_t stopbufferpos=sd->closestptsbufferpos(stoppts);
334
335 if (stopbufferpos>startbufferpos)
336 {
337 const stream &S=s[audiostream(aud)];
338
339 if (S.type==streamtype::ac3audio)
340 playaudio_ac3(sd->getdata(startbufferpos),stopbufferpos-startbufferpos);
341 else
342 playaudio_mp2(sd->getdata(startbufferpos),stopbufferpos-startbufferpos);
343 }
344 }
345 #else // HAVE_LIB_AO
346 void mpgfile::playaudio(int, int, int)
347 {
348 }
349 #endif // HAVE_LIB_AO
350
351 void mpgfile::savempg(muxer &mux, int start, int stop, int savedpics, int savepics, logoutput *log)
352 {
353 if (start<0)
354 start=0;
355 if (start>pictures)
356 start=pictures;
357 if (stop<0)
358 stop=0;
359 if (stop>pictures)
360 stop=pictures;
361 if (start==stop)
362 return;
363 if (stop<start)
364 {
365 int x=start;
366 start=stop;
367 stop=x;
368 }
369
370 int seekpic=idx.indexnr(start);
371 int framerate = mpgfile::frameratescr[idx[seekpic].getframerate()];
372 bool fixedstart=true;
373
374 if (mux.isempty())
375 {
376 fixedstart=false;
377 mux.unsetempty();
378 pts_t startpts = framerate / 300;
379 for (int i=0;i<MAXAVSTREAMS;++i)
380 mux.setpts(i,startpts);
381 }
382
383 pts_t videostartpts=idx[seekpic].getpts();
384 pts_t videostoppts=idx[idx.indexnr(stop)].getpts();
385 pts_t videooffset=videostartpts-mux.getpts(VIDEOSTREAM);
386 pts_t audiopts[MAXAUDIOSTREAMS];
387 pts_t audiostartpts[MAXAUDIOSTREAMS];
388 pts_t audiooffset[MAXAUDIOSTREAMS];
389 for(int a=0;a<MAXAUDIOSTREAMS;++a)
390 {
391 audiooffset[a]=videooffset;
392 audiostartpts[a]=audiopts[a]=videostartpts;
393 }
394 pts_t shift=0;
395
396 {
397 dvbcut_off_t start_pos = idx[idx.indexnr(start)].getpos().fileposition();
398 dvbcut_off_t stop_pos = idx[idx.indexnr(stop)].getpos().fileposition();
399 dvbcut_off_t bytes = stop_pos - start_pos;
400 pts_t delta_pts = (pts_t)(stop - start) * framerate / 300;
401 double mux_rate = (double)bytes * 9e4 / (double)delta_pts;
402 if (log) {
403 //: Placeholder will be replaced with floating point number
404 log->printinfo(QCoreApplication::translate("mpgfile", "Estimated mux rate: %1 MB/s").arg(mux_rate * 1e-6, 0, 'f', 2));
405 }
406 }
407
408 while (seekpic>0 && idx[seekpic].getpts()>=videostartpts-180000)
409 --seekpic;
410
411 dvbcut_off_t tpos;
412 {
413 int stoppic=idx.indexnr(start);
414 while (stoppic<pictures &&
415 (idx[stoppic].getpts()<videostartpts+180000 || !idx[stoppic].getseqheader()))
416 ++stoppic;
417 tpos=idx[stoppic].getpos().packetposition();
418 }
419
420 streamhandle sh(idx[seekpic].getpos().packetposition());
421 streamdata *vsd=sh.newstream(VIDEOSTREAM,s[VIDEOSTREAM].type,istransportstream());
422 for (int a=0;a<MAXAUDIOSTREAMS;++a)
423 if (mux.streampresent(audiostream(a)))
424 sh.newstream(audiostream(a),s[audiostream(a)].type,istransportstream());
425
426 while (sh.fileposition<tpos)
427 if (streamreader(sh)<0)
428 break;
429
430 for (int a=0;a<MAXAUDIOSTREAMS;++a)
431 if (streamdata *sd=sh.stream[audiostream(a)])
432 {
433 pts_t tpts=videostartpts-mux.getpts(VIDEOSTREAM)+mux.getpts(audiostream(a));
434 sd->audio_addpts();
435 uint32_t startbufferpos=sd->ptsbufferpos(tpts);
436 if (startbufferpos>sd->getoffset())
437 sd->discard(startbufferpos-sd->getoffset());
438 sd->audio_addpts(0,true);
439 startbufferpos=sd->closestptsbufferpos(tpts);
440 if (startbufferpos>sd->getoffset())
441 sd->discard(startbufferpos-sd->getoffset());
442
443 pts_t apts=sd->itemlist().front().headerpts(tpts);
444 audiostartpts[a]=apts;
445 if (apts>=0)
446 {
447 if (fixedstart)
448 audiooffset[a]=videooffset-tpts+apts;
449 else if (tpts-apts>shift)
450 shift=tpts-apts;
451 }
452
453 }
454
455 if (!fixedstart)
456 {
457 videooffset-=shift;
458 for(int a=0;a<MAXAUDIOSTREAMS;++a)
459 audiooffset[a]=videooffset;
460 }
461
462 pts_t audiostoppts[MAXAUDIOSTREAMS];
463 for(int a=0;a<MAXAUDIOSTREAMS;++a)
464 audiostoppts[a]=videostoppts-videooffset+audiooffset[a];
465
466 int firstseqhdr=nextseqheader(start);
467 {
468 filepos_t copystart=idx[idx.indexnr(firstseqhdr)].getpos();
469 vsd->discard(vsd->fileposbufferpos(copystart)-vsd->getoffset());
470 }
471 bool isfirstpic=true, isfirstseq=true;
472 int firstseqnr=idx[idx.indexnr(firstseqhdr)].getsequencenumber();
473
474 if (firstseqhdr>start)
475 {
476 recodevideo(mux,start,firstseqhdr,videooffset,savedpics,savepics,log);
477 savedpics+=firstseqhdr-start;
478 }
479
480 int copystop=stop; // first picture not to write to stream
481 while (copystop<pictures && idx[idx.indexnr(copystop)].isbframe())
482 ++copystop;
483 copystop=idx.indexnr(copystop);
484
485 int streampic=idx.indexnr(firstseqhdr);
486
487 while (!log || !log->cancelled())
488 {
489 int packetsread;
490 for (packetsread=0;packetsread<20;++packetsread)
491 if (streamreader(sh)<=0)
492 break;
493 if (packetsread==0)
494 break;
495
496 // copy video
497 if (vsd)
498 for(;;)
499 {
500 if (streampic>=copystop)
501 {
502 vsd=0;
503 sh.delstream(VIDEOSTREAM);
504 break;
505 }
506
507 uint32_t picsize=vsd->fileposbufferpos(idx[streampic+1].getpos())-vsd->getoffset();
508 if (picsize>=vsd->inbytes())
509 break;
510
511 if (!isfirstpic && idx[streampic].getseqheader())
512 isfirstseq=false;
513 isfirstpic=false;
514
515 int seqoff=0;
516 if (!isfirstseq || idx[streampic].getsequencenumber()>=firstseqnr)
517 {
518 if (isfirstseq && firstseqnr>0) // need to subtract offset from picture sequence number
519 {
520 uint8_t *d=(uint8_t*) vsd->getdata();
521
522 for (unsigned int j=0;j+5<picsize;)
523 {
524 if (d[2]&0xfe)
525 j+=3;
526 else
527 if (*(u_int32_t*)&d[j]==mbo32(0x00000100))
528 {
529 int seqpic=(d[j+4]<<2)|((d[j+5]>>6)&0x03);
530 seqpic-=firstseqnr;
531 d[j+4]=seqpic>>2;
532 d[j+5]=(d[j+5]&0x3f)|((seqpic<<6)&0xc0);
533 break;
534 }
535 else
536 ++j;
537 }
538 seqoff=firstseqnr;
539 }
540 pts_t vidpts=idx[streampic].getpts()-videooffset;
541 pts_t viddts=vidpts;
542 if (!idx[streampic].isbframe())
543 {
544 viddts=mux.getdts(VIDEOSTREAM);
545 mux.setdts(VIDEOSTREAM,vidpts);
546 }
547 if (idx[streampic].getseqheader())
548 {
549 int tcpic=streampic;
550 while (tcpic < copystop && idx[tcpic].getsequencenumber() != seqoff)
551 ++tcpic;
552 pts_t tcpts=idx[tcpic].getpts()-videooffset;
553 fixtimecode((uint8_t*)vsd->getdata(),picsize,tcpts);
554 }
555 if (!mux.putpacket(VIDEOSTREAM,vsd->getdata(),picsize,vidpts,viddts,
556 idx[streampic].isiframe() ? MUXER_FLAG_KEY:0 ))
557 {
558 if (log) {
559 //: Placeholder will be replaced with streampic number
560 log->printwarning(QCoreApplication::translate("mpgfile", "putpacket(streampic=%1) returned false").arg(streampic));
561 } else {
562 fprintf(stderr,"WARN: putpacket(streampic=%d) returned false\n",streampic);
563 }
564 }
565 }
566
567 vsd->discard(picsize);
568 ++streampic;
569
570 if (log && savepics>0)
571 log->setprogress(++savedpics*1000/savepics);
572 }
573
574 bool haveaudio=false;
575
576 for (int a=0;a<MAXAUDIOSTREAMS;++a)
577 if (streamdata * const sd=sh.stream[audiostream(a)])
578 {
579 bool stopped=false;
580 sd->audio_addpts();
581 streamdata::itemlisttype::const_iterator nx,it;
582
583 while ((it = sd->itemlist().begin())!=sd->itemlist().end() &&
584 !it->is_frame())
585 sd->pop();
586 if (it!=sd->itemlist().end())
587 while(!stopped)
588 {
589 audiopts[a]=it->headerpts(audiopts[a]);
590 if (audiopts[a]>=audiostoppts[a])
591 {
592 audiostoppts[a]=audiopts[a];
593 stopped=true;
594 break;
595 }
596 nx=it;
597 ++nx;
598 while (nx!=sd->itemlist().end() && !nx->is_frame())
599 ++nx;
600 if (nx==sd->itemlist().end())
601 break;
602 uint32_t bytes=nx->bufferposition-it->bufferposition;
603 pts_t nxheaderpts=nx->headerpts(audiopts[a]);
604
605 if (nxheaderpts>=audiostoppts[a])
606 {
607 if (nxheaderpts-audiostoppts[a]>audiostoppts[a]-audiopts[a])
608 {
609 bytes=0;
610 audiostoppts[a]=audiopts[a];
611 }
612 else
613 audiostoppts[a]=nxheaderpts;
614 stopped=true;
615 }
616
617 if (nx->bufferposition<it->bufferposition)
618 {
619
620 for(it=sd->itemlist().begin();it!=sd->itemlist().end();++it)
621 fprintf(stderr," fileposition:%ld/%d bufferposition:%d flags:%x pts:%s\n",
622 it->fileposition.packetposition(),it->fileposition.packetoffset(),
623 it->bufferposition,it->flags,ptsstring(it->pts).c_str());
624
625 fprintf(stderr,"nx->bufferposition:%d it->bufferposition:%d\n",
626 nx->bufferposition,it->bufferposition);
627
628 for(int i=0;i<MAXAVSTREAMS;++i)
629 if (sh.stream[i])
630 fprintf(stderr,"stream %d%s, itemlist.size():%lu\n",
631 i,(sh.stream[i]==sd)?"*":"",sh.stream[i]->itemlist().size());
632
633 abort();
634 }
635
636 if (bytes>0)
637 {
638 pts_t pts=audiopts[a]-audiooffset[a];
639 //fprintf(stderr, "mux.put audio %d %lld\n", bytes, pts);
640 mux.putpacket(audiostream(a),sd->getdata(),bytes,pts,pts,MUXER_FLAG_KEY);
641
642 sd->discard(bytes);
643 }
644 it=nx;
645 }
646
647 if (stopped)
648 sh.delstream(audiostream(a));
649 else
650 haveaudio=true;
651 }
652
653 if (!vsd &&!haveaudio)
654 break;
655 }
656
657 if ((stop>nextseqheader(start)) && idx[idx.indexnr(stop-1)].isbframe())
658 // we didn't catch the last picture(s) yet
659 {
660 int startrecode=stop-1;
661 while (startrecode>0 && idx[idx.indexnr(startrecode-1)].isbframe())
662 --startrecode;
663 recodevideo(mux,startrecode,stop,videooffset,savedpics,savepics,log);
664 }
665
666 // output info on audio stream timings
667 if (log)
668 for (int a=0;a<MAXAUDIOSTREAMS;++a)
669 if (mux.streampresent(audiostream(a)))
670 {
671 float starts=float(audiostartpts[a]-videostartpts)/90.;
672 float stops=float(audiostoppts[a]-videostoppts)/90.;
673 float shift=float(audiooffset[a]-videooffset)/90.;
674
675 if (starts >= shift) {
676 log->printinfo(QCoreApplication::translate("mpgfile", "Audio channel %1: starts %2 milliseconds after video")
677 .arg(a+1)
678 .arg(fabsf(starts-shift), 0, 'f', 3));
679 } else {
680 log->printinfo(QCoreApplication::translate("mpgfile", "Audio channel %1: starts %2 milliseconds before video")
681 .arg(a+1)
682 .arg(fabsf(starts-shift), 0, 'f', 3));
683 }
684
685 if (stops >= shift) {
686 log->printinfo(QCoreApplication::translate("mpgfile", "Audio channel %1: stops %2 milliseconds after video")
687 .arg(a+1)
688 .arg(fabsf(stops-shift), 0, 'f', 3));
689 } else {
690 log->printinfo(QCoreApplication::translate("mpgfile", "Audio channel %1: stops %2 milliseconds before video")
691 .arg(a+1)
692 .arg(fabsf(stops-shift), 0, 'f', 3));
693 }
694
695 log->printinfo(QCoreApplication::translate("mpgfile", "Audio channel %1: delayed %2 milliseconds")
696 .arg(a+1)
697 .arg(shift, 0, 'f', 3));
698 log->print("");
699 }
700
701 mux.setpts(VIDEOSTREAM, videostoppts-videooffset);
702 for(int a=0;a<MAXAUDIOSTREAMS;++a)
703 mux.setpts(audiostream(a), audiostoppts[a]-audiooffset[a]);
704 }
705
706 void mpgfile::recodevideo(muxer &mux, int start, int stop, pts_t offset,int savedpics,int savepics, logoutput *log)
707 {
708 if (log) {
709 #if QT_VERSION >= 0x050000
710 log->printinfo(QCoreApplication::translate("mpgfile", "Recoding %n pictures", "", stop-start));
711 #else
712 log->printinfo(QCoreApplication::translate("mpgfile", "Recoding %n pictures", "", QCoreApplication::CodecForTr, stop-start));
713 #endif
714 }
715
716 std::list<avframe*> framelist;
717 decodegop(start,stop,framelist);
718
719 AVCodecContext *avcc=s[VIDEOSTREAM].avcc;
720 if (!avcc)
721 return;
722 s[VIDEOSTREAM].setvideoencodingparameters(time_base_num, time_base_den, !framelist.empty() ? (*framelist.front())->interlaced_frame : 0);
723
724 if (int rv=avcodec_open2(avcc, s[VIDEOSTREAM].enc, NULL))
725 {
726 if (log) {
727 //: Placeholder will be replaced with return value (integer)
728 log->printerror(QCoreApplication::translate("mpgfile", "avcodec_open(mpeg2video_encoder) returned %1").arg(rv));
729 }
730 return ;
731 }
732
733 buffer m2v(4<<20);
734
735 int p=0;
736 int outpicture=start;
737 pts_t startpts=idx[idx.indexnr(start)].getpts();
738 while (outpicture<stop)
739 {
740 AVPacket* pkt = av_packet_alloc();
741 u_int8_t *buf=(u_int8_t*)m2v.writeptr();
742
743 pkt->data = buf;
744 pkt->size = m2v.getsize();
745
746 if (!framelist.empty())
747 {
748 avframe &f=*framelist.front();
749
750 f->pts=idx[idx.indexnr(start+p)].getpts()-startpts;
751 f->coded_picture_number=f->display_picture_number=p;
752 f->key_frame=(p==0)?1:0;
753 f->pict_type=(p==0)?AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
754 avcodec_send_frame(avcc, f);
755
756 delete framelist.front();
757 framelist.pop_front();
758 ++p;
759
760 if (avcodec_receive_packet(avcc, pkt) != 0) {
761 av_packet_free(&pkt);
762 continue;
763 }
764 }
765 else
766 {
767 fprintf(stderr,"trying to call avcodec_encode_video with frame=0\n");
768 avcodec_send_frame(avcc, NULL);
769 fprintf(stderr,"...back I am.\n");
770
771 if (avcodec_receive_packet(avcc, pkt) != 0) {
772 av_packet_free(&pkt);
773 break;
774 }
775 }
776
777 pts_t vidpts=idx[idx.indexnr(outpicture)].getpts()-offset;
778 pts_t viddts=mux.getdts(VIDEOSTREAM);
779 mux.setdts(VIDEOSTREAM,vidpts);
780 fixtimecode(pkt->data, pkt->size, vidpts);
781 mux.putpacket(VIDEOSTREAM, pkt->data, pkt->size, vidpts, viddts,
782 (pkt->flags & AV_PKT_FLAG_KEY)?MUXER_FLAG_KEY:0 );
783 ++outpicture;
784
785 if (log && savepics>0)
786 log->setprogress(++savedpics*1000/savepics);
787
788 av_packet_free(&pkt);
789 }
790
791 for(std::list<avframe*>::iterator fit=framelist.begin();fit!=framelist.end();++fit)
792 delete *fit;
793 avcodec_close(avcc);
794 }
795
796 void mpgfile::fixtimecode(uint8_t *buf, int len, pts_t pts)
797 {
798 int frc=-1;
799 int i=0;
800 for (;;)
801 {
802 if (i+8>len)
803 return;
804 else if (buf[i+2]&0xfe)
805 i+=3;
806 else if (buf[i]!=0 || buf[i+1]!=0 || buf[i+2]!=1)
807 i+=1;
808 else if (buf[i+3]==0xb3)
809 { // sequence header
810 frc=buf[i+7]&0x0f;
811 i+=12;
812 }
813 else if (buf[i+3]==0xb8) // GOP header
814 break;
815 else
816 i+=4;
817 }
818 buf+=i;
819 buf[4]=0x00;
820 buf[5]=0x00;
821 buf[6]=0x08;
822 buf[7]&=0x7f;
823 if (frc==-1)
824 return;
825 if (frc==1 || frc==4 || frc==7)
826 ++frc; // use nearest integer
827 int framerate=27000000/frameratescr[frc];
828 int ss=pts/90000;
829 int mm=ss/60; ss %= 60;
830 int hh=mm/60; mm %= 60;
831 int pp=pts%90000;
832 pp=(pp*framerate)/90000;
833 buf[4] = ((hh<<2) & 0x7c) | ((mm>>4) & 0x03);
834 buf[5] = ((mm<<4) & 0xf0) | ((ss>>3) & 0x07) | 0x08;
835 buf[6] = ((ss<<5) & 0xe0) | ((pp>>1) & 0x1f);
836 buf[7] |= (pp<<7) & 0x80;
837 }
838
839 // general purpose utility function to
840 // read a binary file to memory for further processing
841 // ATTENTION: BE SURE YOU HAVE ENOUGH!!! */
842 ssize_t mpgfile::readfile(std::string filename, uint8_t **buffer) {
843
844 FILE *pFile;
845 size_t len, lSize;
846
847 pFile = fopen(filename.c_str() , "rb");
848 if (pFile==NULL) return -1;
849
850 // obtain file size
851 fseek (pFile , 0 , SEEK_END);
852 lSize = ftell(pFile);
853 rewind(pFile);
854
855 // allocate memory to contain the whole file
856 *buffer = (uint8_t*) malloc(sizeof(uint8_t)*lSize);
857 if (buffer == NULL) {
858 fclose(pFile);
859 return -2;
860 }
861
862 // copy the file into the buffer
863 len = fread(*buffer, 1, lSize, pFile);
864 if (len != lSize) {
865 fclose(pFile);
866 free(buffer);
867 return -3;
868 }
869
870 fclose(pFile);
871 return len;
872
873 }