-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathffmpeg_decoder.cpp
637 lines (577 loc) · 16.1 KB
/
ffmpeg_decoder.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
#include "ffmpeg_decoder.h"
bool logSeeking;
bool logReading = false;
volatile bool ffmpegerror;
extern void my_av_log(void*, int level,const char *fmt,...);
static bool doSeekPos = false;
#define MAX_WIDTH 1920
#define MAX_HEIGHT 1080
#ifdef FORCE_CODECWIDTH
#define FRAMEWIDTH pCodecCtx->width
#define FRAMEHEIGHT pCodecCtx->height
#else
#define FRAMEWIDTH pFrame->width
#define FRAMEHEIGHT pFrame->height
#endif
void my_av_dolog(void * /*ptr*/, int level, const char *fmt,va_list vl)
{
if( level >= 16 /*AV_LOG_ERROR*/ )
return;
static char line[1024];
vsnprintf( line,sizeof(line),fmt,vl);
int iLen = strlen(line);
if( line[iLen-1] == '\n' )
line[iLen-1] = '\0';
//fprintf(stderr,line);
esyslog("ffmpeg(%d): %s",level,line);
}
#ifdef USE_FFMPEG
extern cFileName *cfn;
extern cNoadIndexFile *cIF;
#ifdef USE_AVIOCONTEXT
static int noad_read_packet(void *h, uint8_t *buf, int size)
{
FFMPegDecoder *decoder = (FFMPegDecoder*)(h);
if( decoder->__bufBytes <= 0 )
{
if( decoder->ffmpeg_index >= 0 )
{
if( !decoder->cont_reading )
if( decoder->ffmpeg_Lastindex == decoder->ffmpeg_index )
return 0;
bool Independent;
if( !cIF->Get(decoder->ffmpeg_index,&decoder->ffmpegFileNumber, &decoder->ffmpegFileOffset, &Independent, &decoder->ffmpegLength) )
return 0;
if( decoder->ffmpegLength <= 0 )
ffmpegerror = true;
if( logReading )
dsyslog("noad_read read from file, ffmpeg_index = %d (iframe: %s), length = %d",decoder->ffmpeg_index, Independent?"true":"false", decoder->ffmpegLength);
if( decoder->cont_reading )
decoder->ffmpeg_index++;
decoder->ffmpeg_Lastindex = decoder->ffmpeg_index;
}
else
{
if( logReading )
dsyslog("noad_read read from file, ffmpegFileOffset = %ld, length = %d",decoder->ffmpegFileOffset, decoder->ffmpegLength);
if( decoder->ffmpegFileOffset == decoder->ffmpegLastFileOffset )
return 0;
}
cfn->SetOffset( decoder->ffmpegFileNumber, decoder->ffmpegFileOffset);
ReadFrame (cfn->File(), readBuffer, decoder->ffmpegLength, MAXFRAMESIZE);
decoder->__bufBytes = decoder->ffmpegLength;
decoder->__bufPos = readBuffer;
decoder->ffmpegLastFileOffset = decoder->ffmpegFileOffset;
}
if( decoder->__bufBytes > 0 )
{
int cpBytes = size > decoder->__bufBytes?decoder->__bufBytes:size;
memcpy(buf,decoder->__bufPos, cpBytes);
//dsyslog("noad_read --> return %d bytes of %d bytes",cpBytes,__bufBytes);
decoder->__bufPos += cpBytes;
decoder->__bufBytes -= cpBytes;
return cpBytes;
}
return 0;
}
static int noad_write_packet(void */*h*/, uint8_t */*buf*/, int /*size*/)
{
//FFMPegDecoder *decoder = (FFMPegDecoder*)(h->priv_data);
/*
BUF* af = h->priv_data;
int n;
n = min(size, af->buflen-af->bufused);
if(n<0)
return -1;
memcpy(af->buf+af->bufused, buf, n);
af->buf_used+=size;
return n;
*/
return 0;
}
static int64_t noad_seek(void *h, int64_t pos, int whence)
{
FFMPegDecoder *decoder = (FFMPegDecoder*)(h);
// To implement this you need a bufcur element in BUF too
//...
if( whence == AVSEEK_SIZE )
{
return cIF->getVideoFileSize();
}
else if ( whence == SEEK_SET )
{
if( doSeekPos )
decoder->ffmpeg_index = cIF->getIndexForFilepos(pos);
if( logSeeking )
dsyslog("noad-protocol seek to %ld --> index %d",pos,decoder->ffmpeg_index);
decoder->__bufBytes = 0;
}
return pos;
}
#endif
FFMPegDecoder::FFMPegDecoder() :
MPEGDecoder()
{
pFormatCtx = NULL;
//i, videoStream;
pCodecCtx = NULL;
#if LIBAVCODEC_VERSION_MAJOR > 56
pCodecPar = NULL;
#endif
pCodec = NULL;
pFrame = NULL;
__bufBytes = 0;
ffmpeg_index=0;
ffmpeg_Lastindex=0;
cont_reading = false;
av_log_set_callback(my_av_dolog);
av_log_set_level(AV_LOG_ERROR);
#ifdef USE_AVIOCONTEXT
pIOContext = NULL;
#endif
}
FFMPegDecoder::~FFMPegDecoder()
{
decoder_exit();
}
int FFMPegDecoder::decoder_init()
{
// Register all formats and codecs
av_register_all();
#ifdef USE_AVIOCONTEXT
#define IOBUFSIZE (1024L*200L)
iobuffer = (unsigned char*)av_malloc(IOBUFSIZE);
pIOContext = avio_alloc_context(
iobuffer,
IOBUFSIZE,
0,
this,
noad_read_packet,
noad_write_packet,
noad_seek);
#endif
return 0;
}
int FFMPegDecoder::openFile(cFileName *_cfn, cNoadIndexFile *_cIF)
{
cfn =_cfn;
cIF = _cIF;
// Open video file
ffmpeg_index=0;
cont_reading = true;
doSeekPos = true;
#ifdef USE_AVIOCONTEXT
pFormatCtx = avformat_alloc_context();
pFormatCtx->pb = pIOContext;
char somebuf[1024];
sprintf(somebuf, "noad:0x%08lx", (long unsigned int)this);
int openCode = avformat_open_input(&pFormatCtx,"name",NULL,NULL);
if( openCode != 0 )
return -1; // Couldn't open file
#endif
// Retrieve stream information
resetDecoder();
#if LIBAVCODEC_VERSION_MAJOR <57
int openCode2 = av_find_stream_info(pFormatCtx);
#else
int openCode2 = avformat_find_stream_info(pFormatCtx, NULL);
#endif
if(openCode2<0)
return -1; // Couldn't find stream information
// Find the first video stream
#if LIBAVCODEC_VERSION_MAJOR <57
videoStream=-1;
for(i=0; i < (int)pFormatCtx->nb_streams; i++)
{
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
{
videoStream=i;
break;
}
}
#else
videoStream = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &pCodec, 0);
#endif
if(videoStream < 0)
{
esyslog("can't find a video stream!");
return -1;
}
// Get a pointer to the codec context for the video stream
#if LIBAVCODEC_VERSION_MAJOR <57
pCodecCtx=pFormatCtx->streams[videoStream]->codec;
pCodecCtx->flags|=CODEC_FLAG_EMU_EDGE;
if( pCodecCtx->codec_id == CODEC_ID_PROBE )
{
esyslog("can't detect codec for video!");
return -1;
}
#else
pCodecPar=pFormatCtx->streams[videoStream]->codecpar;
if( pCodecPar->codec_id == AV_CODEC_ID_PROBE )
{
esyslog("can't detect codec for video!");
return -1;
}
#endif
//av_close_input_file(pFormatCtx);
// Find the decoder for the video stream
#if LIBAVCODEC_VERSION_MAJOR < 57
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
return -1; // Codec not found
// Inform the codec that we can handle truncated bitstreams -- i.e.,
// bitstreams where frame boundaries can fall in the middle of packets
if(pCodec->capabilities & CODEC_CAP_TRUNCATED)
pCodecCtx->flags|=CODEC_FLAG_TRUNCATED;
#else
pCodec=avcodec_find_decoder(pCodecPar->codec_id);
if(pCodec==NULL)
return -1; // Codec not found
// Create CodecContext from Codec
pCodecCtx= avcodec_alloc_context3(pCodec);
// Inform the codec that we can handle truncated bitstreams -- i.e.,
// bitstreams where frame boundaries can fall in the middle of packets
if(pCodec->capabilities & AV_CODEC_CAP_TRUNCATED)
pCodecCtx->flags|=AV_CODEC_FLAG_TRUNCATED;
#endif
// Open codec
#if LIBAVCODEC_VERSION_MAJOR > 54
if(avcodec_open2(pCodecCtx, pCodec,&avDictionary) < 0)
#else
if(avcodec_open(pCodecCtx, pCodec)<0)
#endif
return -1; // Could not open codec
// Allocate video frame
#if LIBAVCODEC_VERSION_MAJOR < 57
pFrame=avcodec_alloc_frame();
#else
pFrame=av_frame_alloc();
#endif
cont_reading = true;
doSeekPos = false;
dsyslog("init_ffmpeg done" );
return false;
}
int FFMPegDecoder::decoder_exit()
{
// Free the YUV frame
if( pFrame )
{
av_free(pFrame);
pFrame = NULL;
}
// close the file
if( pFormatCtx )
{
#if LIBAVFORMAT_VERSION_MAJOR < 54
av_close_input_file(pFormatCtx);
#else
avformat_close_input(&pFormatCtx);
#endif
pFormatCtx = NULL;
}
// Close the codec
if( pCodecCtx )
{
//avcodec_close(pCodecCtx);
pCodecCtx = NULL;
}
#ifdef USE_AVIOCONTEXT
if( pIOContext )
{
//av_free(iobuffer);
av_free(pIOContext);
pIOContext = NULL;
}
#endif
#if LIBAVCODEC_VERSION_MAJOR > 54
av_dict_free(&avDictionary);
avDictionary = NULL;
#endif
return 0;
}
bool FFMPegDecoder::GetVideoFrame(bool restart)
{
static AVPacket packet;
static int bytesRemaining=0;
static uint8_t *rawData;
static bool fFirstTime=true;
int bytesDecoded;
int frameFinished;
int ret;
#if LIBAVCODEC_VERSION_MAJOR < 57
if( restart )
{
bytesRemaining=0;
if(packet.data!=NULL)
av_free_packet(&packet);
packet.data=NULL;
}
// First time we're called, set packet.data to NULL to indicate it
// doesn't have to be freed
if(fFirstTime)
{
fFirstTime=false;
packet.data=NULL;
}
// Decode packets until we have decoded a complete frame
while(true)
{
// Work on the current packet until we have decoded all of it
while(bytesRemaining > 0)
{
// Decode the next chunk of data
bytesDecoded=avcodec_decode_video2(pCodecCtx, pFrame,&frameFinished, &packet);
//dsyslog("ffmpeg decoded %d bytes from %d bytes",bytesDecoded,bytesRemaining);
// Was there an error?
if(bytesDecoded < 0)
{
esyslog("Error while decoding frame");
//Mpeg1Context *s1 = pCodecCtx->priv_data;
//MpegEncContext *s = &s1->mpeg_enc_ctx;
av_free_packet(&packet);
packet.data=NULL;
bytesRemaining=0;
return false;
}
bytesRemaining-=bytesDecoded;
rawData+=bytesDecoded;
// Did we finish the current frame? Then we can return
if(frameFinished)
{
#ifdef FFMPEG_SUPPRESS_NOPICTURE_ERROR
if( pFrame->data[0] && pFrame->data[1] && pFrame->data[2] )
return true;
else
esyslog("ffmpeg get picture without data!");
#else
//dsyslog("ffmpeg get picture #%d, leaving %d bytes in buffer", pFrame->coded_picture_number,bytesRemaining);
//gotPicture = true;
return true;
#endif
}
}
// Read the next packet, skipping all packets that aren't for this
// stream
do
{
// Free old packet
if(packet.data!=NULL)
av_free_packet(&packet);
// Read new packet
if(av_read_frame(pFormatCtx, &packet)<0)
goto loop_exit;
} while(packet.stream_index!=videoStream);
//dsyslog("found packet with %d bytes of data", packet.size);
bytesRemaining=packet.size;
rawData=packet.data;
}
loop_exit:
// Decode the rest of the last frame
bytesDecoded=avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
// Free last packet
if(packet.data!=NULL)
av_free_packet(&packet);
ffmpegerror = true;
return frameFinished!=0;
#else
// libavcodec 57+
if( restart )
{
if(packet.data!=NULL)
av_packet_unref(&packet);
packet.data=NULL;
avcodec_flush_buffers(pCodecCtx);
}
else
{
ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (ret < 0 && ret != AVERROR(EAGAIN))
{
ffmpegerror = true;
return false;
}
}
do
{
do
{
// Free packet
if(packet.data!=NULL)
av_packet_unref(&packet);
// Read new packet
ret = av_read_frame(pFormatCtx, &packet);
if(ret < 0)
{
if (ret == AVERROR_EOF)
{ // create draining packet
packet.data = NULL;
packet.size = 0;
}
else
{
if (packet.data!=NULL)
av_packet_unref(&packet);
ffmpegerror = true;
return false;
}
}
} while(packet.stream_index!=videoStream && ret != AVERROR_EOF);
ret = avcodec_send_packet(pCodecCtx, &packet);
if (packet.data!=NULL)
av_packet_unref(&packet);
if (ret < 0 && ret != AVERROR(EAGAIN))
{
ffmpegerror = true;
return false;
}
ret = avcodec_receive_frame(pCodecCtx, pFrame);
if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
{
ffmpegerror = true;
return false;
}
} while (ret != 0 && ret != AVERROR_EOF);
return ret != AVERROR_EOF;
#endif
}
bool FFMPegDecoder::getNextPicture(int startIndex, int flags )
{
bool bRet = false;
bool restart = false;
ffmpegerror = false;
if (flags & DEMUX_RESET)
{
ffmpeg_index = startIndex;
resetDecoder(startIndex);
restart = true;
}
// iCurrentDecodedFrame = startIndex;
while( !bRet && ffmpeg_index < cIF->getLast() && !ffmpegerror )
{
bRet = GetVideoFrame(restart);
if( bRet && callBackFunc )
{
if( (FRAMEWIDTH <= MAX_WIDTH && FRAMEWIDTH > 0) && (FRAMEHEIGHT <= MAX_HEIGHT && FRAMEHEIGHT > 0 ) )
{
noadYUVBuf lbuf(pFrame->data,pFrame->linesize,FRAMEWIDTH,FRAMEHEIGHT);
callBackFunc(&lbuf);
}
else
esyslog("ERROR: faulty width (%d) or height(%d)",FRAMEWIDTH,FRAMEHEIGHT);
}
}
startIndex = ffmpeg_index;
return bRet;
}
bool FFMPegDecoder::getPictures(int &startIndex, int flags, stopFunction stop )
{
bool bRet = false;
bool bStop = false;
//dsyslog("getPicture from index %d", startIndex );
bool restart = false;
ffmpegerror = false;
if (flags & DEMUX_RESET)
{
resetDecoder(startIndex);
restart = true;
}
else
if( startIndex < ffmpeg_index )
return false;
ffmpeg_index = startIndex;
while( ffmpeg_index < cIF->getLast() && !ffmpegerror && !bStop )
{
bRet = GetVideoFrame(restart);
restart = false;
if( bRet && callBackFunc )
{
if( (FRAMEWIDTH <= MAX_WIDTH && FRAMEWIDTH > 0) && (FRAMEHEIGHT <= MAX_HEIGHT && FRAMEHEIGHT > 0 ) )
{
noadYUVBuf lbuf(pFrame->data,pFrame->linesize,FRAMEWIDTH,FRAMEHEIGHT);
callBackFunc(&lbuf);
bStop = stop();
}
else
esyslog("ERROR: faulty width (%d) or height(%d)",FRAMEWIDTH,FRAMEHEIGHT);
}
}
startIndex = ffmpeg_index;
return bRet;
}
bool FFMPegDecoder::getGOP(int &startIndex )
{
bool bRet = false;
uint16_t FileNumber;
off_t FileOffset;
bool Independent;
int gopStartFrame = startIndex;
cIF->Get(startIndex, &FileNumber, &FileOffset, &Independent);
if( !Independent )
gopStartFrame = cIF->GetNextIFrame( startIndex, false, NULL, NULL, NULL, true);
//dsyslog("getGOP from index %d (%d)", startIndex, gopStartFrame );
bool restart = true;
ffmpegerror = false;
ffmpeg_index = gopStartFrame;
bool bFirst = true;
if( GOP_Buffer.startindex != gopStartFrame )
{
resetDecoder(gopStartFrame);
GOP_Buffer.numpics = 0;
while( ffmpeg_index < cIF->getLast() && !ffmpegerror && GOP_Buffer.numpics < PICS_IN_GOP )
{
bRet = GetVideoFrame(restart);
restart = false;
if( bRet )
{
if( (FRAMEWIDTH <= MAX_WIDTH && FRAMEWIDTH > 0) && (FRAMEHEIGHT <= MAX_HEIGHT && FRAMEHEIGHT > 0 ) )
{
if( bFirst )
GOP_Buffer.init(FRAMEWIDTH,FRAMEHEIGHT,pFrame->linesize[0],pFrame->linesize[1]);
bFirst = false;
GOP_Buffer.addPic(pFrame->data,pFrame->linesize[0],pFrame->linesize[1]);
}
else
esyslog("ERROR: faulty width (%d) or height(%d)",FRAMEWIDTH,FRAMEHEIGHT);
}
}
GOP_Buffer.startindex = gopStartFrame;
}
if( GOP_Buffer.numpics && callBackFunc )
{
int offset = startIndex - gopStartFrame;
callBackFunc(&GOP_Buffer.gop_buf[offset]);
}
startIndex = ffmpeg_index;
return bRet;
}
extern "C" void av_read_frame_flush(AVFormatContext *s);
void FFMPegDecoder::resetDecoder()
{
//if( pFormatCtx )
// av_read_frame_flush(pFormatCtx);
if( pCodecCtx )
{
pCodecCtx->codec->flush(pCodecCtx);
avcodec_flush_buffers(pCodecCtx);
}
if( pFrame )
av_free(pFrame);
#if LIBAVCODEC_VERSION_MAJOR < 57
pFrame=avcodec_alloc_frame();
#else
pFrame=av_frame_alloc();
#endif
__bufBytes = 0;
}
void FFMPegDecoder::resetDecoder(int iFrame)
{
__bufBytes = 0;
ffmpeg_index = iFrame;
cIF->Get(ffmpeg_index,&ffmpegFileNumber, &ffmpegFileOffset);
avformat_seek_file(pFormatCtx, videoStream, ffmpegFileOffset, ffmpegFileOffset, ffmpegFileOffset, AVSEEK_FLAG_BYTE);
if( pCodecCtx && pCodecCtx->codec )
avcodec_flush_buffers(pCodecCtx);
}
#endif //USE_FFMPEG