/
mpeg2fix.cpp
2700 lines (2291 loc) · 82.1 KB
/
mpeg2fix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//To Do
//support missing audio frames
//support analyze-only mode
// C headers
#include <cstdlib>
#include <cstdio>
// POSIC headers
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <stdint.h>
#include <sys/stat.h>
#include "config.h"
#include "mpeg2fix.h"
#include <QList>
#include <QQueue>
#include <QMap>
#include <QFileInfo>
#include "mythlogging.h"
#include "mythdate.h"
#include "mthread.h"
#ifdef USING_MINGW
#include <winsock2.h>
#else
#include <netinet/in.h>
#endif
#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif
#define ATTR_ALIGN(align) __attribute__ ((__aligned__ (align)))
static void *my_malloc(unsigned size, mpeg2_alloc_t reason)
{
(void)reason;
char * buf;
if (size)
{
buf = (char *) malloc (size + 63 + sizeof (void **));
if (buf)
{
char * align_buf;
memset(buf, 0, size + 63 + sizeof (void **));
align_buf = buf + 63 + sizeof (void **);
align_buf -= (long)align_buf & 63;
*(((void **)align_buf) - 1) = buf;
return align_buf;
}
}
return NULL;
}
static void my_av_print(void *ptr, int level, const char* fmt, va_list vl)
{
(void) ptr;
static QString full_line("");
char str[256];
if (level > AV_LOG_INFO)
return;
vsprintf(str, fmt, vl);
full_line += QString(str);
if (full_line.endsWith("\n"))
{
full_line.truncate(full_line.length() - 1);
LOG(VB_GENERAL, LOG_INFO, full_line);
full_line = QString("");
}
}
static QString PtsTime(int64_t pts)
{
bool is_neg = false;
if (pts < 0)
{
pts = -pts;
is_neg = true;
}
QString msg;
return(msg.sprintf("%s%02d:%02d:%02d.%03d", (is_neg) ? "-" : "",
(unsigned int)(pts / 90000.) / 3600,
((unsigned int)(pts / 90000.) % 3600) / 60,
((unsigned int)(pts / 90000.) % 3600) % 60,
(((unsigned int)(pts / 90.) % 3600000) % 60000) % 1000));
}
PTSOffsetQueue::PTSOffsetQueue(int vidid, QList<int> keys, int64_t initPTS)
{
QList<int>::iterator it;
poq_idx_t idx;
vid_id = vidid;
keyList = keys;
keyList.append(vid_id);
idx.newPTS = initPTS;
idx.pos_pts = 0;
idx.framenum = 0;
idx.type = 0;
for (it = keyList.begin(); it != keyList.end(); ++it)
offset[*it].push_back(idx);
}
int64_t PTSOffsetQueue::Get(int idx, AVPacket *pkt)
{
QList<poq_idx_t>::iterator it;
int64_t value = offset[idx].first().newPTS;
bool done = false;
if (!pkt)
return value;
//Be aware: the key for offset can be either a file position OR a PTS
//The type is defined by type (0==PTS, 1==Pos)
while (offset[idx].count() > 1 && !done)
{
it = ++offset[idx].begin();
if ((((*it).type == 0) && (pkt->pts >= (*it).pos_pts) /* PTS type */) ||
(((*it).type == 1) /* Pos type */ &&
((pkt->pos >= (*it).pos_pts) || (pkt->duration > (*it).framenum))))
{
offset[idx].pop_front();
value = offset[idx].first().newPTS;
}
else
done = true;
}
return value;
}
void PTSOffsetQueue::SetNextPTS(int64_t newPTS, int64_t atPTS)
{
QList<int>::iterator it;
poq_idx_t idx;
idx.newPTS = newPTS;
idx.pos_pts = atPTS;
idx.type = 0;
idx.framenum = 0;
for (it = keyList.begin(); it != keyList.end(); ++it)
offset[*it].push_back(idx);
}
void PTSOffsetQueue::SetNextPos(int64_t newPTS, AVPacket &pkt)
{
QList<int>::iterator it;
int64_t delta = MPEG2fixup::diff2x33(newPTS, offset[vid_id].last().newPTS);
poq_idx_t idx;
idx.pos_pts = pkt.pos;
idx.framenum = pkt.duration;
idx.type = 1;
LOG(VB_FRAME, LOG_INFO, QString("Offset %1 -> %2 (%3) at %4")
.arg(PtsTime(offset[vid_id].last().newPTS))
.arg(PtsTime(newPTS)).arg(PtsTime(delta)).arg(pkt.pos));
for (it = keyList.begin(); it != keyList.end(); ++it)
{
idx.newPTS = newPTS;
offset[*it].push_back(idx);
idx.newPTS = delta;
orig[*it].push_back(idx);
}
}
int64_t PTSOffsetQueue::UpdateOrigPTS(int idx, int64_t &origPTS, AVPacket &pkt)
{
int64_t delta = 0;
QList<poq_idx_t> *dltaList = &orig[idx];
while (dltaList->count() &&
(pkt.pos >= dltaList->first().pos_pts ||
pkt.duration > dltaList->first().framenum))
{
if (dltaList->first().newPTS >= 0)
ptsinc((uint64_t *)&origPTS, 300 * dltaList->first().newPTS);
else
ptsdec((uint64_t *)&origPTS, -300 * dltaList->first().newPTS);
delta += dltaList->first().newPTS;
dltaList->pop_front();
LOG(VB_PROCESS, LOG_INFO,
QString("Moving PTS offset of stream %1 by %2")
.arg(idx).arg(PtsTime(delta)));
}
return (delta);
}
MPEG2fixup::MPEG2fixup(const QString &inf, const QString &outf,
frm_dir_map_t *deleteMap,
const char *fmt, int norp, int fixPTS, int maxf,
bool showprog, int otype, void (*update_func)(float),
int (*check_func)())
{
displayFrame = 0;
infile = inf;
rx.outfile = outf;
rx.done = 0;
format = fmt;
no_repeat = norp;
fix_PTS = fixPTS;
maxframes = maxf;
rx.otype = otype;
real_file_end = file_end = false;
use_secondary = false;
framenum = 0;
discard = 0;
if (deleteMap && deleteMap->count())
{
delMap = *deleteMap;
if (delMap.contains(0))
{
discard = 1;
delMap.remove(0);
}
if (delMap.begin().value() == MARK_CUT_END)
discard = 1;
use_secondary = true;
}
ext_count = 0;
vid_id = -1;
mpeg2_malloc_hooks(my_malloc, NULL);
header_decoder = mpeg2_init();
img_decoder = mpeg2_init();
av_register_all();
av_log_set_callback(my_av_print);
pthread_mutex_init(&rx.mutex, NULL);
pthread_cond_init(&rx.cond, NULL);
//await multiplexer initialization (prevent a deadlock race)
pthread_mutex_lock(&rx.mutex);
pthread_create(&thread, NULL, ReplexStart, this);
pthread_cond_wait(&rx.cond, &rx.mutex);
pthread_mutex_unlock(&rx.mutex);
//initialize progress stats
showprogress = showprog;
update_status = update_func;
check_abort = check_func;
if (showprogress || update_status)
{
if (update_status)
{
status_update_time = 20;
update_status(0);
}
else
status_update_time = 5;
statustime = MythDate::current();
statustime = statustime.addSecs(status_update_time);
const QFileInfo finfo(inf);
filesize = finfo.size();
}
}
MPEG2fixup::~MPEG2fixup()
{
mpeg2_close(header_decoder);
mpeg2_close(img_decoder);
if (inputFC)
avformat_close_input(&inputFC);
MPEG2frame *tmpFrame;
while (vFrame.count())
{
tmpFrame = vFrame.takeFirst();
delete tmpFrame;
}
while (vSecondary.count())
{
tmpFrame = vSecondary.takeFirst();
delete tmpFrame;
}
for (FrameMap::Iterator it = aFrame.begin(); it != aFrame.end(); it++)
{
FrameList *af = (*it);
while (af->count())
{
tmpFrame = af->takeFirst();
delete tmpFrame;
}
delete af;
}
while (framePool.count())
delete framePool.dequeue();
}
//#define MPEG2trans_DEBUG
#define MATCH_HEADER(ptr) (((ptr)[0] == 0x00) && ((ptr)[1] == 0x00) && ((ptr)[2] == 0x01))
static void SETBITS(unsigned char *ptr, long value, int num)
{
static int sb_pos;
static unsigned char *sb_ptr = 0;
uint32_t sb_long, mask;
int offset, offset_r, offset_b;
if (ptr != 0)
{
sb_ptr = ptr;
sb_pos = 0;
}
offset = sb_pos >> 3;
offset_r = sb_pos & 0x07;
offset_b = 32 - offset_r;
mask = ~(((1 << num) - 1) << (offset_b - num));
sb_long = ntohl(*((uint32_t *) (sb_ptr + offset)));
value = value << (offset_b - num);
sb_long = (sb_long & mask) + value;
*((uint32_t *)(sb_ptr + offset)) = htonl(sb_long);
}
void MPEG2fixup::dec2x33(int64_t *pts1, int64_t pts2)
{
*pts1 = udiff2x33(*pts1, pts2);
}
void MPEG2fixup::inc2x33(int64_t *pts1, int64_t pts2)
{
*pts1 = (*pts1 + pts2) % MAX_PTS;
}
int64_t MPEG2fixup::udiff2x33(int64_t pts1, int64_t pts2)
{
int64_t diff;
diff = pts1 - pts2;
if (diff < 0){
diff = MAX_PTS + diff;
}
return (diff % MAX_PTS);
}
int64_t MPEG2fixup::diff2x33(int64_t pts1, int64_t pts2)
{
switch (cmp2x33(pts1, pts2))
{
case 0:
return 0;
break;
case 1:
case -2:
return (pts1 - pts2);
break;
case 2:
return (pts1 + MAX_PTS - pts2);
break;
case -1:
return (pts1 - (pts2 + MAX_PTS));
break;
}
return 0;
}
int64_t MPEG2fixup::add2x33(int64_t pts1, int64_t pts2)
{
int64_t tmp = pts1 + pts2;
if (tmp >= 0)
return (pts1 + pts2) % MAX_PTS;
return (tmp + MAX_PTS);
}
int MPEG2fixup::cmp2x33(int64_t pts1, int64_t pts2)
{
int ret;
if (pts1 > pts2)
{
if ((uint64_t)(pts1 - pts2) > MAX_PTS/2)
ret = -1;
else
ret = 1;
}
else if (pts1 == pts2)
ret = 0;
else
{
if ((uint64_t)(pts2 - pts1) > MAX_PTS/2)
ret = 2;
else
ret = -2;
}
return ret;
}
int MPEG2fixup::FindMPEG2Header(uint8_t *buf, int size, uint8_t code)
{
int i;
for (i = 0; i < size; i++)
{
if (MATCH_HEADER(buf + i) && buf[i + 3] == code)
return i;
}
return 0;
}
//fill_buffers will signal the main thread to start decoding again as soon
//as it runs out of buffers. It will then wait for the buffer to completely
//fill before returning. In this way, the 2 threads are never running
// concurrently
static int fill_buffers(void *r, int finish)
{
MPEG2replex *rx = (MPEG2replex *)r;
if (finish)
return 0;
return (rx->WaitBuffers());
}
MPEG2replex::MPEG2replex() :
done(0), otype(0),
ext_count(0), mplex(0)
{
memset(&vrbuf, 0, sizeof(vrbuf));
memset(extrbuf, 0, sizeof(extrbuf));
memset(&index_vrbuf, 0, sizeof(index_vrbuf));
memset(index_extrbuf, 0, sizeof(index_extrbuf));
memset(exttype, 0, sizeof(exttype));
memset(exttypcnt, 0, sizeof(exttypcnt));
memset(extframe, 0, sizeof(extframe));
memset(&seq_head, 0, sizeof(seq_head));
}
MPEG2replex::~MPEG2replex()
{
if (vrbuf.size)
ring_destroy(&vrbuf);
if (index_vrbuf.size)
ring_destroy(&index_vrbuf);
for (int i = 0; i < ext_count; i++)
{
if (extrbuf[i].size)
ring_destroy(&extrbuf[i]);
if (index_extrbuf[i].size)
ring_destroy(&index_extrbuf[i]);
}
}
int MPEG2replex::WaitBuffers()
{
pthread_mutex_lock( &mutex );
while (1)
{
int i, ok = 1;
if (ring_avail(&index_vrbuf) < sizeof(index_unit))
ok = 0;
for (i = 0; i < ext_count; i++)
if (ring_avail(&index_extrbuf[i]) < sizeof(index_unit))
ok = 0;
if (ok || done)
break;
pthread_cond_signal(&cond);
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
if (done)
{
finish_mpg(mplex);
pthread_exit(NULL);
}
return 0;
}
void *MPEG2fixup::ReplexStart(void *data)
{
MThread::ThreadSetup("MPEG2Replex");
MPEG2fixup *m2f = (MPEG2fixup *) data;
m2f->rx.Start();
MThread::ThreadCleanup();
return NULL;
}
void MPEG2replex::Start()
{
int start = 1;
multiplex_t mx;
//array defines number of allowed audio streams
// note that although only 1 stream is currently supported, multiplex.c
// expects the size to by N_AUDIO
int ext_ok[N_AUDIO];
int video_ok = 0;
//seq_head should be set only for the 1st sequence header. If a new
// seq header comes which is different, we are screwed.
int video_delay = 0, audio_delay = 0;
int fd_out;
memset(&mx, 0, sizeof(mx));
memset(ext_ok, 0, sizeof(ext_ok));
mx.priv = (void *)this;
fd_out = open(outfile.toLocal8Bit().constData(),
O_WRONLY | O_CREAT | O_TRUNC | O_LARGEFILE, 0644);
//await buffer fill
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
mplex = &mx;
init_multiplex(&mx, &seq_head, extframe, exttype, exttypcnt,
video_delay, audio_delay, fd_out, fill_buffers,
&vrbuf, &index_vrbuf, extrbuf, index_extrbuf, otype);
setup_multiplex(&mx);
while (1)
{
check_times( &mx, &video_ok, ext_ok, &start);
write_out_packs( &mx, video_ok, ext_ok);
}
}
#define INDEX_BUF (sizeof(index_unit) * 200)
void MPEG2fixup::InitReplex()
{
// index_vrbuf contains index_units which describe a video frame
// it also contains the start pos of the next frame
// index_arbuf only uses, pts, framesize, length, start, (active, err)
//this should support > 100 frames
uint32_t memsize = vFrame.first()->mpeg2_seq.width *
vFrame.first()->mpeg2_seq.height * 10;
ring_init(&rx.vrbuf, memsize);
ring_init(&rx.index_vrbuf, INDEX_BUF);
memset(rx.exttype, 0, sizeof(rx.exttype));
memset(rx.exttypcnt, 0, sizeof(rx.exttypcnt));
int mp2_count = 0, ac3_count = 0;
for (FrameMap::Iterator it = aFrame.begin(); it != aFrame.end(); it++)
{
int i = aud_map[it.key()];
AVDictionaryEntry *metatag =
av_dict_get(inputFC->streams[it.key()]->metadata,
"language", NULL, 0);
char *lang = metatag ? metatag->value : (char *)"";
ring_init(&rx.extrbuf[i], memsize / 5);
ring_init(&rx.index_extrbuf[i], INDEX_BUF);
rx.extframe[i].set = 1;
rx.extframe[i].bit_rate = getCodecContext(it.key())->bit_rate;
rx.extframe[i].framesize = (*it)->first()->pkt.size;
strncpy(rx.extframe[i].language, lang, 4);
switch(GetStreamType(it.key()))
{
case AV_CODEC_ID_MP2:
case AV_CODEC_ID_MP3:
rx.exttype[i] = 2;
rx.exttypcnt[i] = mp2_count++;
break;
case AV_CODEC_ID_AC3:
rx.exttype[i] = 1;
rx.exttypcnt[i] = ac3_count++;
break;
}
}
//bit_rate/400
rx.seq_head.bit_rate = vFrame.first()->mpeg2_seq.byte_rate / 50;
rx.seq_head.frame_rate = (vFrame.first()->mpeg2_seq.frame_period +
26999999ULL) / vFrame.first()->mpeg2_seq.frame_period;
rx.ext_count = ext_count;
}
void MPEG2fixup::FrameInfo(MPEG2frame *f)
{
QString msg = QString("Id:%1 %2 V:%3").arg(f->pkt.stream_index)
.arg(PtsTime(f->pkt.pts))
.arg(ring_free(&rx.index_vrbuf) / sizeof(index_unit));
if (ext_count)
{
msg += " EXT:";
for (int i = 0; i < ext_count; i++)
msg += QString(" %2")
.arg(ring_free(&rx.index_extrbuf[i]) / sizeof(index_unit));
}
LOG(VB_RPLXQUEUE, LOG_INFO, msg);
}
int MPEG2fixup::AddFrame(MPEG2frame *f)
{
index_unit iu;
ringbuffer *rb = 0, *rbi = 0;
int id = f->pkt.stream_index;
memset(&iu, 0, sizeof(index_unit));
iu.frame_start = 1;
if (id == vid_id)
{
rb = &rx.vrbuf;
rbi = &rx.index_vrbuf;
iu.frame = GetFrameTypeN(f);
iu.seq_header = f->isSequence;
iu.gop = f->isGop;
iu.gop_off = f->gopPos - f->pkt.data;
iu.frame_off = f->framePos - f->pkt.data;
iu.dts = f->pkt.dts * 300;
}
else if (GetStreamType(id) == AV_CODEC_ID_MP2 ||
GetStreamType(id) == AV_CODEC_ID_MP3 ||
GetStreamType(id) == AV_CODEC_ID_AC3)
{
rb = &rx.extrbuf[aud_map[id]];
rbi = &rx.index_extrbuf[aud_map[id]];
iu.framesize = f->pkt.size;
}
if (!rb || !rbi)
{
LOG(VB_GENERAL, LOG_ERR, "Ringbuffer pointers empty. No stream found");
return 1;
}
iu.active = 1;
iu.length = f->pkt.size;
iu.pts = f->pkt.pts * 300;
pthread_mutex_lock( &rx.mutex );
FrameInfo(f);
while (ring_free(rb) < (unsigned int)f->pkt.size ||
ring_free(rbi) < sizeof(index_unit))
{
int i, ok = 1;
if (rbi != &rx.index_vrbuf &&
ring_avail(&rx.index_vrbuf) < sizeof(index_unit))
ok = 0;
for (i = 0; i < ext_count; i++)
if (rbi != &rx.index_extrbuf[i] &&
ring_avail(&rx.index_extrbuf[i]) < sizeof(index_unit))
ok = 0;
if (!ok && ring_free(rb) < (unsigned int)f->pkt.size &&
ring_free(rbi) >= sizeof(index_unit))
{
// increase memory to avoid deadlock
unsigned int inc_size = 10 * (unsigned int)f->pkt.size;
LOG(VB_GENERAL, LOG_NOTICE,
QString("Increasing ringbuffer size by %1 to avoid deadlock")
.arg(inc_size));
if (!ring_reinit(rb, rb->size + inc_size))
ok = 1;
}
if (!ok)
{
pthread_mutex_unlock( &rx.mutex );
//deadlock
LOG(VB_GENERAL, LOG_ERR,
"Deadlock detected. One buffer is full when "
"the other is empty! Aborting");
return 1;
}
pthread_cond_signal(&rx.cond);
pthread_cond_wait(&rx.cond, &rx.mutex);
FrameInfo(f);
}
if (ring_write(rb, f->pkt.data, f->pkt.size)<0){
pthread_mutex_unlock( &rx.mutex );
LOG(VB_GENERAL, LOG_ERR,
QString("Ring buffer overflow %1").arg(rb->size));
return 1;
}
if (ring_write(rbi, (uint8_t *)&iu, sizeof(index_unit))<0){
pthread_mutex_unlock( &rx.mutex );
LOG(VB_GENERAL, LOG_ERR,
QString("Ring buffer overflow %1").arg(rbi->size));
return 1;
}
pthread_mutex_unlock(&rx.mutex);
last_written_pos = f->pkt.pos;
return 0;
}
bool MPEG2fixup::InitAV(QString inputfile, const char *type, int64_t offset)
{
int ret;
QByteArray ifarray = inputfile.toLocal8Bit();
const char *ifname = ifarray.constData();
AVInputFormat *fmt = NULL;
if (type)
fmt = av_find_input_format(type);
// Open recording
LOG(VB_GENERAL, LOG_INFO, QString("Opening %1").arg(inputfile));
inputFC = NULL;
ret = avformat_open_input(&inputFC, ifname, fmt, NULL);
if (ret)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Couldn't open input file, error #%1").arg(ret));
return false;
}
mkvfile = !strcmp(inputFC->iformat->name, "mkv") ? 1 : 0;
if (offset)
av_seek_frame(inputFC, vid_id, offset, AVSEEK_FLAG_BYTE);
// Getting stream information
ret = avformat_find_stream_info(inputFC, NULL);
if (ret < 0)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Couldn't get stream info, error #%1").arg(ret));
avformat_close_input(&inputFC);
inputFC = NULL;
return false;
}
// Dump stream information
if (VERBOSE_LEVEL_CHECK(VB_GENERAL, LOG_INFO))
av_dump_format(inputFC, 0, ifname, 0);
for (unsigned int i = 0; i < inputFC->nb_streams; i++)
{
switch (inputFC->streams[i]->codec->codec_type)
{
case AVMEDIA_TYPE_VIDEO:
if (vid_id == -1)
vid_id = i;
break;
case AVMEDIA_TYPE_AUDIO:
if (inputFC->streams[i]->codec->channels == 0)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Skipping invalid audio stream: %1").arg(i));
break;
}
if (inputFC->streams[i]->codec->codec_id == AV_CODEC_ID_AC3 ||
inputFC->streams[i]->codec->codec_id == AV_CODEC_ID_MP3 ||
inputFC->streams[i]->codec->codec_id == AV_CODEC_ID_MP2)
{
aud_map[i] = ext_count++;
aFrame[i] = new FrameList();
}
else
LOG(VB_GENERAL, LOG_ERR,
QString("Skipping unsupported audio stream: %1")
.arg(inputFC->streams[i]->codec->codec_id));
break;
default:
LOG(VB_GENERAL, LOG_ERR,
QString("Skipping unsupported codec %1 on stream %2")
.arg(inputFC->streams[i]->codec->codec_type).arg(i));
break;
}
}
return true;
}
void MPEG2fixup::SetFrameNum(uint8_t *ptr, int num)
{
SETBITS(ptr + 4, num, 10);
}
void MPEG2fixup::AddSequence(MPEG2frame *frame1, MPEG2frame *frame2)
{
if (frame1->isSequence || !frame2->isSequence)
return;
int head_size = (frame2->framePos - frame2->pkt.data);
frame1->ensure_size(frame1->pkt.size + head_size);
memmove(frame1->pkt.data + head_size, frame1->pkt.data, frame1->pkt.size);
memcpy(frame1->pkt.data, frame2->pkt.data, head_size);
frame1->pkt.size += head_size;
ProcessVideo(frame1, header_decoder);
#if 0
if (VERBOSE_LEVEL_CHECK(VB_PROCESS, LOG_ANY))
{
static int count = 0;
QString filename = QString("hdr%1.yuv").arg(count++);
WriteFrame(filename, &frame1->pkt);
}
#endif
}
int MPEG2fixup::ProcessVideo(MPEG2frame *vf, mpeg2dec_t *dec)
{
int state = -1;
int last_pos = 0;
mpeg2_info_t *info;
if (dec == header_decoder)
{
mpeg2_reset(dec, 0);
vf->isSequence = 0;
vf->isGop = 0;
}
info = (mpeg2_info_t *)mpeg2_info(dec);
mpeg2_buffer(dec, vf->pkt.data, vf->pkt.data + vf->pkt.size);
while (state != STATE_PICTURE)
{
state = mpeg2_parse(dec);
if (dec == header_decoder)
{
switch (state)
{
case STATE_SEQUENCE:
case STATE_SEQUENCE_MODIFIED:
case STATE_SEQUENCE_REPEATED:
memcpy(&vf->mpeg2_seq, info->sequence,
sizeof(mpeg2_sequence_t));
vf->isSequence = 1;
break;
case STATE_GOP:
memcpy(&vf->mpeg2_gop, info->gop, sizeof(mpeg2_gop_t));
vf->isGop = 1;
vf->gopPos = vf->pkt.data + last_pos;
//pd->adjustFrameCount=0;
break;
case STATE_PICTURE:
memcpy(&vf->mpeg2_pic, info->current_picture,
sizeof(mpeg2_picture_t));
vf->framePos = vf->pkt.data + last_pos;
break;
case STATE_BUFFER:
LOG(VB_GENERAL, LOG_WARNING,
"Warning: partial frame found!");
return 1;
}
}
else if (state == STATE_BUFFER)
{
WriteData("abort.dat", vf->pkt.data, vf->pkt.size);
LOG(VB_GENERAL, LOG_ERR,
QString("Failed to decode frame. Position was: %1")
.arg(last_pos));
return -1;
}
last_pos = (vf->pkt.size - mpeg2_getpos(dec)) - 4;
}
if (dec != header_decoder)
{
while (state != STATE_BUFFER)
state = mpeg2_parse(dec);
if (info->display_picture)
{
// This is a hack to force libmpeg2 to finish writing out the slice
// without it, the final row doesn't get put into the disp_pic
// (for B-frames only).
// 0xb2 is 'user data' and is actually illegal between pic
// headers, but it is just discarded by libmpeg2
uint8_t tmp[8] = {0x00, 0x00, 0x01, 0xb2, 0xff, 0xff, 0xff, 0xff};
mpeg2_buffer(dec, tmp, tmp + 8);
mpeg2_parse(dec);
}
}
if (VERBOSE_LEVEL_CHECK(VB_DECODE, LOG_INFO))
{
QString msg = QString("");
#if 0
msg += QString("unused:%1 ") .arg(vf->pkt.size - mpeg2_getpos(dec));
#endif
if (vf->isSequence)
msg += QString("%1x%2 P:%3 ").arg(info->sequence->width)
.arg(info->sequence->height).arg(info->sequence->frame_period);
if (info->gop)
{
QString gop;
gop.sprintf("%02d:%02d:%02d:%03d ",
info->gop->hours, info->gop->minutes,
info->gop->seconds, info->gop->pictures);
msg += gop;
}
if (info->current_picture) {
int ct = info->current_picture->flags & PIC_MASK_CODING_TYPE;
char coding_type = (ct == PIC_FLAG_CODING_TYPE_I) ? 'I' :
((ct == PIC_FLAG_CODING_TYPE_P) ? 'P' :
((ct == PIC_FLAG_CODING_TYPE_B) ? 'B' :
((ct == PIC_FLAG_CODING_TYPE_D) ?'D' : 'X')));
char top_bottom = (info->current_picture->flags &
PIC_FLAG_TOP_FIELD_FIRST) ? 'T' : 'B';
char progressive = (info->current_picture->flags &
PIC_FLAG_PROGRESSIVE_FRAME) ? 'P' : '_';
msg += QString("#%1 fl:%2%3%4%5%6 ")
.arg(info->current_picture->temporal_reference)
.arg(info->current_picture->nb_fields)
.arg(coding_type)
.arg(top_bottom)
.arg(progressive)
.arg(info->current_picture->flags >> 4, 0, 16);
}
msg += QString("pos: %1").arg(vf->pkt.pos);
LOG(VB_DECODE, LOG_INFO, msg);
}
return 0;
}
void MPEG2fixup::WriteFrame(QString filename, MPEG2frame *f)
{
MPEG2frame *tmpFrame = GetPoolFrame(f);
if (tmpFrame == NULL)
return;
if (!tmpFrame->isSequence)
{
for (FrameList::Iterator it = vFrame.begin(); it != vFrame.end(); it++)
{
if ((*it)->isSequence)
{
AddSequence(tmpFrame, *it);
break;
}
}
}
WriteFrame(filename, &tmpFrame->pkt);
framePool.enqueue(tmpFrame);
}
void MPEG2fixup::WriteFrame(QString filename, AVPacket *pkt)
{
MPEG2frame *tmpFrame = GetPoolFrame(pkt);
if (tmpFrame == NULL)
return;
QString fname = filename + ".enc";
WriteData(fname, pkt->data, pkt->size);
mpeg2dec_t *tmp_decoder = mpeg2_init();
mpeg2_info_t *info = (mpeg2_info_t *)mpeg2_info(tmp_decoder);
while (!info->display_picture)
{
if (ProcessVideo(tmpFrame, tmp_decoder))
{
delete tmpFrame;
return;
}
}