chunker-player / chunker_streamer / chunker_streamer.c @ 9f3252e2
History | View | Annotate | Download (50.7 KB)
1 |
/*
|
---|---|
2 |
* Copyright (c) 2009-2011 Carmelo Daniele, Dario Marchese, Diego Reforgiato, Giuseppe Tropea
|
3 |
* Copyright (c) 2010-2011 Csaba Kiraly
|
4 |
* developed for the Napa-Wine EU project. See www.napa-wine.eu
|
5 |
*
|
6 |
* This is free software; see lgpl-2.1.txt
|
7 |
*/
|
8 |
|
9 |
#include "chunker_streamer.h" |
10 |
#include <signal.h> |
11 |
#include <math.h> |
12 |
#include <getopt.h> |
13 |
#include <libswscale/swscale.h> |
14 |
#include <libavutil/opt.h> |
15 |
|
16 |
#ifdef USE_AVFILTER
|
17 |
#include <libavfilter/avfilter.h> |
18 |
#include "chunker_filtering.h" |
19 |
#endif
|
20 |
|
21 |
#include "chunk_pusher.h" |
22 |
|
23 |
struct outstream {
|
24 |
struct output *output;
|
25 |
ExternalChunk *chunk; |
26 |
AVCodecContext *pCodecCtxEnc; |
27 |
}; |
28 |
#define QUALITYLEVELS_MAX 9 |
29 |
struct outstream outstream[1+QUALITYLEVELS_MAX+1]; |
30 |
int qualitylevels = 3; |
31 |
int indexchannel = 1; |
32 |
int passthrough = 1; |
33 |
|
34 |
#define DEBUG
|
35 |
#define DEBUG_AUDIO_FRAMES false |
36 |
#define DEBUG_VIDEO_FRAMES false |
37 |
#define DEBUG_CHUNKER false |
38 |
#define DEBUG_ANOMALIES true |
39 |
#define DEBUG_TIMESTAMPING false |
40 |
#include "dbg.h" |
41 |
|
42 |
#define STREAMER_MAX(a,b) ((a>b)?(a):(b))
|
43 |
#define STREAMER_MIN(a,b) ((a<b)?(a):(b))
|
44 |
|
45 |
//#define DISPLAY_PSNR
|
46 |
#define GET_PSNR(x) ((x==0) ? 0 : (-10.0*log(x)/log(10))) |
47 |
|
48 |
ChunkerMetadata *cmeta = NULL;
|
49 |
int seq_current_chunk = 1; //chunk numbering starts from 1; HINT do i need more bytes? |
50 |
|
51 |
#define AUDIO_CHUNK 0 |
52 |
#define VIDEO_CHUNK 1 |
53 |
|
54 |
void SaveFrame(AVFrame *pFrame, int width, int height); |
55 |
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf);
|
56 |
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf);
|
57 |
void bit32_encoded_push(uint32_t v, uint8_t *p);
|
58 |
|
59 |
int video_record_count = 0; |
60 |
int savedVideoFrames = 0; |
61 |
long int firstSavedVideoFrame = 0; |
62 |
int ChunkerStreamerTestMode = 0; |
63 |
|
64 |
int pts_anomaly_threshold = -1; |
65 |
int newtime_anomaly_threshold = -1; |
66 |
bool timebank = false; |
67 |
char *outside_world_url = NULL; |
68 |
|
69 |
int gop_size = 25; |
70 |
int max_b_frames = 3; |
71 |
bool vcopy = false; |
72 |
|
73 |
long delay_audio = 0; //delay audio by x millisec |
74 |
|
75 |
char *avfilter="yadif"; |
76 |
|
77 |
// Constant number of frames per chunk
|
78 |
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType) |
79 |
{ |
80 |
dcprintf(DEBUG_CHUNKER, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
|
81 |
if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
|
82 |
return 1; |
83 |
|
84 |
return 0; |
85 |
} |
86 |
|
87 |
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
|
88 |
// It can be considered as constant size.
|
89 |
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType) |
90 |
{ |
91 |
dcprintf(DEBUG_CHUNKER, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
|
92 |
if(echunk->payload_len >= cmeta->targetChunkSize)
|
93 |
return 1; |
94 |
|
95 |
return 0; |
96 |
} |
97 |
|
98 |
// Performace optimization.
|
99 |
// The chunkFilled function has been splitted into two functions (one for each strategy).
|
100 |
// Instead of continuously check the strategy flag (which is constant),
|
101 |
// we change the callback just once according to the current strategy (look at the switch statement in the main in which this function pointer is set)
|
102 |
int (*chunkFilled)(ExternalChunk *echunk, int chunkType); |
103 |
|
104 |
void initChunk(ExternalChunk *chunk, int *seq_num) { |
105 |
chunk->seq = (*seq_num)++; |
106 |
chunk->frames_num = 0;
|
107 |
chunk->payload_len = 0;
|
108 |
chunk->len=0;
|
109 |
if(chunk->data != NULL) |
110 |
free(chunk->data); |
111 |
chunk->data = NULL;
|
112 |
chunk->start_time.tv_sec = -1;
|
113 |
chunk->start_time.tv_usec = -1;
|
114 |
chunk->end_time.tv_sec = -1;
|
115 |
chunk->end_time.tv_usec = -1;
|
116 |
chunk->priority = 0;
|
117 |
chunk->category = 0;
|
118 |
chunk->_refcnt = 0;
|
119 |
} |
120 |
|
121 |
int quit = 0; |
122 |
|
123 |
void sigproc()
|
124 |
{ |
125 |
printf("you have pressed ctrl-c, terminating...\n");
|
126 |
quit = 1;
|
127 |
} |
128 |
|
129 |
static void print_usage(int argc, char *argv[]) |
130 |
{ |
131 |
fprintf (stderr, |
132 |
"\nUsage:%s [options]\n"
|
133 |
"\n"
|
134 |
"Mandatory options:\n"
|
135 |
"\t[-i input file]\n"
|
136 |
"\t[-a audio bitrate]\n"
|
137 |
"\t[-v video bitrate]\n\n"
|
138 |
"Other options:\n"
|
139 |
"\t[-F output] (overrides config file)\n"
|
140 |
"\t[-A audioencoder]\n"
|
141 |
"\t[-V videoencoder]\n"
|
142 |
"\t[-s WxH]: force video size.\n"
|
143 |
"\t[-l]: this is a live stream.\n"
|
144 |
"\t[-o]: adjust A/V frame timestamps (deafault off, use it only with flawed containers)\n"
|
145 |
"\t[-p]: pts anomaly threshold (default: -1=off).\n"
|
146 |
"\t[-q]: sync anomaly threshold ((default: -1=off).\n"
|
147 |
"\t[-t]: QoE test mode\n\n"
|
148 |
|
149 |
"\t[--video_stream]:set video_stream ID in input\n"
|
150 |
"\t[--audio_stream]:set audio_stream ID in input\n"
|
151 |
"\t[--avfilter]:set input filter (default: yadif\n"
|
152 |
"\t[--qualitylevels]:set number of quality levels\n"
|
153 |
"\t[--passthrough 0/1]: turn off/on generation of passthrough channel\n"
|
154 |
"\t[--indexchannel 0/1]: turn off/on generation of index channel\n"
|
155 |
"\n"
|
156 |
"Codec options:\n"
|
157 |
"\t[-g GOP]: gop size\n"
|
158 |
"\t[-b frames]: max number of consecutive b frames\n"
|
159 |
"\t[-x extas]: extra video codec options (e.g. -x me_method=hex,flags2=+dct8x8+wpred+bpyrami+mixed_refs)\n"
|
160 |
"\n"
|
161 |
"=======================================================\n", argv[0] |
162 |
); |
163 |
} |
164 |
|
165 |
int sendChunk(struct output *output, ExternalChunk *chunk) { |
166 |
#ifdef HTTPIO
|
167 |
return pushChunkHttp(chunk, outside_world_url);
|
168 |
#endif
|
169 |
#ifdef TCPIO
|
170 |
return pushChunkTcp(output, chunk);
|
171 |
#endif
|
172 |
#ifdef UDPIO
|
173 |
return pushChunkUDP(chunk);
|
174 |
#endif
|
175 |
} |
176 |
|
177 |
AVFrame *preprocessFrame(AVFrame *pFrame) { |
178 |
#ifdef USE_AVFILTER
|
179 |
AVFrame *pFrame2 = NULL;
|
180 |
pFrame2=avcodec_alloc_frame(); |
181 |
if(pFrame2==NULL) { |
182 |
fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
|
183 |
if(pFrame2) av_free(pFrame2);
|
184 |
return NULL; |
185 |
} |
186 |
#endif
|
187 |
|
188 |
#ifdef VIDEO_DEINTERLACE
|
189 |
avpicture_deinterlace( |
190 |
(AVPicture*) pFrame, |
191 |
(const AVPicture*) pFrame,
|
192 |
pCodecCtxEnc->pix_fmt, |
193 |
pCodecCtxEnc->width, |
194 |
pCodecCtxEnc->height); |
195 |
#endif
|
196 |
|
197 |
#ifdef USE_AVFILTER
|
198 |
//apply avfilters
|
199 |
filter(pFrame,pFrame2); |
200 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOfilter: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame2->pkt_dts, pFrame2->pkt_pts, pFrame2->pts); |
201 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOfilter intype %d%s\n", pFrame2->pict_type, pFrame2->key_frame ? " (key)" : ""); |
202 |
return pFrame2;
|
203 |
#else
|
204 |
return NULL; |
205 |
#endif
|
206 |
} |
207 |
|
208 |
|
209 |
int transcodeFrame(uint8_t *video_outbuf, int video_outbuf_size, int64_t *target_pts, AVFrame *pFrame, AVRational time_base, AVCodecContext *pCodecCtx, AVCodecContext *pCodecCtxEnc) |
210 |
{ |
211 |
int video_frame_size = 0; |
212 |
AVFrame *scaledFrame = NULL;
|
213 |
scaledFrame=avcodec_alloc_frame(); |
214 |
if(scaledFrame==NULL) { |
215 |
fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
|
216 |
if(scaledFrame) av_free(scaledFrame);
|
217 |
return -1; |
218 |
} |
219 |
int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height);
|
220 |
uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
|
221 |
avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height); |
222 |
if(!video_outbuf || !scaledFrame_buffer) {
|
223 |
fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
|
224 |
return -1; |
225 |
} |
226 |
|
227 |
|
228 |
|
229 |
if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
|
230 |
// static AVPicture pict;
|
231 |
static struct SwsContext *img_convert_ctx = NULL; |
232 |
|
233 |
pFrame->pict_type = 0;
|
234 |
img_convert_ctx = sws_getCachedContext(img_convert_ctx, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); |
235 |
if(img_convert_ctx == NULL) { |
236 |
fprintf(stderr, "Cannot initialize the conversion context!\n");
|
237 |
exit(1);
|
238 |
} |
239 |
sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
|
240 |
scaledFrame->pts = pFrame->pts; |
241 |
scaledFrame->pict_type = 0;
|
242 |
video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame); |
243 |
} else {
|
244 |
pFrame->pict_type = 0;
|
245 |
video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame); |
246 |
} |
247 |
|
248 |
//use pts if dts is invalid
|
249 |
if(pCodecCtxEnc->coded_frame->pts!=AV_NOPTS_VALUE)
|
250 |
*target_pts = av_rescale_q(pCodecCtxEnc->coded_frame->pts, pCodecCtxEnc->time_base, time_base); |
251 |
else { //TODO: review this |
252 |
if(scaledFrame) av_free(scaledFrame);
|
253 |
if(scaledFrame_buffer) av_free(scaledFrame_buffer);
|
254 |
return -1; |
255 |
} |
256 |
|
257 |
if(video_frame_size > 0) { |
258 |
if(pCodecCtxEnc->coded_frame) {
|
259 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOout: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pCodecCtxEnc->coded_frame->pkt_dts, pCodecCtxEnc->coded_frame->pkt_pts, pCodecCtxEnc->coded_frame->pts); |
260 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOout: outtype: %d%s\n", pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : ""); |
261 |
} |
262 |
#ifdef DISPLAY_PSNR
|
263 |
static double ist_psnr = 0; |
264 |
static double cum_psnr = 0; |
265 |
static int psnr_samples = 0; |
266 |
if(pCodecCtxEnc->coded_frame) {
|
267 |
if(pCodecCtxEnc->flags&CODEC_FLAG_PSNR) {
|
268 |
ist_psnr = GET_PSNR(pCodecCtxEnc->coded_frame->error[0]/(pCodecCtxEnc->width*pCodecCtxEnc->height*255.0*255.0)); |
269 |
psnr_samples++; |
270 |
cum_psnr += ist_psnr; |
271 |
fprintf(stderr, "PSNR: ist %.4f avg: %.4f\n", ist_psnr, cum_psnr / (double)psnr_samples); |
272 |
} |
273 |
} |
274 |
#endif
|
275 |
} |
276 |
|
277 |
if(scaledFrame) av_free(scaledFrame);
|
278 |
if(scaledFrame_buffer) av_free(scaledFrame_buffer);
|
279 |
return video_frame_size;
|
280 |
} |
281 |
|
282 |
|
283 |
void createFrame(struct Frame *frame, long long newTime, int video_frame_size, int pict_type) |
284 |
{ |
285 |
|
286 |
frame->timestamp.tv_sec = (long long)newTime/1000; |
287 |
frame->timestamp.tv_usec = newTime%1000;
|
288 |
frame->size = video_frame_size; |
289 |
/* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
|
290 |
frame->type = pict_type; |
291 |
|
292 |
|
293 |
/* should be on some other place
|
294 |
// if (!vcopy) dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: original codec frame number %d vs. encoded %d vs. packed %d\n", pCodecCtx->frame_number, pCodecCtxEnc->frame_number, frame->number);
|
295 |
// if (!vcopy) dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: duration %d timebase %d %d container timebase %d\n", (int)packet.duration, pCodecCtxEnc->time_base.den, pCodecCtxEnc->time_base.num, pCodecCtx->time_base.den);
|
296 |
|
297 |
#ifdef YUV_RECORD_ENABLED
|
298 |
if(!vcopy && ChunkerStreamerTestMode)
|
299 |
{
|
300 |
if(videotrace)
|
301 |
fprintf(videotrace, "%d %d %d\n", frame->number, pict_type, frame->size);
|
302 |
|
303 |
SaveFrame(pFrame, dest_width, dest_height);
|
304 |
|
305 |
++savedVideoFrames;
|
306 |
SaveEncodedFrame(frame, video_outbuf);
|
307 |
|
308 |
if(!firstSavedVideoFrame)
|
309 |
firstSavedVideoFrame = frame->number;
|
310 |
|
311 |
char tmp_filename[255];
|
312 |
sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
|
313 |
FILE* tmp = fopen(tmp_filename, "w");
|
314 |
if(tmp)
|
315 |
{
|
316 |
fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
|
317 |
,dest_width, dest_height
|
318 |
,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
|
319 |
fclose(tmp);
|
320 |
}
|
321 |
}
|
322 |
#endif
|
323 |
*/
|
324 |
|
325 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
|
326 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: timestamped sec %ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec); |
327 |
} |
328 |
|
329 |
|
330 |
void addFrameToOutstream(struct outstream *os, Frame *frame, uint8_t *video_outbuf) |
331 |
{ |
332 |
|
333 |
ExternalChunk *chunk = os->chunk; |
334 |
struct output *output = os->output;
|
335 |
|
336 |
if(update_chunk(chunk, frame, video_outbuf) == -1) { |
337 |
fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
|
338 |
exit(-1);
|
339 |
} |
340 |
|
341 |
if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy? |
342 |
//calculate priority
|
343 |
chunk->priority /= chunk->frames_num; |
344 |
|
345 |
//SAVE ON FILE
|
346 |
//saveChunkOnFile(chunk);
|
347 |
//Send the chunk to an external transport/player
|
348 |
sendChunk(output, chunk); |
349 |
dctprintf(DEBUG_CHUNKER, "VIDEO: sent chunk video %d, prio:%f, size %d\n", chunk->seq, chunk->priority, chunk->len);
|
350 |
chunk->seq = 0; //signal that we need an increase |
351 |
//initChunk(chunk, &seq_current_chunk);
|
352 |
} |
353 |
} |
354 |
|
355 |
long long pts2ms(int64_t pts, AVRational time_base) |
356 |
{ |
357 |
return pts * 1000 * time_base.num / time_base.den; |
358 |
} |
359 |
|
360 |
AVCodecContext *openVideoEncoder(const char *video_codec, int video_bitrate, int dest_width, int dest_height, AVRational time_base, const char *codec_options) { |
361 |
|
362 |
AVCodec *pCodecEnc; |
363 |
AVCodecContext *pCodecCtxEnc; |
364 |
|
365 |
//setup video output encoder
|
366 |
if (strcmp(video_codec, "copy") == 0) { |
367 |
return NULL; |
368 |
} |
369 |
|
370 |
pCodecEnc = avcodec_find_encoder_by_name(video_codec); |
371 |
if (pCodecEnc) {
|
372 |
fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
|
373 |
} else {
|
374 |
fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
|
375 |
return NULL; // Codec not found |
376 |
} |
377 |
|
378 |
pCodecCtxEnc=avcodec_alloc_context(); |
379 |
pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO; |
380 |
pCodecCtxEnc->codec_id = pCodecEnc->id; |
381 |
|
382 |
pCodecCtxEnc->bit_rate = video_bitrate; |
383 |
//~ pCodecCtxEnc->qmin = 30;
|
384 |
//~ pCodecCtxEnc->qmax = 30;
|
385 |
//times 20 follows the defaults, was not needed in previous versions of libavcodec
|
386 |
// pCodecCtxEnc->crf = 20.0f;
|
387 |
// resolution must be a multiple of two
|
388 |
pCodecCtxEnc->width = dest_width; |
389 |
pCodecCtxEnc->height = dest_height; |
390 |
// frames per second
|
391 |
//~ pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
|
392 |
//printf("pCodecCtx->time_base=%d/%d\n", pCodecCtx->time_base.num, pCodecCtx->time_base.den);
|
393 |
pCodecCtxEnc->time_base= time_base;//(AVRational){1,25};
|
394 |
pCodecCtxEnc->gop_size = gop_size; // emit one intra frame every gop_size frames
|
395 |
pCodecCtxEnc->max_b_frames = max_b_frames; |
396 |
pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P; |
397 |
pCodecCtxEnc->flags |= CODEC_FLAG_PSNR; |
398 |
//~ pCodecCtxEnc->flags |= CODEC_FLAG_QSCALE;
|
399 |
|
400 |
//some generic quality tuning
|
401 |
pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD; |
402 |
|
403 |
//some rate control parameters for streaming, taken from ffserver.c
|
404 |
{ |
405 |
/* Bitrate tolerance is less for streaming */
|
406 |
AVCodecContext *av = pCodecCtxEnc; |
407 |
//if (av->bit_rate_tolerance == 0) //ffmeg sets the dafult to 4M independent of other parameters, for some reason
|
408 |
av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
|
409 |
(int64_t)av->bit_rate*av->time_base.num/av->time_base.den); |
410 |
//if (av->qmin == 0)
|
411 |
// av->qmin = 3;
|
412 |
//if (av->qmax == 0)
|
413 |
// av->qmax = 31;
|
414 |
//if (av->max_qdiff == 0)
|
415 |
// av->max_qdiff = 3;
|
416 |
//av->qcompress = 0.5;
|
417 |
//av->qblur = 0.5;
|
418 |
|
419 |
//if (!av->nsse_weight)
|
420 |
// av->nsse_weight = 8;
|
421 |
|
422 |
//av->frame_skip_cmp = FF_CMP_DCTMAX;
|
423 |
//if (!av->me_method)
|
424 |
// av->me_method = ME_EPZS;
|
425 |
//av->rc_buffer_aggressivity = 1.0;
|
426 |
|
427 |
//if (!av->rc_eq)
|
428 |
// av->rc_eq = "tex^qComp";
|
429 |
//if (!av->i_quant_factor)
|
430 |
// av->i_quant_factor = -0.8;
|
431 |
//if (!av->b_quant_factor)
|
432 |
// av->b_quant_factor = 1.25;
|
433 |
//if (!av->b_quant_offset)
|
434 |
// av->b_quant_offset = 1.25;
|
435 |
if (!av->rc_max_rate)
|
436 |
av->rc_max_rate = av->bit_rate * 1;
|
437 |
|
438 |
if (av->rc_max_rate && !av->rc_buffer_size) {
|
439 |
av->rc_buffer_size = av->rc_max_rate; |
440 |
} |
441 |
} |
442 |
//end of code taken fromffserver.c
|
443 |
|
444 |
switch (pCodecEnc->id) {
|
445 |
case CODEC_ID_H264 :
|
446 |
// Fast Profile
|
447 |
// libx264-fast.ffpreset preset
|
448 |
pCodecCtxEnc->coder_type = FF_CODER_TYPE_AC; // coder = 1 -> enable CABAC
|
449 |
pCodecCtxEnc->flags |= CODEC_FLAG_LOOP_FILTER; // flags=+loop -> deblock
|
450 |
pCodecCtxEnc->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1 |
451 |
pCodecCtxEnc->partitions |= X264_PART_I8X8|X264_PART_I4X4|X264_PART_P8X8|X264_PART_B8X8; // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
|
452 |
pCodecCtxEnc->me_method=ME_HEX; // me_method=hex
|
453 |
pCodecCtxEnc->me_subpel_quality = 6; // subq=7 |
454 |
pCodecCtxEnc->me_range = 16; // me_range=16 |
455 |
//pCodecCtxEnc->gop_size = 250; // g=250
|
456 |
//pCodecCtxEnc->keyint_min = 25; // keyint_min=25
|
457 |
pCodecCtxEnc->scenechange_threshold = 40; // sc_threshold=40 |
458 |
pCodecCtxEnc->i_quant_factor = 0.71; // i_qfactor=0.71 |
459 |
pCodecCtxEnc->b_frame_strategy = 1; // b_strategy=1 |
460 |
pCodecCtxEnc->qcompress = 0.6; // qcomp=0.6 |
461 |
pCodecCtxEnc->qmin = 10; // qmin=10 |
462 |
pCodecCtxEnc->qmax = 51; // qmax=51 |
463 |
pCodecCtxEnc->max_qdiff = 4; // qdiff=4 |
464 |
//pCodecCtxEnc->max_b_frames = 3; // bf=3
|
465 |
pCodecCtxEnc->refs = 2; // refs=3 |
466 |
//pCodecCtxEnc->directpred = 1; // directpred=1
|
467 |
pCodecCtxEnc->directpred = 3; // directpred=1 in preset -> "directpred", "direct mv prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)" |
468 |
//pCodecCtxEnc->trellis = 1; // trellis=1
|
469 |
pCodecCtxEnc->flags2 |= CODEC_FLAG2_BPYRAMID|CODEC_FLAG2_MIXED_REFS|CODEC_FLAG2_WPRED|CODEC_FLAG2_8X8DCT|CODEC_FLAG2_FASTPSKIP; // flags2=+bpyramid+mixed_refs+wpred+dct8x8+fastpskip
|
470 |
pCodecCtxEnc->weighted_p_pred = 2; // wpredp=2 |
471 |
|
472 |
// libx264-main.ffpreset preset
|
473 |
//pCodecCtxEnc->flags2|=CODEC_FLAG2_8X8DCT;
|
474 |
//pCodecCtxEnc->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
|
475 |
//pCodecCtxEnc->crf = 22;
|
476 |
|
477 |
#ifdef STREAMER_X264_USE_SSIM
|
478 |
pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM; |
479 |
#endif
|
480 |
|
481 |
//pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
|
482 |
// pCodecCtxEnc->rc_min_rate = 0;
|
483 |
// pCodecCtxEnc->rc_max_rate = video_bitrate*2;
|
484 |
// pCodecCtxEnc->rc_buffer_size = 0;
|
485 |
break;
|
486 |
case CODEC_ID_MPEG4 :
|
487 |
break;
|
488 |
default:
|
489 |
fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
|
490 |
} |
491 |
|
492 |
if ((av_set_options_string(pCodecCtxEnc, codec_options, "=", ",")) < 0) { |
493 |
fprintf(stderr, "Error parsing options string: '%s'\n", codec_options);
|
494 |
return NULL; |
495 |
} |
496 |
|
497 |
if(avcodec_open(pCodecCtxEnc, pCodecEnc)<0) { |
498 |
fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
|
499 |
return NULL; // Could not open codec |
500 |
} |
501 |
|
502 |
return pCodecCtxEnc;
|
503 |
} |
504 |
|
505 |
|
506 |
int main(int argc, char *argv[]) { |
507 |
signal(SIGINT, sigproc); |
508 |
|
509 |
int i=0,j,k; |
510 |
|
511 |
//output variables
|
512 |
uint8_t *video_outbuf = NULL;
|
513 |
int video_outbuf_size, video_frame_size;
|
514 |
uint8_t *audio_outbuf = NULL;
|
515 |
int audio_outbuf_size, audio_frame_size;
|
516 |
int audio_data_size;
|
517 |
|
518 |
//numeric identifiers of input streams
|
519 |
int videoStream = -1; |
520 |
int audioStream = -1; |
521 |
|
522 |
// int len1;
|
523 |
int frameFinished;
|
524 |
//frame sequential counters
|
525 |
int contFrameAudio=1, contFrameVideo=0; |
526 |
// int numBytes;
|
527 |
|
528 |
//command line parameters
|
529 |
int audio_bitrate = -1; |
530 |
int video_bitrate = -1; |
531 |
char *audio_codec = "mp2"; |
532 |
char *video_codec = "mpeg4"; |
533 |
char *codec_options = ""; |
534 |
int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file) |
535 |
int offset_av = 0; //tells to compensate for offset between audio and video in the file |
536 |
|
537 |
//a raw buffer for decoded uncompressed audio samples
|
538 |
int16_t *samples = NULL;
|
539 |
//a raw uncompressed video picture
|
540 |
AVFrame *pFrame1 = NULL;
|
541 |
|
542 |
AVFormatContext *pFormatCtx; |
543 |
AVCodecContext *pCodecCtx = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL; |
544 |
AVCodec *pCodec = NULL ,*aCodec = NULL ,*aCodecEnc = NULL; |
545 |
AVPacket packet; |
546 |
|
547 |
//stuff needed to compute the right timestamps
|
548 |
short int FirstTimeAudio=1, FirstTimeVideo=1; |
549 |
short int pts_anomalies_counter=0; |
550 |
short int newtime_anomalies_counter=0; |
551 |
long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0; |
552 |
struct timeval lastAudioSent = {0, 0}; |
553 |
int64_t ptsvideo1=0;
|
554 |
int64_t ptsaudio1=0;
|
555 |
int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0; |
556 |
|
557 |
//Napa-Wine specific Frame and Chunk structures for transport
|
558 |
Frame *frame = NULL;
|
559 |
ExternalChunk *chunkaudio = NULL;
|
560 |
|
561 |
char av_input[1024]; |
562 |
int dest_width = -1; |
563 |
int dest_height = -1; |
564 |
|
565 |
static struct option long_options[] = |
566 |
{ |
567 |
{"audio_stream", required_argument, 0, 0}, |
568 |
{"video_stream", required_argument, 0, 0}, |
569 |
{"avfilter", required_argument, 0, 0}, |
570 |
{"indexchannel", required_argument, 0, 0}, |
571 |
{"passthrough", required_argument, 0, 0}, |
572 |
{"qualitylevels", required_argument, 0, 'Q'}, |
573 |
{0, 0, 0, 0} |
574 |
}; |
575 |
/* `getopt_long' stores the option index here. */
|
576 |
int option_index = 0, c; |
577 |
int mandatories = 0; |
578 |
while ((c = getopt_long (argc, argv, "i:a:v:A:V:s:lop:q:tF:g:b:d:x:Q:", long_options, &option_index)) != -1) |
579 |
{ |
580 |
switch (c) {
|
581 |
case 0: //for long options |
582 |
if( strcmp( "audio_stream", long_options[option_index].name ) == 0 ) { audioStream = atoi(optarg); } |
583 |
if( strcmp( "video_stream", long_options[option_index].name ) == 0 ) { videoStream = atoi(optarg); } |
584 |
if( strcmp( "avfilter", long_options[option_index].name ) == 0 ) { avfilter = strdup(optarg); } |
585 |
if( strcmp( "indexchannel", long_options[option_index].name ) == 0 ) { indexchannel = atoi(optarg); } |
586 |
if( strcmp( "passthrough", long_options[option_index].name ) == 0 ) { passthrough = atoi(optarg); } |
587 |
break;
|
588 |
case 'i': |
589 |
sprintf(av_input, "%s", optarg);
|
590 |
mandatories++; |
591 |
break;
|
592 |
case 'a': |
593 |
sscanf(optarg, "%d", &audio_bitrate);
|
594 |
mandatories++; |
595 |
break;
|
596 |
case 'v': |
597 |
sscanf(optarg, "%d", &video_bitrate);
|
598 |
mandatories++; |
599 |
break;
|
600 |
case 'A': |
601 |
audio_codec = strdup(optarg); |
602 |
break;
|
603 |
case 'V': |
604 |
video_codec = strdup(optarg); |
605 |
break;
|
606 |
case 's': |
607 |
sscanf(optarg, "%dx%d", &dest_width, &dest_height);
|
608 |
break;
|
609 |
case 'l': |
610 |
live_source = 1;
|
611 |
break;
|
612 |
case 'o': |
613 |
offset_av = 1;
|
614 |
break;
|
615 |
case 't': |
616 |
ChunkerStreamerTestMode = 1;
|
617 |
break;
|
618 |
case 'p': |
619 |
sscanf(optarg, "%d", &pts_anomaly_threshold);
|
620 |
break;
|
621 |
case 'q': |
622 |
sscanf(optarg, "%d", &newtime_anomaly_threshold);
|
623 |
break;
|
624 |
case 'F': |
625 |
outside_world_url = strdup(optarg); |
626 |
break;
|
627 |
case 'g': |
628 |
sscanf(optarg, "%d", &gop_size);
|
629 |
break;
|
630 |
case 'b': |
631 |
sscanf(optarg, "%d", &max_b_frames);
|
632 |
break;
|
633 |
case 'd': |
634 |
sscanf(optarg, "%ld", &delay_audio);
|
635 |
break;
|
636 |
case 'x': |
637 |
codec_options = strdup(optarg); |
638 |
break;
|
639 |
case 'Q': |
640 |
sscanf(optarg, "%d", &qualitylevels);
|
641 |
if (qualitylevels > QUALITYLEVELS_MAX) {
|
642 |
fprintf(stderr,"Too many quality levels: %d (max:%d)\n", qualitylevels, QUALITYLEVELS_MAX);
|
643 |
return -1; |
644 |
} |
645 |
break;
|
646 |
default:
|
647 |
print_usage(argc, argv); |
648 |
return -1; |
649 |
} |
650 |
} |
651 |
|
652 |
if(mandatories < 3) |
653 |
{ |
654 |
print_usage(argc, argv); |
655 |
return -1; |
656 |
} |
657 |
|
658 |
#ifdef YUV_RECORD_ENABLED
|
659 |
if(ChunkerStreamerTestMode)
|
660 |
{ |
661 |
DELETE_DIR("yuv_data");
|
662 |
CREATE_DIR("yuv_data");
|
663 |
//FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
|
664 |
//fclose(pFile);
|
665 |
} |
666 |
#endif
|
667 |
|
668 |
#ifdef TCPIO
|
669 |
static char peer_ip[16]; |
670 |
static int peer_port; |
671 |
int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port); |
672 |
if (res < 2) { |
673 |
fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
|
674 |
return -2; |
675 |
} |
676 |
|
677 |
for (i=0; i < (passthrough?1:0) + qualitylevels + (indexchannel?1:0); i++) { |
678 |
outstream[i].output = initTCPPush(peer_ip, peer_port+i); |
679 |
if (!outstream[i].output) {
|
680 |
fprintf(stderr, "Error initializing output module, exiting\n");
|
681 |
exit(1);
|
682 |
} |
683 |
} |
684 |
#endif
|
685 |
|
686 |
restart:
|
687 |
// read the configuration file
|
688 |
cmeta = chunkerInit(); |
689 |
if (!outside_world_url) {
|
690 |
outside_world_url = strdup(cmeta->outside_world_url); |
691 |
} |
692 |
switch(cmeta->strategy)
|
693 |
{ |
694 |
case 1: |
695 |
chunkFilled = chunkFilledSizeStrategy; |
696 |
break;
|
697 |
default:
|
698 |
chunkFilled = chunkFilledFramesStrategy; |
699 |
} |
700 |
|
701 |
if(live_source)
|
702 |
fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
|
703 |
if(offset_av)
|
704 |
fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
|
705 |
|
706 |
// Register all formats and codecs
|
707 |
av_register_all(); |
708 |
|
709 |
// Open input file
|
710 |
if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) { |
711 |
fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
|
712 |
exit(-1);
|
713 |
} |
714 |
|
715 |
// Retrieve stream information
|
716 |
if(av_find_stream_info(pFormatCtx) < 0) { |
717 |
fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
|
718 |
exit(-1);
|
719 |
} |
720 |
|
721 |
// Dump information about file onto standard error
|
722 |
av_dump_format(pFormatCtx, 0, av_input, 0); |
723 |
|
724 |
// Find the video and audio stream numbers
|
725 |
for(i=0; i<pFormatCtx->nb_streams; i++) { |
726 |
if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) { |
727 |
videoStream=i; |
728 |
} |
729 |
if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) { |
730 |
audioStream=i; |
731 |
} |
732 |
} |
733 |
|
734 |
if(videoStream==-1 || audioStream==-1) { // TODO: refine to work with 1 or the other |
735 |
fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
|
736 |
exit(-1);
|
737 |
} |
738 |
|
739 |
fprintf(stderr, "INIT: Num streams : %d TBR: %d %d RFRAMERATE:%d %d Duration:%ld\n", pFormatCtx->nb_streams, pFormatCtx->streams[videoStream]->time_base.num, pFormatCtx->streams[videoStream]->time_base.den, pFormatCtx->streams[videoStream]->r_frame_rate.num, pFormatCtx->streams[videoStream]->r_frame_rate.den, (long int)pFormatCtx->streams[videoStream]->duration); |
740 |
|
741 |
fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
|
742 |
fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
|
743 |
|
744 |
|
745 |
// Get a pointer to the codec context for the input video stream
|
746 |
pCodecCtx=pFormatCtx->streams[videoStream]->codec; |
747 |
pCodec = avcodec_find_decoder(pCodecCtx->codec_id); |
748 |
//extract W and H
|
749 |
fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
|
750 |
|
751 |
// Get a pointer to the codec context for the input audio stream
|
752 |
if(audioStream != -1) { |
753 |
aCodecCtx=pFormatCtx->streams[audioStream]->codec; |
754 |
fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
|
755 |
} |
756 |
|
757 |
// Figure out size
|
758 |
dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
|
759 |
dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
|
760 |
|
761 |
//initialize outstream structures
|
762 |
for (i=0; i < (passthrough?1:0) + qualitylevels + (indexchannel?1:0); i++) { |
763 |
outstream[i].chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
|
764 |
if(!outstream[i].chunk) {
|
765 |
fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
|
766 |
return -1; |
767 |
} |
768 |
outstream[i].chunk->data = NULL;
|
769 |
outstream[i].chunk->seq = 0;
|
770 |
dcprintf(DEBUG_CHUNKER, "INIT: chunk video %d\n", outstream[i].chunk->seq);
|
771 |
outstream[i].pCodecCtxEnc = NULL;
|
772 |
} |
773 |
if (passthrough) outstream[0].pCodecCtxEnc = NULL; |
774 |
for (i=(passthrough?1:0),j=1,k=1; i < (passthrough?1:0) + qualitylevels; i++) { |
775 |
outstream[i].pCodecCtxEnc = openVideoEncoder(video_codec, video_bitrate/j, (dest_width/k/2)*2, (dest_height/k/2)*2, pCodecCtx->time_base, codec_options); // (w/2)*2, since libx264 requires width,height to be even |
776 |
if (!outstream[i].pCodecCtxEnc) {
|
777 |
return -1; |
778 |
} |
779 |
j*=3; //reduce bitrate to 1/3 |
780 |
k*=2; //reduce dimensions to 1/2 |
781 |
} |
782 |
if (indexchannel) {
|
783 |
outstream[(passthrough?1:0) + qualitylevels].pCodecCtxEnc = openVideoEncoder(video_codec, 50000, 160, 120, pCodecCtx->time_base, codec_options); |
784 |
if (!outstream[(passthrough?1:0) + qualitylevels].pCodecCtxEnc) { |
785 |
return -1; |
786 |
} |
787 |
} |
788 |
|
789 |
//fprintf(stderr, "INIT: VIDEO timebase OUT:%d %d IN: %d %d\n", outstream[1].pCodecCtxEnc->time_base.num, outstream[1].pCodecCtxEnc->time_base.den, pCodecCtx->time_base.num, pCodecCtx->time_base.den);
|
790 |
|
791 |
if(pCodec==NULL) { |
792 |
fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
|
793 |
return -1; // Codec not found |
794 |
} |
795 |
if(avcodec_open(pCodecCtx, pCodec)<0) { |
796 |
fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
|
797 |
return -1; // Could not open codec |
798 |
} |
799 |
if(audioStream!=-1) { |
800 |
//setup audio output encoder
|
801 |
aCodecCtxEnc = avcodec_alloc_context(); |
802 |
aCodecCtxEnc->bit_rate = audio_bitrate; //256000
|
803 |
aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16; |
804 |
aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate; |
805 |
aCodecCtxEnc->channels = aCodecCtx->channels; |
806 |
fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
|
807 |
|
808 |
// Find the decoder for the audio stream
|
809 |
aCodec = avcodec_find_decoder(aCodecCtx->codec_id); |
810 |
aCodecEnc = avcodec_find_encoder_by_name(audio_codec); |
811 |
if(aCodec==NULL) { |
812 |
fprintf(stderr,"INIT: Unsupported acodec!\n");
|
813 |
return -1; |
814 |
} |
815 |
if(aCodecEnc==NULL) { |
816 |
fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
|
817 |
return -1; |
818 |
} |
819 |
|
820 |
if(avcodec_open(aCodecCtx, aCodec)<0) { |
821 |
fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
|
822 |
return -1; // Could not open codec |
823 |
} |
824 |
if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) { |
825 |
fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
|
826 |
return -1; // Could not open codec |
827 |
} |
828 |
} |
829 |
else {
|
830 |
fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
|
831 |
} |
832 |
|
833 |
// Allocate audio in and out buffers
|
834 |
samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE); |
835 |
if(samples == NULL) { |
836 |
fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
|
837 |
return -1; |
838 |
} |
839 |
audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE; |
840 |
audio_outbuf = av_malloc(audio_outbuf_size); |
841 |
if(audio_outbuf == NULL) { |
842 |
fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
|
843 |
return -1; |
844 |
} |
845 |
|
846 |
// Allocate video in frame and out buffer
|
847 |
pFrame1=avcodec_alloc_frame(); |
848 |
if(pFrame1==NULL) { |
849 |
fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
|
850 |
return -1; |
851 |
} |
852 |
video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE; |
853 |
video_outbuf = av_malloc(video_outbuf_size); |
854 |
|
855 |
//allocate Napa-Wine transport
|
856 |
frame = (Frame *)malloc(sizeof(Frame));
|
857 |
if(!frame) {
|
858 |
fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
|
859 |
return -1; |
860 |
} |
861 |
|
862 |
//create empty first audio chunk
|
863 |
|
864 |
chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
|
865 |
if(!chunkaudio) {
|
866 |
fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
|
867 |
return -1; |
868 |
} |
869 |
chunkaudio->data=NULL;
|
870 |
chunkaudio->seq = 0;
|
871 |
//initChunk(chunkaudio, &seq_current_chunk);
|
872 |
dcprintf(DEBUG_CHUNKER, "INIT: chunk audio %d\n", chunkaudio->seq);
|
873 |
|
874 |
#ifdef HTTPIO
|
875 |
/* initialize the HTTP chunk pusher */
|
876 |
initChunkPusher(); //TRIPLO
|
877 |
#endif
|
878 |
|
879 |
long sleep=0; |
880 |
struct timeval now_tv;
|
881 |
struct timeval tmp_tv;
|
882 |
long long lateTime = 0; |
883 |
long long maxAudioInterval = 0; |
884 |
long long maxVDecodeTime = 0; |
885 |
// unsigned char lastIFrameDistance = 0;
|
886 |
|
887 |
#ifdef UDPIO
|
888 |
static char peer_ip[16]; |
889 |
static int peer_port; |
890 |
int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port); |
891 |
if (res < 2) { |
892 |
fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
|
893 |
return -2; |
894 |
} |
895 |
|
896 |
initUDPPush(peer_ip, peer_port); |
897 |
#endif
|
898 |
|
899 |
char videotrace_filename[255]; |
900 |
char psnr_filename[255]; |
901 |
sprintf(videotrace_filename, "yuv_data/videotrace.log");
|
902 |
sprintf(psnr_filename, "yuv_data/psnrtrace.log");
|
903 |
FILE* videotrace = fopen(videotrace_filename, "w");
|
904 |
FILE* psnrtrace = fopen(psnr_filename, "w");
|
905 |
|
906 |
#ifdef USE_AVFILTER
|
907 |
//init AVFilter
|
908 |
avfilter_register_all(); |
909 |
init_filters(avfilter, pCodecCtx); |
910 |
#endif
|
911 |
|
912 |
//main loop to read from the input file
|
913 |
while((av_read_frame(pFormatCtx, &packet)>=0) && !quit) |
914 |
{ |
915 |
//detect if a strange number of anomalies is occurring
|
916 |
if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) { |
917 |
pts_anomalies_counter++; |
918 |
dctprintf(DEBUG_ANOMALIES, "READLOOP: pts BASE anomaly detected number %d (a:%"PRId64" v:%"PRId64" dts:%"PRId64")\n", pts_anomalies_counter, ptsaudio1, ptsvideo1, packet.dts); |
919 |
if(pts_anomaly_threshold >=0 && live_source) { //reset just in case of live source |
920 |
if(pts_anomalies_counter > pts_anomaly_threshold) {
|
921 |
dctprintf(DEBUG_ANOMALIES, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
|
922 |
av_free_packet(&packet); |
923 |
goto close;
|
924 |
} |
925 |
} |
926 |
} |
927 |
|
928 |
//newTime_video and _audio are in usec
|
929 |
//if video and audio stamps differ more than 5sec
|
930 |
if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) { |
931 |
newtime_anomalies_counter++; |
932 |
dctprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME audio video differ anomaly detected number %d (a:%lld, v:%lld)\n", newtime_anomalies_counter, newTime_audio, newTime_video);
|
933 |
} |
934 |
|
935 |
if(newtime_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) { |
936 |
if(live_source) { //restart just in case of live source |
937 |
dctprintf(DEBUG_ANOMALIES, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
|
938 |
av_free_packet(&packet); |
939 |
goto close;
|
940 |
} |
941 |
} |
942 |
|
943 |
// Is this a packet from the video stream?
|
944 |
if(packet.stream_index==videoStream)
|
945 |
{ |
946 |
if(!live_source)
|
947 |
{ |
948 |
if(audioStream != -1) { //take this "time bank" method into account only if we have audio track |
949 |
// lateTime < 0 means a positive time account that can be used to decode video frames
|
950 |
// if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
|
951 |
// therefore, it's better to skip the frame
|
952 |
if(timebank && (lateTime+maxVDecodeTime) >= 0) |
953 |
{ |
954 |
dcprintf(DEBUG_ANOMALIES, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
|
955 |
av_free_packet(&packet); |
956 |
continue;
|
957 |
} |
958 |
} |
959 |
} |
960 |
|
961 |
gettimeofday(&tmp_tv, NULL);
|
962 |
|
963 |
//decode the video packet into a raw pFrame
|
964 |
|
965 |
if(avcodec_decode_video2(pCodecCtx, pFrame1, &frameFinished, &packet)>0) |
966 |
{ |
967 |
AVFrame *pFrame; |
968 |
pFrame = pFrame1; |
969 |
|
970 |
// usleep(5000);
|
971 |
dctprintf(DEBUG_VIDEO_FRAMES, "VIDEOin pkt: dts %"PRId64" pts %"PRId64" pts-dts %"PRId64"\n", packet.dts, packet.pts, packet.pts-packet.dts ); |
972 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame->pkt_dts, pFrame->pkt_pts, pFrame->pts); |
973 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame->pict_type, pFrame->key_frame ? " (key)" : ""); |
974 |
|
975 |
if(frameFinished)
|
976 |
{ // it must be true all the time else error
|
977 |
AVFrame *pFrame2 = NULL;
|
978 |
|
979 |
frame->number = ++contFrameVideo; |
980 |
|
981 |
|
982 |
|
983 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: finished frame %d dts %"PRId64" pts %"PRId64"\n", frame->number, packet.dts, packet.pts); |
984 |
if(frame->number==0) { |
985 |
if(packet.dts==AV_NOPTS_VALUE)
|
986 |
{ |
987 |
//a Dts with a noPts value is troublesome case for delta calculation based on Dts
|
988 |
contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0); |
989 |
av_free_packet(&packet); |
990 |
continue;
|
991 |
} |
992 |
last_pkt_dts = packet.dts; |
993 |
newTime = 0;
|
994 |
} |
995 |
else {
|
996 |
if(packet.dts!=AV_NOPTS_VALUE) {
|
997 |
delta_video = packet.dts-last_pkt_dts; |
998 |
last_pkt_dts = packet.dts; |
999 |
} |
1000 |
else if(delta_video==0) |
1001 |
{ |
1002 |
//a Dts with a noPts value is troublesome case for delta calculation based on Dts
|
1003 |
contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0); |
1004 |
av_free_packet(&packet); |
1005 |
continue;
|
1006 |
} |
1007 |
} |
1008 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: deltavideo : %d\n", (int)delta_video); |
1009 |
|
1010 |
//set initial timestamp
|
1011 |
if(FirstTimeVideo && pFrame->pkt_pts>0) { |
1012 |
if(offset_av) {
|
1013 |
ptsvideo1 = pFrame->pkt_pts; |
1014 |
FirstTimeVideo = 0;
|
1015 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1); |
1016 |
} else { //we want to compensate audio and video offset for this source |
1017 |
//maintain the offset between audio pts and video pts
|
1018 |
//because in case of live source they have the same numbering
|
1019 |
if(ptsaudio1 > 0) //if we have already seen some audio frames... |
1020 |
ptsvideo1 = ptsaudio1; |
1021 |
else
|
1022 |
ptsvideo1 = pFrame->pkt_pts; |
1023 |
FirstTimeVideo = 0;
|
1024 |
dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1); |
1025 |
} |
1026 |
} |
1027 |
|
1028 |
// store timestamp in useconds for next frame sleep
|
1029 |
if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
|
1030 |
newTime_video = pts2ms(pFrame->pkt_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base)*1000;
|
1031 |
} else {
|
1032 |
newTime_video = pts2ms(pFrame->pkt_dts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base)*1000; //TODO: a better estimate is needed |
1033 |
} |
1034 |
dcprintf(DEBUG_VIDEO_FRAMES, "Setting v:%lld\n", newTime_video);
|
1035 |
|
1036 |
if(passthrough) { //copy channel |
1037 |
video_frame_size = packet.size; |
1038 |
if (video_frame_size > video_outbuf_size) {
|
1039 |
fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
|
1040 |
av_free_packet(&packet); |
1041 |
continue;
|
1042 |
} else {
|
1043 |
memcpy(video_outbuf, packet.data, video_frame_size); |
1044 |
} |
1045 |
|
1046 |
if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
|
1047 |
target_pts = pFrame->pkt_pts; |
1048 |
}else { //TODO: review this |
1049 |
target_pts = pFrame->pkt_dts; |
1050 |
} |
1051 |
createFrame(frame, pts2ms(target_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base), video_frame_size, |
1052 |
pFrame->pict_type); |
1053 |
addFrameToOutstream(&outstream[0], frame, video_outbuf);
|
1054 |
} |
1055 |
|
1056 |
if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
|
1057 |
pFrame->pts = av_rescale_q(pFrame->pkt_pts, pFormatCtx->streams[videoStream]->time_base, outstream[(passthrough?1:0)].pCodecCtxEnc->time_base); |
1058 |
} else { //try to figure out the pts //TODO: review this |
1059 |
if (pFrame->pkt_dts != AV_NOPTS_VALUE) {
|
1060 |
pFrame->pts = av_rescale_q(pFrame->pkt_dts, pFormatCtx->streams[videoStream]->time_base, outstream[(passthrough?1:0)].pCodecCtxEnc->time_base); |
1061 |
} |
1062 |
} |
1063 |
|
1064 |
pFrame2 = preprocessFrame(pFrame); |
1065 |
if (pFrame2) pFrame = pFrame2;
|
1066 |
|
1067 |
for (i=(passthrough?1:0); i < (passthrough?1:0) + qualitylevels + (indexchannel?1:0); i++) { |
1068 |
video_frame_size = transcodeFrame(video_outbuf, video_outbuf_size, &target_pts, pFrame, pFormatCtx->streams[videoStream]->time_base, pCodecCtx, outstream[i].pCodecCtxEnc); |
1069 |
if (video_frame_size <= 0) { |
1070 |
av_free_packet(&packet); |
1071 |
contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0); |
1072 |
continue; //TODO: this seems wrong, continuing the internal cycle |
1073 |
} |
1074 |
createFrame(frame, pts2ms(target_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base), video_frame_size, |
1075 |
(unsigned char)outstream[i].pCodecCtxEnc->coded_frame->pict_type); |
1076 |
addFrameToOutstream(&outstream[i], frame, video_outbuf); |
1077 |
} |
1078 |
|
1079 |
|
1080 |
//compute how long it took to encode video frame
|
1081 |
gettimeofday(&now_tv, NULL);
|
1082 |
long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000; |
1083 |
usec+=(now_tv.tv_usec-tmp_tv.tv_usec); |
1084 |
if(usec > maxVDecodeTime)
|
1085 |
maxVDecodeTime = usec; |
1086 |
|
1087 |
//we DONT have an audio track, so we compute timings and determine
|
1088 |
//how much time we have to sleep at next VIDEO frame taking
|
1089 |
//also into account how much time was needed to encode the current
|
1090 |
//video frame
|
1091 |
//all this in case the video source is not live, i.e. not self-timing
|
1092 |
//and only in case there is no audio track
|
1093 |
if(audioStream == -1) { |
1094 |
if(!live_source) {
|
1095 |
if(newTime_prev != 0) { |
1096 |
//how much delay between video frames ideally
|
1097 |
long long maxDelay = newTime_video - newTime_prev; |
1098 |
sleep = (maxDelay - usec); |
1099 |
dcprintf(DEBUG_ANOMALIES,"\tmaxDelay=%ld\n", ((long)maxDelay)); |
1100 |
dcprintf(DEBUG_ANOMALIES,"\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep)); |
1101 |
} |
1102 |
else
|
1103 |
sleep = 0;
|
1104 |
|
1105 |
//update and store counters
|
1106 |
newTime_prev = newTime_video; |
1107 |
|
1108 |
//i can also sleep now instead of at the beginning of
|
1109 |
//the next frame because in this case we only have video
|
1110 |
//frames, hence it would immediately be the next thing to do
|
1111 |
if(sleep > 0) { |
1112 |
dcprintf(DEBUG_TIMESTAMPING,"\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
|
1113 |
usleep(sleep); |
1114 |
} |
1115 |
|
1116 |
} |
1117 |
} |
1118 |
if(pFrame2) av_free(pFrame2);
|
1119 |
} |
1120 |
} |
1121 |
} else if(packet.stream_index==audioStream) { |
1122 |
if(sleep > 0) |
1123 |
{ |
1124 |
dcprintf(DEBUG_TIMESTAMPING, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
|
1125 |
usleep(sleep); |
1126 |
} |
1127 |
|
1128 |
audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE; |
1129 |
//decode the audio packet into a raw audio source buffer
|
1130 |
if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0) |
1131 |
{ |
1132 |
dcprintf(DEBUG_AUDIO_FRAMES, "\n-------AUDIO FRAME\n");
|
1133 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base)); |
1134 |
if(audio_data_size>0) { |
1135 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: datasizeaudio:%d\n", audio_data_size);
|
1136 |
/* if a frame has been decoded, output it */
|
1137 |
//fwrite(samples, 1, audio_data_size, outfileaudio);
|
1138 |
} |
1139 |
else {
|
1140 |
av_free_packet(&packet); |
1141 |
continue;
|
1142 |
} |
1143 |
|
1144 |
audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples); |
1145 |
if(audio_frame_size <= 0) { |
1146 |
av_free_packet(&packet); |
1147 |
continue;
|
1148 |
} |
1149 |
|
1150 |
frame->number = contFrameAudio; |
1151 |
|
1152 |
if(frame->number==0) { |
1153 |
if(packet.dts==AV_NOPTS_VALUE) {
|
1154 |
av_free_packet(&packet); |
1155 |
continue;
|
1156 |
} |
1157 |
last_pkt_dts_audio = packet.dts; |
1158 |
newTime = 0;
|
1159 |
} |
1160 |
else {
|
1161 |
if(packet.dts!=AV_NOPTS_VALUE) {
|
1162 |
delta_audio = packet.dts-last_pkt_dts_audio; |
1163 |
last_pkt_dts_audio = packet.dts; |
1164 |
} |
1165 |
else if(delta_audio==0) { |
1166 |
av_free_packet(&packet); |
1167 |
continue;
|
1168 |
} |
1169 |
} |
1170 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
|
1171 |
//use pts if dts is invalid
|
1172 |
if(packet.dts!=AV_NOPTS_VALUE)
|
1173 |
target_pts = packet.dts; |
1174 |
else if(packet.pts!=AV_NOPTS_VALUE) { |
1175 |
target_pts = packet.pts; |
1176 |
} else {
|
1177 |
av_free_packet(&packet); |
1178 |
continue;
|
1179 |
} |
1180 |
|
1181 |
if(offset_av)
|
1182 |
{ |
1183 |
if(FirstTimeAudio && packet.dts>0) { |
1184 |
ptsaudio1 = packet.dts; |
1185 |
FirstTimeAudio = 0;
|
1186 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1); |
1187 |
} |
1188 |
} |
1189 |
else //we want to compensate audio and video offset for this source |
1190 |
{ |
1191 |
if(FirstTimeAudio && packet.dts>0) { |
1192 |
//maintain the offset between audio pts and video pts
|
1193 |
//because in case of live source they have the same numbering
|
1194 |
if(ptsvideo1 > 0) //if we have already seen some video frames... |
1195 |
ptsaudio1 = ptsvideo1; |
1196 |
else
|
1197 |
ptsaudio1 = packet.dts; |
1198 |
FirstTimeAudio = 0;
|
1199 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1); |
1200 |
} |
1201 |
} |
1202 |
//compute the new audio timestamps in milliseconds
|
1203 |
if(frame->number>0) { |
1204 |
newTime = ((target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio; |
1205 |
// store timestamp in useconds for next frame sleep
|
1206 |
newTime_audio = newTime*1000;
|
1207 |
} |
1208 |
dcprintf(DEBUG_TIMESTAMPING, "AUDIO: NEWTIMESTAMP %lld\n", newTime);
|
1209 |
if(newTime<0) { |
1210 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SKIPPING FRAME\n");
|
1211 |
newtime_anomalies_counter++; |
1212 |
dctprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d (a:%lld)\n", newtime_anomalies_counter, newTime*1000); |
1213 |
av_free_packet(&packet); |
1214 |
continue; //SKIP THIS FRAME, bad timestamp |
1215 |
} |
1216 |
|
1217 |
frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000; |
1218 |
frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
|
1219 |
frame->size = audio_frame_size; |
1220 |
frame->type = 5; // 5 is audio type |
1221 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: pts %"PRId64" duration %d timebase %d %d dts %"PRId64"\n", packet.pts, packet.duration, pFormatCtx->streams[audioStream]->time_base.num, pFormatCtx->streams[audioStream]->time_base.den, packet.dts); |
1222 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: timestamp sec:%ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec); |
1223 |
dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: deltaaudio %"PRId64"\n", delta_audio); |
1224 |
contFrameAudio++; |
1225 |
|
1226 |
if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) { |
1227 |
fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
|
1228 |
exit(-1);
|
1229 |
} |
1230 |
//set priority
|
1231 |
chunkaudio->priority = 1;
|
1232 |
|
1233 |
if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
|
1234 |
// is chunk filled using current strategy?
|
1235 |
//SAVE ON FILE
|
1236 |
//saveChunkOnFile(chunkaudio);
|
1237 |
//Send the chunk to an external transport/player
|
1238 |
for (i=0; i < (passthrough?1:0) + qualitylevels; i++) { //do not send audio to the index channel |
1239 |
sendChunk(outstream[i].output, chunkaudio); |
1240 |
} |
1241 |
dctprintf(DEBUG_CHUNKER, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
|
1242 |
chunkaudio->seq = 0; //signal that we need an increase |
1243 |
//initChunk(chunkaudio, &seq_current_chunk);
|
1244 |
} |
1245 |
|
1246 |
//we have an audio track, so we compute timings and determine
|
1247 |
//how much time we have to sleep at next audio frame taking
|
1248 |
//also into account how much time was needed to encode the
|
1249 |
//video frames
|
1250 |
//all this in case the video source is not live, i.e. not self-timing
|
1251 |
if(!live_source)
|
1252 |
{ |
1253 |
if(newTime_prev != 0) |
1254 |
{ |
1255 |
long long maxDelay = newTime_audio - newTime_prev; |
1256 |
|
1257 |
gettimeofday(&now_tv, NULL);
|
1258 |
long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000; |
1259 |
usec+=(now_tv.tv_usec-lastAudioSent.tv_usec); |
1260 |
|
1261 |
if(usec > maxAudioInterval)
|
1262 |
maxAudioInterval = usec; |
1263 |
|
1264 |
lateTime -= (maxDelay - usec); |
1265 |
dcprintf(DEBUG_TIMESTAMPING,"\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval)); |
1266 |
dcprintf(DEBUG_TIMESTAMPING,"\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime)); |
1267 |
|
1268 |
if((lateTime+maxAudioInterval) < 0) |
1269 |
sleep = (lateTime+maxAudioInterval)*-1;
|
1270 |
else
|
1271 |
sleep = 0;
|
1272 |
} |
1273 |
else
|
1274 |
sleep = 0;
|
1275 |
|
1276 |
newTime_prev = newTime_audio; |
1277 |
gettimeofday(&lastAudioSent, NULL);
|
1278 |
} |
1279 |
} |
1280 |
} |
1281 |
dcprintf(DEBUG_CHUNKER,"Free the packet that was allocated by av_read_frame\n");
|
1282 |
av_free_packet(&packet); |
1283 |
} |
1284 |
|
1285 |
if(videotrace)
|
1286 |
fclose(videotrace); |
1287 |
if(psnrtrace)
|
1288 |
fclose(psnrtrace); |
1289 |
|
1290 |
close:
|
1291 |
for (i=0; i < (passthrough?1:0) + qualitylevels + (indexchannel?1:0); i++) { |
1292 |
if(outstream[i].chunk->seq != 0 && outstream[i].chunk->frames_num>0) { |
1293 |
sendChunk(outstream[i].output, outstream[0].chunk);
|
1294 |
dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
|
1295 |
outstream[i].chunk->seq = 0; //signal that we need an increase just in case we will restart |
1296 |
} |
1297 |
} |
1298 |
for (i=0; i < (passthrough?1:0) + qualitylevels; i++) { |
1299 |
if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) { |
1300 |
sendChunk(outstream[i].output, chunkaudio); |
1301 |
dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
|
1302 |
} |
1303 |
} |
1304 |
chunkaudio->seq = 0; //signal that we need an increase just in case we will restart |
1305 |
|
1306 |
#ifdef HTTPIO
|
1307 |
/* finalize the HTTP chunk pusher */
|
1308 |
finalizeChunkPusher(); |
1309 |
#endif
|
1310 |
|
1311 |
for (i=0; i < (passthrough?1:0) + qualitylevels + (indexchannel?1:0); i++) { |
1312 |
free(outstream[i].chunk); |
1313 |
} |
1314 |
free(chunkaudio); |
1315 |
free(frame); |
1316 |
av_free(video_outbuf); |
1317 |
av_free(audio_outbuf); |
1318 |
free(cmeta); |
1319 |
|
1320 |
// Free the YUV frame
|
1321 |
av_free(pFrame1); |
1322 |
av_free(samples); |
1323 |
|
1324 |
// Close the codec
|
1325 |
avcodec_close(pCodecCtx); |
1326 |
for (i=(passthrough?1:0); i < (passthrough?1:0) + qualitylevels + (indexchannel?1:0); i++) { |
1327 |
avcodec_close(outstream[i].pCodecCtxEnc); |
1328 |
} |
1329 |
|
1330 |
if(audioStream!=-1) { |
1331 |
avcodec_close(aCodecCtx); |
1332 |
avcodec_close(aCodecCtxEnc); |
1333 |
} |
1334 |
|
1335 |
// Close the video file
|
1336 |
av_close_input_file(pFormatCtx); |
1337 |
|
1338 |
if(LOOP_MODE) {
|
1339 |
//we want video to continue, but the av_read_frame stopped
|
1340 |
//lets wait a 5 secs, and cycle in again
|
1341 |
usleep(5000000);
|
1342 |
dcprintf(DEBUG_CHUNKER, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
|
1343 |
videoStream = -1;
|
1344 |
audioStream = -1;
|
1345 |
FirstTimeAudio=1;
|
1346 |
FirstTimeVideo=1;
|
1347 |
pts_anomalies_counter=0;
|
1348 |
newtime_anomalies_counter=0;
|
1349 |
newTime=0;
|
1350 |
newTime_audio=0;
|
1351 |
newTime_prev=0;
|
1352 |
ptsvideo1=0;
|
1353 |
ptsaudio1=0;
|
1354 |
last_pkt_dts=0;
|
1355 |
delta_video=0;
|
1356 |
delta_audio=0;
|
1357 |
last_pkt_dts_audio=0;
|
1358 |
target_pts=0;
|
1359 |
i=0;
|
1360 |
//~ contFrameVideo = 0;
|
1361 |
//~ contFrameAudio = 1;
|
1362 |
|
1363 |
#ifdef YUV_RECORD_ENABLED
|
1364 |
if(ChunkerStreamerTestMode)
|
1365 |
{ |
1366 |
video_record_count++; |
1367 |
//~ savedVideoFrames = 0;
|
1368 |
|
1369 |
//~ char tmp_filename[255];
|
1370 |
//~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
|
1371 |
//~ FILE *pFile=fopen(tmp_filename, "w");
|
1372 |
//~ if(pFile!=NULL)
|
1373 |
//~ fclose(pFile);
|
1374 |
} |
1375 |
#endif
|
1376 |
|
1377 |
goto restart;
|
1378 |
} |
1379 |
|
1380 |
#ifdef TCPIO
|
1381 |
for (i=0; i < (passthrough?1:0) + qualitylevels + (indexchannel?1:0); i++) { |
1382 |
finalizeTCPChunkPusher(outstream[i].output); |
1383 |
} |
1384 |
#endif
|
1385 |
|
1386 |
#ifdef USE_AVFILTER
|
1387 |
close_filters(); |
1388 |
#endif
|
1389 |
|
1390 |
return 0; |
1391 |
} |
1392 |
|
1393 |
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf) {
|
1394 |
//the frame.h gets encoded into 5 slots of 32bits (3 ints plus 2 more for the timeval struct
|
1395 |
static int sizeFrameHeader = 5*sizeof(int32_t); |
1396 |
|
1397 |
//moving temp pointer to encode Frame on the wire
|
1398 |
uint8_t *tempdata = NULL;
|
1399 |
|
1400 |
if(chunk->seq == 0) { |
1401 |
initChunk(chunk, &seq_current_chunk); |
1402 |
} |
1403 |
//add frame priority to chunk priority (to be normalized later on)
|
1404 |
chunk->priority += frame->type + 1; // I:2, P:3, B:4 |
1405 |
|
1406 |
//HINT on malloc
|
1407 |
chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
|
1408 |
if(!chunk->data) {
|
1409 |
fprintf(stderr, "Memory error in chunk!!!\n");
|
1410 |
return -1; |
1411 |
} |
1412 |
chunk->frames_num++; // number of frames in the current chunk
|
1413 |
|
1414 |
/*
|
1415 |
//package the Frame header
|
1416 |
tempdata = chunk->data+chunk->payload_len;
|
1417 |
*((int32_t *)tempdata) = frame->number;
|
1418 |
tempdata+=sizeof(int32_t);
|
1419 |
*((struct timeval *)tempdata) = frame->timestamp;
|
1420 |
tempdata+=sizeof(struct timeval);
|
1421 |
*((int32_t *)tempdata) = frame->size;
|
1422 |
tempdata+=sizeof(int32_t);
|
1423 |
*((int32_t *)tempdata) = frame->type;
|
1424 |
tempdata+=sizeof(int32_t);
|
1425 |
*/
|
1426 |
//package the Frame header: network order and platform independent
|
1427 |
tempdata = chunk->data+chunk->payload_len; |
1428 |
bit32_encoded_push(frame->number, tempdata); |
1429 |
bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE); |
1430 |
bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
|
1431 |
bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
|
1432 |
bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
|
1433 |
|
1434 |
//insert the new frame data
|
1435 |
memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size); |
1436 |
chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
|
1437 |
//chunk lenght is updated just prior to pushing it out because
|
1438 |
//the chunk header len is better calculated there
|
1439 |
//chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
|
1440 |
|
1441 |
//update timestamps
|
1442 |
if(((int)frame->timestamp.tv_sec < (int)chunk->start_time.tv_sec) || ((int)frame->timestamp.tv_sec==(int)chunk->start_time.tv_sec && (int)frame->timestamp.tv_usec < (int)chunk->start_time.tv_usec) || (int)chunk->start_time.tv_sec==-1) { |
1443 |
chunk->start_time.tv_sec = frame->timestamp.tv_sec; |
1444 |
chunk->start_time.tv_usec = frame->timestamp.tv_usec; |
1445 |
} |
1446 |
|
1447 |
if(((int)frame->timestamp.tv_sec > (int)chunk->end_time.tv_sec) || ((int)frame->timestamp.tv_sec==(int)chunk->end_time.tv_sec && (int)frame->timestamp.tv_usec > (int)chunk->end_time.tv_usec) || (int)chunk->end_time.tv_sec==-1) { |
1448 |
chunk->end_time.tv_sec = frame->timestamp.tv_sec; |
1449 |
chunk->end_time.tv_usec = frame->timestamp.tv_usec; |
1450 |
} |
1451 |
return 0; |
1452 |
} |
1453 |
|
1454 |
void SaveFrame(AVFrame *pFrame, int width, int height) |
1455 |
{ |
1456 |
FILE *pFile; |
1457 |
int y;
|
1458 |
|
1459 |
// Open file
|
1460 |
char tmp_filename[255]; |
1461 |
sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
|
1462 |
pFile=fopen(tmp_filename, "ab");
|
1463 |
if(pFile==NULL) |
1464 |
return;
|
1465 |
|
1466 |
// Write header
|
1467 |
//fprintf(pFile, "P5\n%d %d\n255\n", width, height);
|
1468 |
|
1469 |
// Write Y data
|
1470 |
for(y=0; y<height; y++) |
1471 |
if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width) |
1472 |
{ |
1473 |
printf("errno = %d\n", errno);
|
1474 |
exit(1);
|
1475 |
} |
1476 |
// Write U data
|
1477 |
for(y=0; y<height/2; y++) |
1478 |
if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2) |
1479 |
{ |
1480 |
printf("errno = %d\n", errno);
|
1481 |
exit(1);
|
1482 |
} |
1483 |
// Write V data
|
1484 |
for(y=0; y<height/2; y++) |
1485 |
if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2) |
1486 |
{ |
1487 |
printf("errno = %d\n", errno);
|
1488 |
exit(1);
|
1489 |
} |
1490 |
|
1491 |
// Close file
|
1492 |
fclose(pFile); |
1493 |
} |
1494 |
|
1495 |
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
|
1496 |
{ |
1497 |
static FILE* pFile = NULL; |
1498 |
|
1499 |
pFile=fopen("yuv_data/streamer_out.mpeg4", "ab"); |
1500 |
fwrite(frame, sizeof(Frame), 1, pFile); |
1501 |
fwrite(video_outbuf, frame->size, 1, pFile);
|
1502 |
fclose(pFile); |
1503 |
} |