Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ c3031a67

History | View | Annotate | Download (49.3 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

    
33
#define DEBUG
34
#define DEBUG_AUDIO_FRAMES  false
35
#define DEBUG_VIDEO_FRAMES  false
36
#define DEBUG_CHUNKER false
37
#define DEBUG_ANOMALIES true
38
#define DEBUG_TIMESTAMPING false
39
#include "dbg.h"
40

    
41
#define STREAMER_MAX(a,b) ((a>b)?(a):(b))
42
#define STREAMER_MIN(a,b) ((a<b)?(a):(b))
43

    
44
//#define DISPLAY_PSNR
45
#define GET_PSNR(x) ((x==0) ? 0 : (-10.0*log(x)/log(10)))
46

    
47
ChunkerMetadata *cmeta = NULL;
48
int seq_current_chunk = 1; //chunk numbering starts from 1; HINT do i need more bytes?
49

    
50
#define AUDIO_CHUNK 0
51
#define VIDEO_CHUNK 1
52

    
53
void SaveFrame(AVFrame *pFrame, int width, int height);
54
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf);
55
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf);
56
void bit32_encoded_push(uint32_t v, uint8_t *p);
57

    
58
int video_record_count = 0;
59
int savedVideoFrames = 0;
60
long int firstSavedVideoFrame = 0;
61
int ChunkerStreamerTestMode = 0;
62

    
63
int pts_anomaly_threshold = -1;
64
int newtime_anomaly_threshold = -1;
65
bool timebank = false;
66
char *outside_world_url = NULL;
67

    
68
int gop_size = 25;
69
int max_b_frames = 3;
70
bool vcopy = false;
71

    
72
long delay_audio = 0; //delay audio by x millisec
73

    
74
char *avfilter="yadif";
75

    
76
// Constant number of frames per chunk
77
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType)
78
{
79
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
80
        if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
81
                return 1;
82

    
83
        return 0;
84
}
85

    
86
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
87
// It can be considered as constant size.
88
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType)
89
{
90
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
91
        if(echunk->payload_len >= cmeta->targetChunkSize)
92
                return 1;
93
        
94
        return 0;
95
}
96

    
97
// Performace optimization.
98
// The chunkFilled function has been splitted into two functions (one for each strategy).
99
// Instead of continuously check the strategy flag (which is constant),
100
// 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)
101
int (*chunkFilled)(ExternalChunk *echunk, int chunkType);
102

    
103
void initChunk(ExternalChunk *chunk, int *seq_num) {
104
        chunk->seq = (*seq_num)++;
105
        chunk->frames_num = 0;
106
        chunk->payload_len = 0;
107
        chunk->len=0;
108
  if(chunk->data != NULL)
109
    free(chunk->data);
110
        chunk->data = NULL;
111
        chunk->start_time.tv_sec = -1;
112
        chunk->start_time.tv_usec = -1;
113
        chunk->end_time.tv_sec = -1;
114
        chunk->end_time.tv_usec = -1;
115
        chunk->priority = 0;
116
        chunk->category = 0;
117
        chunk->_refcnt = 0;
118
}
119

    
120
int quit = 0;
121

    
122
void sigproc()
123
{
124
        printf("you have pressed ctrl-c, terminating...\n");
125
        quit = 1;
126
}
127

    
128
static void print_usage(int argc, char *argv[])
129
{
130
  fprintf (stderr,
131
    "\nUsage:%s [options]\n"
132
    "\n"
133
    "Mandatory options:\n"
134
    "\t[-i input file]\n"
135
    "\t[-a audio bitrate]\n"
136
    "\t[-v video bitrate]\n\n"
137
    "Other options:\n"
138
    "\t[-F output] (overrides config file)\n"
139
    "\t[-A audioencoder]\n"
140
    "\t[-V videoencoder]\n"
141
    "\t[-s WxH]: force video size.\n"
142
    "\t[-l]: this is a live stream.\n"
143
    "\t[-o]: adjust A/V frame timestamps (deafault off, use it only with flawed containers)\n"
144
    "\t[-p]: pts anomaly threshold (default: -1=off).\n"
145
    "\t[-q]: sync anomaly threshold ((default: -1=off).\n"
146
    "\t[-t]: QoE test mode\n\n"
147

    
148
    "\t[--video_stream]:set video_stream ID in input\n"
149
    "\t[--audio_stream]:set audio_stream ID in input\n"
150
    "\t[--avfilter]:set input filter (default: yadif\n"
151
    "\t[--no-indexchannel]: turn off generation of index channel\n"
152
    "\t[--qualitylevels]:set number of quality levels\n"
153
    "\n"
154
    "Codec options:\n"
155
    "\t[-g GOP]: gop size\n"
156
    "\t[-b frames]: max number of consecutive b frames\n"
157
    "\t[-x extas]: extra video codec options (e.g. -x me_method=hex,flags2=+dct8x8+wpred+bpyrami+mixed_refs)\n"
158
    "\n"
159
    "=======================================================\n", argv[0]
160
    );
161
  }
162

    
163
int sendChunk(struct output *output, ExternalChunk *chunk) {
164
#ifdef HTTPIO
165
                                                return pushChunkHttp(chunk, outside_world_url);
166
#endif
167
#ifdef TCPIO
168
                                                return pushChunkTcp(output, chunk);
169
#endif
170
#ifdef UDPIO
171
                                                return pushChunkUDP(chunk);
172
#endif
173
}
174

    
175

    
176
int transcodeFrame(uint8_t *video_outbuf, int video_outbuf_size, int64_t *target_pts, AVFrame *pFrame, AVRational time_base, AVCodecContext *pCodecCtx, AVCodecContext *pCodecCtxEnc)
177
{
178
        int video_frame_size = 0;
179
        AVFrame *pFrame2 = NULL;
180
        AVFrame *scaledFrame = NULL;
181
        pFrame2=avcodec_alloc_frame();
182
        scaledFrame=avcodec_alloc_frame();
183
        if(pFrame2==NULL || scaledFrame==NULL) {
184
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
185
                if(pFrame2) av_free(pFrame2);
186
                if(scaledFrame) av_free(scaledFrame);
187
                return -1;
188
        }
189
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height);
190
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
191
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height);
192
        if(!video_outbuf || !scaledFrame_buffer) {
193
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
194
                return -1;
195
        }
196

    
197
                                            if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
198
                                                pFrame->pts = av_rescale_q(pFrame->pkt_pts, time_base, pCodecCtxEnc->time_base);
199
                                            } else {        //try to figure out the pts //TODO: review this
200
                                                if (pFrame->pkt_dts != AV_NOPTS_VALUE) {
201
                                                        pFrame->pts = av_rescale_q(pFrame->pkt_dts, time_base, pCodecCtxEnc->time_base);
202
                                                }
203
                                            }
204

    
205
#ifdef VIDEO_DEINTERLACE
206
                                            avpicture_deinterlace(
207
                                                        (AVPicture*) pFrame,
208
                                                        (const AVPicture*) pFrame,
209
                                                        pCodecCtxEnc->pix_fmt,
210
                                                        pCodecCtxEnc->width,
211
                                                        pCodecCtxEnc->height);
212
#endif
213

    
214
#ifdef USE_AVFILTER
215
                                            //apply avfilters
216
                                            filter(pFrame,pFrame2);
217
                                            pFrame = pFrame2;
218
                                            dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame2->pkt_dts, pFrame2->pkt_pts, pFrame2->pts);
219
                                            dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame2->pict_type, pFrame2->key_frame ? " (key)" : "");
220
#endif
221

    
222
                                            if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
223
//                                                static AVPicture pict;
224
                                                static struct SwsContext *img_convert_ctx = NULL;
225

    
226
                                                pFrame->pict_type = 0;
227
                                                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);
228
                                                if(img_convert_ctx == NULL) {
229
                                                        fprintf(stderr, "Cannot initialize the conversion context!\n");
230
                                                        exit(1);
231
                                                }
232
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
233
                                                scaledFrame->pts = pFrame->pts;
234
                                                scaledFrame->pict_type = 0;
235
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
236
                                            } else {
237
                                                pFrame->pict_type = 0;
238
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
239
                                            }
240

    
241
                                            //use pts if dts is invalid
242
                                            if(pCodecCtxEnc->coded_frame->pts!=AV_NOPTS_VALUE)
243
                                                *target_pts = av_rescale_q(pCodecCtxEnc->coded_frame->pts, pCodecCtxEnc->time_base, time_base);
244
                                            else {        //TODO: review this
245
                                                if(pFrame2) av_free(pFrame2);
246
                                                if(scaledFrame) av_free(scaledFrame);
247
                                                if(scaledFrame_buffer) av_free(scaledFrame_buffer);
248
                                                return -1;
249
                                            }
250

    
251
                                        if(video_frame_size > 0) {
252
                                            if(pCodecCtxEnc->coded_frame) {
253
                                                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);
254
                                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOout: outtype: %d%s\n", pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
255
                                            }
256
#ifdef DISPLAY_PSNR
257
                                            static double ist_psnr = 0;
258
                                            static double cum_psnr = 0;
259
                                            static int psnr_samples = 0;
260
                                            if(pCodecCtxEnc->coded_frame) {
261
                                                if(pCodecCtxEnc->flags&CODEC_FLAG_PSNR) {
262
                                                        ist_psnr = GET_PSNR(pCodecCtxEnc->coded_frame->error[0]/(pCodecCtxEnc->width*pCodecCtxEnc->height*255.0*255.0));
263
                                                        psnr_samples++;
264
                                                        cum_psnr += ist_psnr;
265
                                                        fprintf(stderr, "PSNR: ist %.4f avg: %.4f\n", ist_psnr, cum_psnr / (double)psnr_samples);
266
                                                }
267
                                            }
268
#endif
269
                                        }
270

    
271
        if(pFrame2) av_free(pFrame2);
272
        if(scaledFrame) av_free(scaledFrame);
273
        if(scaledFrame_buffer) av_free(scaledFrame_buffer);
274
        return video_frame_size;
275
}
276

    
277

    
278
void createFrame(struct Frame *frame, long long newTime, int video_frame_size, int pict_type)
279
{
280

    
281
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
282
                                        frame->timestamp.tv_usec = newTime%1000;
283
                                        frame->size = video_frame_size;
284
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
285
                                        frame->type = pict_type;
286

    
287

    
288
/* should be on some other place
289
//                                        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);
290
//                                        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);
291

292
#ifdef YUV_RECORD_ENABLED
293
                                        if(!vcopy && ChunkerStreamerTestMode)
294
                                        {
295
                                                if(videotrace)
296
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pict_type, frame->size);
297

298
                                                SaveFrame(pFrame, dest_width, dest_height);
299

300
                                                ++savedVideoFrames;
301
                                                SaveEncodedFrame(frame, video_outbuf);
302

303
                                                if(!firstSavedVideoFrame)
304
                                                        firstSavedVideoFrame = frame->number;
305

306
                                                char tmp_filename[255];
307
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
308
                                                FILE* tmp = fopen(tmp_filename, "w");
309
                                                if(tmp)
310
                                                {
311
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
312
                                                                ,dest_width, dest_height
313
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
314
                                                        fclose(tmp);
315
                                                }
316
                                        }
317
#endif
318
*/
319

    
320
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
321
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: timestamped sec %ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec);
322
}
323

    
324

    
325
void addFrameToOutstream(struct outstream *os, Frame *frame, uint8_t *video_outbuf)
326
{
327

    
328
        ExternalChunk *chunk = os->chunk;
329
        struct output *output = os->output;
330

    
331
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
332
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
333
                                                exit(-1);
334
                                        }
335

    
336
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
337
                                                //calculate priority
338
                                                chunk->priority /= chunk->frames_num;
339

    
340
                                                //SAVE ON FILE
341
                                                //saveChunkOnFile(chunk);
342
                                                //Send the chunk to an external transport/player
343
                                                sendChunk(output, chunk);
344
                                                dctprintf(DEBUG_CHUNKER, "VIDEO: sent chunk video %d, prio:%f, size %d\n", chunk->seq, chunk->priority, chunk->len);
345
                                                chunk->seq = 0; //signal that we need an increase
346
                                                //initChunk(chunk, &seq_current_chunk);
347
                                        }
348
}
349

    
350
long long pts2ms(int64_t pts, AVRational time_base)
351
{
352
        return pts * 1000 * time_base.num / time_base.den;
353
}
354

    
355
AVCodecContext *openVideoEncoder(const char *video_codec, int video_bitrate, int dest_width, int dest_height, AVRational time_base, const char *codec_options) {
356

    
357
        AVCodec *pCodecEnc;
358
        AVCodecContext *pCodecCtxEnc;
359

    
360
        //setup video output encoder
361
        if (strcmp(video_codec, "copy") == 0) {
362
                return NULL;
363
        }
364

    
365
        pCodecEnc = avcodec_find_encoder_by_name(video_codec);
366
        if (pCodecEnc) {
367
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
368
        } else {
369
                fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
370
                return NULL; // Codec not found
371
        }
372

    
373
        pCodecCtxEnc=avcodec_alloc_context();
374
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
375
        pCodecCtxEnc->codec_id = pCodecEnc->id;
376

    
377
        pCodecCtxEnc->bit_rate = video_bitrate;
378
        //~ pCodecCtxEnc->qmin = 30;
379
        //~ pCodecCtxEnc->qmax = 30;
380
        //times 20 follows the defaults, was not needed in previous versions of libavcodec
381
//        pCodecCtxEnc->crf = 20.0f;
382
        // resolution must be a multiple of two 
383
        pCodecCtxEnc->width = dest_width;
384
        pCodecCtxEnc->height = dest_height;
385
        // frames per second 
386
        //~ pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
387
        //printf("pCodecCtx->time_base=%d/%d\n", pCodecCtx->time_base.num, pCodecCtx->time_base.den);
388
        pCodecCtxEnc->time_base= time_base;//(AVRational){1,25};
389
        pCodecCtxEnc->gop_size = gop_size; // emit one intra frame every gop_size frames 
390
        pCodecCtxEnc->max_b_frames = max_b_frames;
391
        pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P;
392
        pCodecCtxEnc->flags |= CODEC_FLAG_PSNR;
393
        //~ pCodecCtxEnc->flags |= CODEC_FLAG_QSCALE;
394

    
395
        //some generic quality tuning
396
        pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD;
397

    
398
        //some rate control parameters for streaming, taken from ffserver.c
399
        {
400
        /* Bitrate tolerance is less for streaming */
401
        AVCodecContext *av = pCodecCtxEnc;
402
        if (av->bit_rate_tolerance == 0)
403
            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
404
                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);
405
        //if (av->qmin == 0)
406
        //    av->qmin = 3;
407
        //if (av->qmax == 0)
408
        //    av->qmax = 31;
409
        //if (av->max_qdiff == 0)
410
        //    av->max_qdiff = 3;
411
        //av->qcompress = 0.5;
412
        //av->qblur = 0.5;
413

    
414
        //if (!av->nsse_weight)
415
        //    av->nsse_weight = 8;
416

    
417
        //av->frame_skip_cmp = FF_CMP_DCTMAX;
418
        //if (!av->me_method)
419
        //    av->me_method = ME_EPZS;
420
        //av->rc_buffer_aggressivity = 1.0;
421

    
422
        //if (!av->rc_eq)
423
        //    av->rc_eq = "tex^qComp";
424
        //if (!av->i_quant_factor)
425
        //    av->i_quant_factor = -0.8;
426
        //if (!av->b_quant_factor)
427
        //    av->b_quant_factor = 1.25;
428
        //if (!av->b_quant_offset)
429
        //    av->b_quant_offset = 1.25;
430
        if (!av->rc_max_rate)
431
            av->rc_max_rate = av->bit_rate * 2;
432

    
433
        if (av->rc_max_rate && !av->rc_buffer_size) {
434
            av->rc_buffer_size = av->rc_max_rate;
435
        }
436
        }
437
        //end of code taken fromffserver.c
438

    
439
  switch (pCodecEnc->id) {
440
    case CODEC_ID_H264 :
441
        // Fast Profile
442
        // libx264-fast.ffpreset preset 
443
        pCodecCtxEnc->coder_type = FF_CODER_TYPE_AC; // coder = 1 -> enable CABAC
444
        pCodecCtxEnc->flags |= CODEC_FLAG_LOOP_FILTER; // flags=+loop -> deblock
445
        pCodecCtxEnc->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1
446
        pCodecCtxEnc->partitions |= X264_PART_I8X8|X264_PART_I4X4|X264_PART_P8X8|X264_PART_B8X8;        // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
447
        pCodecCtxEnc->me_method=ME_HEX; // me_method=hex
448
        pCodecCtxEnc->me_subpel_quality = 6; // subq=7
449
        pCodecCtxEnc->me_range = 16; // me_range=16
450
        //pCodecCtxEnc->gop_size = 250; // g=250
451
        //pCodecCtxEnc->keyint_min = 25; // keyint_min=25
452
        pCodecCtxEnc->scenechange_threshold = 40; // sc_threshold=40
453
        pCodecCtxEnc->i_quant_factor = 0.71; // i_qfactor=0.71
454
        pCodecCtxEnc->b_frame_strategy = 1; // b_strategy=1
455
        pCodecCtxEnc->qcompress = 0.6; // qcomp=0.6
456
        pCodecCtxEnc->qmin = 10; // qmin=10
457
        pCodecCtxEnc->qmax = 51; // qmax=51
458
        pCodecCtxEnc->max_qdiff = 4; // qdiff=4
459
        //pCodecCtxEnc->max_b_frames = 3; // bf=3
460
        pCodecCtxEnc->refs = 2; // refs=3
461
        //pCodecCtxEnc->directpred = 1; // directpred=1
462
        pCodecCtxEnc->directpred = 3; // directpred=1 in preset -> "directpred", "direct mv prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)"
463
        //pCodecCtxEnc->trellis = 1; // trellis=1
464
        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
465
        pCodecCtxEnc->weighted_p_pred = 2; // wpredp=2
466

    
467
        // libx264-main.ffpreset preset
468
        //pCodecCtxEnc->flags2|=CODEC_FLAG2_8X8DCT;
469
        //pCodecCtxEnc->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
470
        //pCodecCtxEnc->crf = 22;
471

    
472
#ifdef STREAMER_X264_USE_SSIM
473
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
474
#endif
475

    
476
        //pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
477
        // pCodecCtxEnc->rc_min_rate = 0;
478
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
479
        // pCodecCtxEnc->rc_buffer_size = 0;
480
        break;
481
    case CODEC_ID_MPEG4 :
482
        break;
483
    default:
484
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
485
  }
486

    
487
  if ((av_set_options_string(pCodecCtxEnc, codec_options, "=", ",")) < 0) {
488
    fprintf(stderr, "Error parsing options string: '%s'\n", codec_options);
489
    return NULL;
490
  }
491

    
492
  if(avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
493
    fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
494
    return NULL; // Could not open codec
495
  }
496

    
497
 return pCodecCtxEnc;
498
}
499

    
500

    
501
int main(int argc, char *argv[]) {
502
        signal(SIGINT, sigproc);
503
        
504
        int i=0,j,k;
505

    
506
        //output variables
507
        uint8_t *video_outbuf = NULL;
508
        int video_outbuf_size, video_frame_size;
509
        uint8_t *audio_outbuf = NULL;
510
        int audio_outbuf_size, audio_frame_size;
511
        int audio_data_size;
512

    
513
        //numeric identifiers of input streams
514
        int videoStream = -1;
515
        int audioStream = -1;
516

    
517
//        int len1;
518
        int frameFinished;
519
        //frame sequential counters
520
        int contFrameAudio=1, contFrameVideo=0;
521
//        int numBytes;
522

    
523
        //command line parameters
524
        int audio_bitrate = -1;
525
        int video_bitrate = -1;
526
        char *audio_codec = "mp2";
527
        char *video_codec = "mpeg4";
528
        char *codec_options = "";
529
        int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file)
530
        int offset_av = 0; //tells to compensate for offset between audio and video in the file
531
        
532
        //a raw buffer for decoded uncompressed audio samples
533
        int16_t *samples = NULL;
534
        //a raw uncompressed video picture
535
        AVFrame *pFrame1 = NULL;
536

    
537
        AVFormatContext *pFormatCtx;
538
        AVCodecContext  *pCodecCtx = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL;
539
        AVCodec         *pCodec = NULL ,*aCodec = NULL ,*aCodecEnc = NULL;
540
        AVPacket         packet;
541

    
542
        //stuff needed to compute the right timestamps
543
        short int FirstTimeAudio=1, FirstTimeVideo=1;
544
        short int pts_anomalies_counter=0;
545
        short int newtime_anomalies_counter=0;
546
        long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0;
547
        struct timeval lastAudioSent = {0, 0};
548
        int64_t ptsvideo1=0;
549
        int64_t ptsaudio1=0;
550
        int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0;
551

    
552
        //Napa-Wine specific Frame and Chunk structures for transport
553
        Frame *frame = NULL;
554
        ExternalChunk *chunkaudio = NULL;
555
        
556
        char av_input[1024];
557
        int dest_width = -1;
558
        int dest_height = -1;
559
        
560
        static struct option long_options[] =
561
        {
562
                {"audio_stream", required_argument, 0, 0},
563
                {"video_stream", required_argument, 0, 0},
564
                {"avfilter", required_argument, 0, 0},
565
                {"indexchannel", no_argument, &indexchannel, 1},
566
                {"no-indexchannel", no_argument, &indexchannel, 0},
567
                {"qualitylevels", required_argument, 0, 'Q'},
568
                {0, 0, 0, 0}
569
        };
570
        /* `getopt_long' stores the option index here. */
571
        int option_index = 0, c;
572
        int mandatories = 0;
573
        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)
574
        {
575
                switch (c) {
576
                        case 0: //for long options
577
                                if( strcmp( "audio_stream", long_options[option_index].name ) == 0 ) { audioStream = atoi(optarg); }
578
                                if( strcmp( "video_stream", long_options[option_index].name ) == 0 ) { videoStream = atoi(optarg); }
579
                                if( strcmp( "avfilter", long_options[option_index].name ) == 0 ) { avfilter = strdup(optarg); }
580
                                break;
581
                        case 'i':
582
                                sprintf(av_input, "%s", optarg);
583
                                mandatories++;
584
                                break;
585
                        case 'a':
586
                                sscanf(optarg, "%d", &audio_bitrate);
587
                                mandatories++;
588
                                break;
589
                        case 'v':
590
                                sscanf(optarg, "%d", &video_bitrate);
591
                                mandatories++;
592
                                break;
593
                        case 'A':
594
                                audio_codec = strdup(optarg);
595
                                break;
596
                        case 'V':
597
                                video_codec = strdup(optarg);
598
                                break;
599
                        case 's':
600
                                sscanf(optarg, "%dx%d", &dest_width, &dest_height);
601
                                break;
602
                        case 'l':
603
                                live_source = 1;
604
                                break;
605
                        case 'o':
606
                                offset_av = 1;
607
                                break;
608
                        case 't':
609
                                ChunkerStreamerTestMode = 1;
610
                                break;
611
                        case 'p':
612
                                sscanf(optarg, "%d", &pts_anomaly_threshold);
613
                                break;
614
                        case 'q':
615
                                sscanf(optarg, "%d", &newtime_anomaly_threshold);
616
                                break;
617
                        case 'F':
618
                                outside_world_url = strdup(optarg);
619
                                break;
620
                        case 'g':
621
                                sscanf(optarg, "%d", &gop_size);
622
                                break;
623
                        case 'b':
624
                                sscanf(optarg, "%d", &max_b_frames);
625
                                break;
626
                        case 'd':
627
                                sscanf(optarg, "%ld", &delay_audio);
628
                                break;
629
                        case 'x':
630
                                codec_options = strdup(optarg);
631
                                break;
632
                        case 'Q':
633
                                sscanf(optarg, "%d", &qualitylevels);
634
                                if (qualitylevels > QUALITYLEVELS_MAX) {
635
                                        fprintf(stderr,"Too many quality levels: %d (max:%d)\n", qualitylevels, QUALITYLEVELS_MAX);
636
                                        return -1;
637
                                }
638
                                break;
639
                        default:
640
                                print_usage(argc, argv);
641
                                return -1;
642
                }
643
        }
644
        
645
        if(mandatories < 3) 
646
        {
647
                print_usage(argc, argv);
648
                return -1;
649
        }
650

    
651
#ifdef YUV_RECORD_ENABLED
652
        if(ChunkerStreamerTestMode)
653
        {
654
                DELETE_DIR("yuv_data");
655
                CREATE_DIR("yuv_data");
656
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
657
                //fclose(pFile);
658
        }
659
#endif
660

    
661
#ifdef TCPIO
662
        static char peer_ip[16];
663
        static int peer_port;
664
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
665
        if (res < 2) {
666
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
667
                return -2;
668
        }
669

    
670
        for (i=0; i < 1 + qualitylevels + (indexchannel?1:0); i++) {
671
                outstream[i].output = initTCPPush(peer_ip, peer_port+i);
672
                if (!outstream[i].output) {
673
                        fprintf(stderr, "Error initializing output module, exiting\n");
674
                        exit(1);
675
                }
676
        }
677
#endif
678

    
679
restart:
680
        // read the configuration file
681
        cmeta = chunkerInit();
682
        if (!outside_world_url) {
683
                outside_world_url = strdup(cmeta->outside_world_url);
684
        }
685
        switch(cmeta->strategy)
686
        {
687
                case 1:
688
                        chunkFilled = chunkFilledSizeStrategy;
689
                        break;
690
                default:
691
                        chunkFilled = chunkFilledFramesStrategy;
692
        }
693
                
694
        if(live_source)
695
                fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
696
        if(offset_av)
697
                fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
698

    
699
        // Register all formats and codecs
700
        av_register_all();
701

    
702
        // Open input file
703
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
704
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
705
                exit(-1);
706
        }
707

    
708
        // Retrieve stream information
709
        if(av_find_stream_info(pFormatCtx) < 0) {
710
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
711
                exit(-1);
712
        }
713

    
714
        // Dump information about file onto standard error
715
        av_dump_format(pFormatCtx, 0, av_input, 0);
716

    
717
        // Find the video and audio stream numbers
718
        for(i=0; i<pFormatCtx->nb_streams; i++) {
719
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
720
                        videoStream=i;
721
                }
722
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
723
                        audioStream=i;
724
                }
725
        }
726

    
727
        if(videoStream==-1 || audioStream==-1) {        // TODO: refine to work with 1 or the other
728
                fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
729
                exit(-1);
730
        }
731

    
732
        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);
733

    
734
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
735
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
736

    
737

    
738
        // Get a pointer to the codec context for the input video stream
739
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
740
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
741
        //extract W and H
742
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
743

    
744
        // Get a pointer to the codec context for the input audio stream
745
        if(audioStream != -1) {
746
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
747
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
748
        }
749

    
750
        // Figure out size
751
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
752
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
753

    
754
        //initialize outstream structures
755
        for (i=0; i < 1 + qualitylevels + (indexchannel?1:0); i++) {
756
                outstream[i].chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
757
                if(!outstream[i].chunk) {
758
                        fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
759
                        return -1;
760
                }
761
                outstream[i].chunk->data = NULL;
762
                outstream[i].chunk->seq = 0;
763
                dcprintf(DEBUG_CHUNKER, "INIT: chunk video %d\n", outstream[i].chunk->seq);
764
                outstream[i].pCodecCtxEnc = NULL;
765
        }
766
        outstream[0].pCodecCtxEnc = NULL;
767
        for (i=1,j=1,k=1; i < 1 + qualitylevels; i++) {
768
                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
769
                if (!outstream[i].pCodecCtxEnc) {
770
                        return -1;
771
                }
772
                j*=3;        //reduce bitrate to 1/3
773
                k*=2;        //reduce dimensions to 1/2
774
        }
775
        if (indexchannel) {
776
                outstream[qualitylevels + 1].pCodecCtxEnc = openVideoEncoder(video_codec, 50000, 160, 120, pCodecCtx->time_base, codec_options);
777
                if (!outstream[qualitylevels + 1].pCodecCtxEnc) {
778
                        return -1;
779
                }
780
        }
781

    
782
        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);
783

    
784
        if(pCodec==NULL) {
785
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
786
                return -1; // Codec not found
787
        }
788
        if(avcodec_open(pCodecCtx, pCodec)<0) {
789
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
790
                return -1; // Could not open codec
791
        }
792
        if(audioStream!=-1) {
793
                //setup audio output encoder
794
                aCodecCtxEnc = avcodec_alloc_context();
795
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
796
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
797
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
798
                aCodecCtxEnc->channels = aCodecCtx->channels;
799
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
800

    
801
                // Find the decoder for the audio stream
802
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
803
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
804
                if(aCodec==NULL) {
805
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
806
                        return -1;
807
                }
808
                if(aCodecEnc==NULL) {
809
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
810
                        return -1;
811
                }
812
        
813
                if(avcodec_open(aCodecCtx, aCodec)<0) {
814
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
815
                        return -1; // Could not open codec
816
                }
817
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
818
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
819
                        return -1; // Could not open codec
820
                }
821
        }
822
        else {
823
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
824
        }
825

    
826
        // Allocate audio in and out buffers
827
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
828
        if(samples == NULL) {
829
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
830
                return -1;
831
        }
832
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
833
        audio_outbuf = av_malloc(audio_outbuf_size);
834
        if(audio_outbuf == NULL) {
835
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
836
                return -1;
837
        }
838

    
839
        // Allocate video in frame and out buffer
840
        pFrame1=avcodec_alloc_frame();
841
        if(pFrame1==NULL) {
842
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
843
                return -1;
844
        }
845
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
846
        video_outbuf = av_malloc(video_outbuf_size);
847

    
848
        //allocate Napa-Wine transport
849
        frame = (Frame *)malloc(sizeof(Frame));
850
        if(!frame) {
851
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
852
                return -1;
853
        }
854

    
855
        //create empty first audio chunk
856

    
857
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
858
        if(!chunkaudio) {
859
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
860
                return -1;
861
        }
862
  chunkaudio->data=NULL;
863
        chunkaudio->seq = 0;
864
        //initChunk(chunkaudio, &seq_current_chunk);
865
        dcprintf(DEBUG_CHUNKER, "INIT: chunk audio %d\n", chunkaudio->seq);
866

    
867
#ifdef HTTPIO
868
        /* initialize the HTTP chunk pusher */
869
        initChunkPusher(); //TRIPLO
870
#endif
871

    
872
        long sleep=0;
873
        struct timeval now_tv;
874
        struct timeval tmp_tv;
875
        long long lateTime = 0;
876
        long long maxAudioInterval = 0;
877
        long long maxVDecodeTime = 0;
878
//        unsigned char lastIFrameDistance = 0;
879

    
880
#ifdef UDPIO
881
        static char peer_ip[16];
882
        static int peer_port;
883
        int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
884
        if (res < 2) {
885
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
886
                return -2;
887
        }
888
        
889
        initUDPPush(peer_ip, peer_port);
890
#endif
891
        
892
        char videotrace_filename[255];
893
        char psnr_filename[255];
894
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
895
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
896
        FILE* videotrace = fopen(videotrace_filename, "w");
897
        FILE* psnrtrace = fopen(psnr_filename, "w");
898

    
899
#ifdef USE_AVFILTER
900
        //init AVFilter
901
        avfilter_register_all();
902
        init_filters(avfilter, pCodecCtx);
903
#endif
904

    
905
        //main loop to read from the input file
906
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
907
        {
908
                //detect if a strange number of anomalies is occurring
909
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
910
                        pts_anomalies_counter++;
911
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
912
                        if(pts_anomaly_threshold >=0 && live_source) { //reset just in case of live source
913
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
914
                                        dcprintf(DEBUG_ANOMALIES, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
915
                                        av_free_packet(&packet);
916
                                        goto close;
917
                                }
918
                        }
919
                }
920

    
921
                //newTime_video and _audio are in usec
922
                //if video and audio stamps differ more than 5sec
923
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
924
                        newtime_anomalies_counter++;
925
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
926
                }
927

    
928
                if(newtime_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) {
929
                        if(live_source) { //restart just in case of live source
930
                                dcprintf(DEBUG_ANOMALIES, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
931
                                av_free_packet(&packet);
932
                                goto close;
933
                        }
934
                }
935

    
936
                // Is this a packet from the video stream?
937
                if(packet.stream_index==videoStream)
938
                {
939
                        if(!live_source)
940
                        {
941
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
942
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
943
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
944
                                        // therefore, it's better to skip the frame
945
                                        if(timebank && (lateTime+maxVDecodeTime) >= 0)
946
                                        {
947
                                                dcprintf(DEBUG_ANOMALIES, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
948
                                                av_free_packet(&packet);
949
                                                continue;
950
                                        }
951
                                }
952
                        }
953
                        
954
                        gettimeofday(&tmp_tv, NULL);
955
                        
956
                        //decode the video packet into a raw pFrame
957
                        if(avcodec_decode_video2(pCodecCtx, pFrame1, &frameFinished, &packet)>0)
958
                        {
959
                                AVFrame *pFrame;
960
                                pFrame = pFrame1;
961

    
962
                                // usleep(5000);
963
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOin pkt: dts %"PRId64" pts %"PRId64" pts-dts %"PRId64"\n", packet.dts, packet.pts, packet.pts-packet.dts );
964
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame->pkt_dts, pFrame->pkt_pts, pFrame->pts);
965
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame->pict_type, pFrame->key_frame ? " (key)" : "");
966
                                if(frameFinished)
967
                                { // it must be true all the time else error
968
                                
969
                                        frame->number = ++contFrameVideo;
970

    
971

    
972

    
973
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: finished frame %d dts %"PRId64" pts %"PRId64"\n", frame->number, packet.dts, packet.pts);
974
                                        if(frame->number==0) {
975
                                                if(packet.dts==AV_NOPTS_VALUE)
976
                                                {
977
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
978
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
979
                                                        av_free_packet(&packet);
980
                                                        continue;
981
                                                }
982
                                                last_pkt_dts = packet.dts;
983
                                                newTime = 0;
984
                                        }
985
                                        else {
986
                                                if(packet.dts!=AV_NOPTS_VALUE) {
987
                                                        delta_video = packet.dts-last_pkt_dts;
988
                                                        last_pkt_dts = packet.dts;
989
                                                }
990
                                                else if(delta_video==0)
991
                                                {
992
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
993
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
994
                                                        av_free_packet(&packet);
995
                                                        continue;
996
                                                }
997
                                        }
998
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: deltavideo : %d\n", (int)delta_video);
999

    
1000
                                        //set initial timestamp
1001
                                        if(FirstTimeVideo && pFrame->pkt_pts>0) {
1002
                                                if(offset_av) {
1003
                                                        ptsvideo1 = pFrame->pkt_pts;
1004
                                                        FirstTimeVideo = 0;
1005
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1);
1006
                                                } else { //we want to compensate audio and video offset for this source
1007
                                                        //maintain the offset between audio pts and video pts
1008
                                                        //because in case of live source they have the same numbering
1009
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
1010
                                                                ptsvideo1 = ptsaudio1;
1011
                                                        else
1012
                                                                ptsvideo1 = pFrame->pkt_pts;
1013
                                                        FirstTimeVideo = 0;
1014
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1);
1015
                                                }
1016
                                        }
1017

    
1018
                                        // store timestamp in useconds for next frame sleep
1019
                                        newTime_video = pts2ms(pFrame->pkt_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base)*1000;
1020

    
1021
                                        if(true) {        //copy channel
1022
                                                video_frame_size = packet.size;
1023
                                                if (video_frame_size > video_outbuf_size) {
1024
                                                        fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
1025
                                                        av_free_packet(&packet);
1026
                                                        continue;
1027
                                                } else {
1028
                                                        memcpy(video_outbuf, packet.data, video_frame_size);
1029
                                                }
1030

    
1031
                                                if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
1032
                                                        target_pts = pFrame->pkt_pts;
1033
                                                }else {        //TODO: review this
1034
                                                        target_pts = pFrame->pkt_dts;
1035
                                                }
1036
                                                createFrame(frame, pts2ms(target_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base), video_frame_size, 
1037
                                                    pFrame->pict_type);
1038
                                                addFrameToOutstream(&outstream[0], frame, video_outbuf);
1039
                                        }
1040
                                        for (i=1; i < 1 + qualitylevels + (indexchannel?1:0); i++) {
1041
                                                video_frame_size = transcodeFrame(video_outbuf, video_outbuf_size, &target_pts, pFrame, pFormatCtx->streams[videoStream]->time_base, pCodecCtx, outstream[i].pCodecCtxEnc);
1042
                                                if (video_frame_size <= 0) {
1043
                                                        av_free_packet(&packet);
1044
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
1045
                                                        continue;
1046
                                                }
1047
                                                createFrame(frame, pts2ms(target_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base), video_frame_size,
1048
                                                    (unsigned char)outstream[i].pCodecCtxEnc->coded_frame->pict_type);
1049
                                                addFrameToOutstream(&outstream[i], frame, video_outbuf);
1050
                                        }
1051

    
1052

    
1053
                                        //compute how long it took to encode video frame
1054
                                        gettimeofday(&now_tv, NULL);
1055
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
1056
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
1057
                                        if(usec > maxVDecodeTime)
1058
                                                maxVDecodeTime = usec;
1059

    
1060
                                        //we DONT have an audio track, so we compute timings and determine
1061
                                        //how much time we have to sleep at next VIDEO frame taking
1062
                                        //also into account how much time was needed to encode the current
1063
                                        //video frame
1064
                                        //all this in case the video source is not live, i.e. not self-timing
1065
                                        //and only in case there is no audio track
1066
                                        if(audioStream == -1) {
1067
                                                if(!live_source) {
1068
                                                        if(newTime_prev != 0) {
1069
                                                                //how much delay between video frames ideally
1070
                                                                long long maxDelay = newTime_video - newTime_prev;
1071
                                                                sleep = (maxDelay - usec);
1072
                                                                dcprintf(DEBUG_ANOMALIES,"\tmaxDelay=%ld\n", ((long)maxDelay));
1073
                                                                dcprintf(DEBUG_ANOMALIES,"\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
1074
                                                        }
1075
                                                        else
1076
                                                                sleep = 0;
1077

    
1078
                                                        //update and store counters
1079
                                                        newTime_prev = newTime_video;
1080

    
1081
                                                        //i can also sleep now instead of at the beginning of
1082
                                                        //the next frame because in this case we only have video
1083
                                                        //frames, hence it would immediately be the next thing to do
1084
                                                        if(sleep > 0) {
1085
                                                                dcprintf(DEBUG_TIMESTAMPING,"\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
1086
                                                                usleep(sleep);
1087
                                                        }
1088

    
1089
                                                }
1090
                                        }
1091
                                }
1092
                        }
1093
                } else if(packet.stream_index==audioStream) {
1094
                        if(sleep > 0)
1095
                        {
1096
                                dcprintf(DEBUG_TIMESTAMPING, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
1097
                                usleep(sleep);
1098
                        }
1099
                        
1100
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1101
                        //decode the audio packet into a raw audio source buffer
1102
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
1103
                        {
1104
                                dcprintf(DEBUG_AUDIO_FRAMES, "\n-------AUDIO FRAME\n");
1105
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
1106
                                if(audio_data_size>0) {
1107
                                        dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: datasizeaudio:%d\n", audio_data_size);
1108
                                        /* if a frame has been decoded, output it */
1109
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
1110
                                }
1111
                                else {
1112
                                        av_free_packet(&packet);
1113
                                        continue;
1114
                                }
1115
        
1116
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
1117
                                if(audio_frame_size <= 0) {
1118
                                        av_free_packet(&packet);
1119
                                        continue;
1120
                                }
1121
                                
1122
                                frame->number = contFrameAudio;
1123

    
1124
                                if(frame->number==0) {
1125
                                        if(packet.dts==AV_NOPTS_VALUE) {
1126
                                                av_free_packet(&packet);
1127
                                                continue;
1128
                                        }
1129
                                        last_pkt_dts_audio = packet.dts;
1130
                                        newTime = 0;
1131
                                }
1132
                                else {
1133
                                        if(packet.dts!=AV_NOPTS_VALUE) {
1134
                                                delta_audio = packet.dts-last_pkt_dts_audio;
1135
                                                last_pkt_dts_audio = packet.dts;
1136
                                        }
1137
                                        else if(delta_audio==0) {
1138
                                                av_free_packet(&packet);
1139
                                                continue;
1140
                                        }
1141
                                }
1142
                                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);
1143
                                //use pts if dts is invalid
1144
                                if(packet.dts!=AV_NOPTS_VALUE)
1145
                                        target_pts = packet.dts;
1146
                                else if(packet.pts!=AV_NOPTS_VALUE) {
1147
                                        target_pts = packet.pts;
1148
                                } else  {
1149
                                        av_free_packet(&packet);
1150
                                        continue;
1151
                                }
1152

    
1153
                                if(offset_av)
1154
                                {
1155
                                        if(FirstTimeAudio && packet.dts>0) {
1156
                                                ptsaudio1 = packet.dts;
1157
                                                FirstTimeAudio = 0;
1158
                                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1);
1159
                                        }
1160
                                }
1161
                                else //we want to compensate audio and video offset for this source
1162
                                {
1163
                                        if(FirstTimeAudio && packet.dts>0) {
1164
                                                //maintain the offset between audio pts and video pts
1165
                                                //because in case of live source they have the same numbering
1166
                                                if(ptsvideo1 > 0) //if we have already seen some video frames...
1167
                                                        ptsaudio1 = ptsvideo1;
1168
                                                else
1169
                                                        ptsaudio1 = packet.dts;
1170
                                                FirstTimeAudio = 0;
1171
                                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1);
1172
                                        }
1173
                                }
1174
                                //compute the new audio timestamps in milliseconds
1175
                                if(frame->number>0) {
1176
                                        newTime = ((target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio;
1177
                                        // store timestamp in useconds for next frame sleep
1178
                                        newTime_audio = newTime*1000;
1179
                                }
1180
                                dcprintf(DEBUG_TIMESTAMPING, "AUDIO: NEWTIMESTAMP %lld\n", newTime);
1181
                                if(newTime<0) {
1182
                                        dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SKIPPING FRAME\n");
1183
                                        newtime_anomalies_counter++;
1184
                                        dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d\n", newtime_anomalies_counter);
1185
                                        av_free_packet(&packet);
1186
                                        continue; //SKIP THIS FRAME, bad timestamp
1187
                                }
1188

    
1189
                                frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000;
1190
                                frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
1191
                                frame->size = audio_frame_size;
1192
                                frame->type = 5; // 5 is audio type
1193
                                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);
1194
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: timestamp sec:%ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec);
1195
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: deltaaudio %"PRId64"\n", delta_audio);        
1196
                                contFrameAudio++;
1197

    
1198
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1199
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1200
                                        exit(-1);
1201
                                }
1202
                                //set priority
1203
                                chunkaudio->priority = 1;
1204

    
1205
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1206
                                        // is chunk filled using current strategy?
1207
                                        //SAVE ON FILE
1208
                                        //saveChunkOnFile(chunkaudio);
1209
                                        //Send the chunk to an external transport/player
1210
                                        for (i=0; i < 1 + qualitylevels; i++) {        //do not send audio to the index channel
1211
                                                sendChunk(outstream[i].output, chunkaudio);
1212
                                        }
1213
                                        dctprintf(DEBUG_CHUNKER, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1214
                                        chunkaudio->seq = 0; //signal that we need an increase
1215
                                        //initChunk(chunkaudio, &seq_current_chunk);
1216
                                }
1217

    
1218
                                //we have an audio track, so we compute timings and determine
1219
                                //how much time we have to sleep at next audio frame taking
1220
                                //also into account how much time was needed to encode the
1221
                                //video frames
1222
                                //all this in case the video source is not live, i.e. not self-timing
1223
                                if(!live_source)
1224
                                {
1225
                                        if(newTime_prev != 0)
1226
                                        {
1227
                                                long long maxDelay = newTime_audio - newTime_prev;
1228

    
1229
                                                gettimeofday(&now_tv, NULL);
1230
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1231
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1232

    
1233
                                                if(usec > maxAudioInterval)
1234
                                                        maxAudioInterval = usec;
1235

    
1236
                                                lateTime -= (maxDelay - usec);
1237
                                                dcprintf(DEBUG_TIMESTAMPING,"\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1238
                                                dcprintf(DEBUG_TIMESTAMPING,"\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1239

    
1240
                                                if((lateTime+maxAudioInterval) < 0)
1241
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1242
                                                else
1243
                                                        sleep = 0;
1244
                                        }
1245
                                        else
1246
                                                sleep = 0;
1247

    
1248
                                        newTime_prev = newTime_audio;
1249
                                        gettimeofday(&lastAudioSent, NULL);
1250
                                }
1251
                        }
1252
                }
1253
                dcprintf(DEBUG_CHUNKER,"Free the packet that was allocated by av_read_frame\n");
1254
                av_free_packet(&packet);
1255
        }
1256
        
1257
        if(videotrace)
1258
                fclose(videotrace);
1259
        if(psnrtrace)
1260
                fclose(psnrtrace);
1261

    
1262
close:
1263
        for (i=0; i < 1 + qualitylevels + (indexchannel?1:0); i++) {
1264
                if(outstream[i].chunk->seq != 0 && outstream[i].chunk->frames_num>0) {
1265
                        sendChunk(outstream[i].output, outstream[0].chunk);
1266
                        dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1267
                        outstream[i].chunk->seq = 0; //signal that we need an increase just in case we will restart
1268
                }
1269
        }
1270
        for (i=0; i < 1 + qualitylevels; i++) {
1271
                if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1272
                        sendChunk(outstream[i].output, chunkaudio);
1273
                        dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1274
                }
1275
        }
1276
        chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1277

    
1278
#ifdef HTTPIO
1279
        /* finalize the HTTP chunk pusher */
1280
        finalizeChunkPusher();
1281
#endif
1282

    
1283
        for (i=0; i < 1 + qualitylevels + (indexchannel?1:0); i++) {
1284
                free(outstream[i].chunk);
1285
        }
1286
        free(chunkaudio);
1287
        free(frame);
1288
        av_free(video_outbuf);
1289
        av_free(audio_outbuf);
1290
        free(cmeta);
1291

    
1292
        // Free the YUV frame
1293
        av_free(pFrame1);
1294
        av_free(samples);
1295
  
1296
        // Close the codec
1297
        avcodec_close(pCodecCtx);
1298
        for (i=1; i < 1 + qualitylevels + (indexchannel?1:0); i++) {
1299
                avcodec_close(outstream[i].pCodecCtxEnc);
1300
        }
1301

    
1302
        if(audioStream!=-1) {
1303
                avcodec_close(aCodecCtx);
1304
                avcodec_close(aCodecCtxEnc);
1305
        }
1306
  
1307
        // Close the video file
1308
        av_close_input_file(pFormatCtx);
1309

    
1310
        if(LOOP_MODE) {
1311
                //we want video to continue, but the av_read_frame stopped
1312
                //lets wait a 5 secs, and cycle in again
1313
                usleep(5000000);
1314
                dcprintf(DEBUG_CHUNKER, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
1315
                videoStream = -1;
1316
                audioStream = -1;
1317
                FirstTimeAudio=1;
1318
                FirstTimeVideo=1;
1319
                pts_anomalies_counter=0;
1320
                newtime_anomalies_counter=0;
1321
                newTime=0;
1322
                newTime_audio=0;
1323
                newTime_prev=0;
1324
                ptsvideo1=0;
1325
                ptsaudio1=0;
1326
                last_pkt_dts=0;
1327
                delta_video=0;
1328
                delta_audio=0;
1329
                last_pkt_dts_audio=0;
1330
                target_pts=0;
1331
                i=0;
1332
                //~ contFrameVideo = 0;
1333
                //~ contFrameAudio = 1;
1334
                
1335
#ifdef YUV_RECORD_ENABLED
1336
                if(ChunkerStreamerTestMode)
1337
                {
1338
                        video_record_count++;
1339
                        //~ savedVideoFrames = 0;
1340
                        
1341
                        //~ char tmp_filename[255];
1342
                        //~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
1343
                        //~ FILE *pFile=fopen(tmp_filename, "w");
1344
                        //~ if(pFile!=NULL)
1345
                                //~ fclose(pFile);
1346
                }
1347
#endif
1348

    
1349
                goto restart;
1350
        }
1351

    
1352
#ifdef TCPIO
1353
        for (i=0; i < 1 + qualitylevels + (indexchannel?1:0); i++) {
1354
                finalizeTCPChunkPusher(outstream[i].output);
1355
        }
1356
#endif
1357

    
1358
#ifdef USE_AVFILTER
1359
        close_filters();
1360
#endif
1361

    
1362
        return 0;
1363
}
1364

    
1365
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf) {
1366
        //the frame.h gets encoded into 5 slots of 32bits (3 ints plus 2 more for the timeval struct
1367
        static int sizeFrameHeader = 5*sizeof(int32_t);
1368

    
1369
        //moving temp pointer to encode Frame on the wire
1370
        uint8_t *tempdata = NULL;
1371

    
1372
        if(chunk->seq == 0) {
1373
                initChunk(chunk, &seq_current_chunk);
1374
        }
1375
        //add frame priority to chunk priority (to be normalized later on)
1376
        chunk->priority += frame->type + 1; // I:2, P:3, B:4
1377

    
1378
        //HINT on malloc
1379
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1380
        if(!chunk->data)  {
1381
                fprintf(stderr, "Memory error in chunk!!!\n");
1382
                return -1;
1383
        }
1384
        chunk->frames_num++; // number of frames in the current chunk
1385

    
1386
/*
1387
        //package the Frame header
1388
        tempdata = chunk->data+chunk->payload_len;
1389
        *((int32_t *)tempdata) = frame->number;
1390
        tempdata+=sizeof(int32_t);
1391
        *((struct timeval *)tempdata) = frame->timestamp;
1392
        tempdata+=sizeof(struct timeval);
1393
        *((int32_t *)tempdata) = frame->size;
1394
        tempdata+=sizeof(int32_t);
1395
        *((int32_t *)tempdata) = frame->type;
1396
        tempdata+=sizeof(int32_t);
1397
*/
1398
        //package the Frame header: network order and platform independent
1399
        tempdata = chunk->data+chunk->payload_len;
1400
        bit32_encoded_push(frame->number, tempdata);
1401
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1402
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1403
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1404
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1405

    
1406
         //insert the new frame data
1407
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1408
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1409
        //chunk lenght is updated just prior to pushing it out because
1410
        //the chunk header len is better calculated there
1411
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1412

    
1413
        //update timestamps
1414
        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) {
1415
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1416
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1417
        }
1418
        
1419
        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) {
1420
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1421
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1422
        }
1423
        return 0;
1424
}
1425

    
1426
void SaveFrame(AVFrame *pFrame, int width, int height)
1427
{
1428
        FILE *pFile;
1429
        int  y;
1430

    
1431
         // Open file
1432
        char tmp_filename[255];
1433
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1434
        pFile=fopen(tmp_filename, "ab");
1435
        if(pFile==NULL)
1436
                return;
1437

    
1438
        // Write header
1439
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1440
  
1441
        // Write Y data
1442
        for(y=0; y<height; y++)
1443
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1444
                {
1445
                        printf("errno = %d\n", errno);
1446
                        exit(1);
1447
                }
1448
        // Write U data
1449
        for(y=0; y<height/2; y++)
1450
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1451
                  {
1452
                        printf("errno = %d\n", errno);
1453
                        exit(1);
1454
                }
1455
        // Write V data
1456
        for(y=0; y<height/2; y++)
1457
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1458
                  {
1459
                        printf("errno = %d\n", errno);
1460
                        exit(1);
1461
                }
1462
  
1463
        // Close file
1464
        fclose(pFile);
1465
}
1466

    
1467
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1468
{
1469
        static FILE* pFile = NULL;
1470
        
1471
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1472
        fwrite(frame, sizeof(Frame), 1, pFile);
1473
        fwrite(video_outbuf, frame->size, 1, pFile);
1474
        fclose(pFile);
1475
}