Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ 7cbabb7f

History | View | Annotate | Download (46.7 KB)

1
/*
2
 *  Copyright (c) 2009-2011 Carmelo Daniele, Dario Marchese, Diego Reforgiato, Giuseppe Tropea
3
 *  developed for the Napa-Wine EU project. See www.napa-wine.eu
4
 *
5
 *  This is free software; see lgpl-2.1.txt
6
 */
7

    
8
#include "chunker_streamer.h"
9
#include <signal.h>
10
#include <math.h>
11
#include <getopt.h>
12
#include <libswscale/swscale.h>
13
#include <libavutil/opt.h>
14

    
15
#ifdef USE_AVFILTER
16
#include <libavfilter/avfilter.h>
17
#include "chunker_filtering.h"
18
#endif
19

    
20
#define DEBUG
21
#define DEBUG_AUDIO_FRAMES  false
22
#define DEBUG_VIDEO_FRAMES  false
23
#define DEBUG_CHUNKER false
24
#define DEBUG_ANOMALIES true
25
#define DEBUG_TIMESTAMPING false
26
#include "dbg.h"
27

    
28
#define STREAMER_MAX(a,b) ((a>b)?(a):(b))
29
#define STREAMER_MIN(a,b) ((a<b)?(a):(b))
30

    
31
//#define DISPLAY_PSNR
32
#define GET_PSNR(x) ((x==0) ? 0 : (-10.0*log(x)/log(10)))
33

    
34
ChunkerMetadata *cmeta = NULL;
35
int seq_current_chunk = 1; //chunk numbering starts from 1; HINT do i need more bytes?
36

    
37
#define AUDIO_CHUNK 0
38
#define VIDEO_CHUNK 1
39

    
40
void SaveFrame(AVFrame *pFrame, int width, int height);
41
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf);
42
int pushChunkTcp(ExternalChunk *echunk);
43
void initTCPPush(char* ip, int port);
44
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf);
45
void finalizeTCPChunkPusher();
46
void bit32_encoded_push(uint32_t v, uint8_t *p);
47

    
48
int video_record_count = 0;
49
int savedVideoFrames = 0;
50
long int firstSavedVideoFrame = 0;
51
int ChunkerStreamerTestMode = 0;
52

    
53
int pts_anomaly_threshold = -1;
54
int newtime_anomaly_threshold = -1;
55
bool timebank = false;
56
char *outside_world_url = NULL;
57

    
58
int gop_size = 25;
59
int max_b_frames = 3;
60
bool vcopy = false;
61

    
62
long delay_audio = 0; //delay audio by x millisec
63

    
64
char *avfilter="yadif";
65

    
66
// Constant number of frames per chunk
67
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType)
68
{
69
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
70
        if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
71
                return 1;
72

    
73
        return 0;
74
}
75

    
76
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
77
// It can be considered as constant size.
78
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType)
79
{
80
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
81
        if(echunk->payload_len >= cmeta->targetChunkSize)
82
                return 1;
83
        
84
        return 0;
85
}
86

    
87
// Performace optimization.
88
// The chunkFilled function has been splitted into two functions (one for each strategy).
89
// Instead of continuously check the strategy flag (which is constant),
90
// 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)
91
int (*chunkFilled)(ExternalChunk *echunk, int chunkType);
92

    
93
void initChunk(ExternalChunk *chunk, int *seq_num) {
94
        chunk->seq = (*seq_num)++;
95
        chunk->frames_num = 0;
96
        chunk->payload_len = 0;
97
        chunk->len=0;
98
  if(chunk->data != NULL)
99
    free(chunk->data);
100
        chunk->data = NULL;
101
        chunk->start_time.tv_sec = -1;
102
        chunk->start_time.tv_usec = -1;
103
        chunk->end_time.tv_sec = -1;
104
        chunk->end_time.tv_usec = -1;
105
        chunk->priority = 0;
106
        chunk->category = 0;
107
        chunk->_refcnt = 0;
108
}
109

    
110
int quit = 0;
111

    
112
void sigproc()
113
{
114
        printf("you have pressed ctrl-c, terminating...\n");
115
        quit = 1;
116
}
117

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

    
138
    "\t[--video_stream]:set video_stream ID in input\n"
139
    "\t[--audio_stream]:set audio_stream ID in input\n"
140
    "\t[--avfilter]:set input filter (default: yadif\n"
141
    "\n"
142
    "Codec options:\n"
143
    "\t[-g GOP]: gop size\n"
144
    "\t[-b frames]: max number of consecutive b frames\n"
145
    "\t[-x extas]: extra video codec options (e.g. -x me_method=hex,flags2=+dct8x8+wpred+bpyrami+mixed_refs)\n"
146
    "\n"
147
    "=======================================================\n", argv[0]
148
    );
149
  }
150

    
151
int sendChunk(ExternalChunk *chunk) {
152
#ifdef HTTPIO
153
                                                return pushChunkHttp(chunk, outside_world_url);
154
#endif
155
#ifdef TCPIO
156
                                                return pushChunkTcp(chunk);
157
#endif
158
#ifdef UDPIO
159
                                                return pushChunkUDP(chunk);
160
#endif
161
}
162

    
163
int main(int argc, char *argv[]) {
164
        signal(SIGINT, sigproc);
165
        
166
        int i=0;
167

    
168
        //output variables
169
        uint8_t *video_outbuf = NULL;
170
        int video_outbuf_size, video_frame_size;
171
        uint8_t *audio_outbuf = NULL;
172
        int audio_outbuf_size, audio_frame_size;
173
        int audio_data_size;
174

    
175
        //numeric identifiers of input streams
176
        int videoStream = -1;
177
        int audioStream = -1;
178

    
179
//        int len1;
180
        int frameFinished;
181
        //frame sequential counters
182
        int contFrameAudio=1, contFrameVideo=0;
183
//        int numBytes;
184

    
185
        //command line parameters
186
        int audio_bitrate = -1;
187
        int video_bitrate = -1;
188
        char *audio_codec = "mp2";
189
        char *video_codec = "mpeg4";
190
        char *codec_options = "";
191
        int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file)
192
        int offset_av = 0; //tells to compensate for offset between audio and video in the file
193
        
194
        //a raw buffer for decoded uncompressed audio samples
195
        int16_t *samples = NULL;
196
        //a raw uncompressed video picture
197
        AVFrame *pFrame1 = NULL;
198
        AVFrame *pFrame2 = NULL;
199
        AVFrame *scaledFrame = NULL;
200

    
201
        AVFormatContext *pFormatCtx;
202
        AVCodecContext  *pCodecCtx = NULL ,*pCodecCtxEnc = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL;
203
        AVCodec         *pCodec = NULL ,*pCodecEnc = NULL ,*aCodec = NULL ,*aCodecEnc = NULL;
204
        AVPacket         packet;
205

    
206
        //stuff needed to compute the right timestamps
207
        short int FirstTimeAudio=1, FirstTimeVideo=1;
208
        short int pts_anomalies_counter=0;
209
        short int newtime_anomalies_counter=0;
210
        long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0;
211
        struct timeval lastAudioSent = {0, 0};
212
        int64_t ptsvideo1=0;
213
        int64_t ptsaudio1=0;
214
        int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0;
215

    
216
        //Napa-Wine specific Frame and Chunk structures for transport
217
        Frame *frame = NULL;
218
        ExternalChunk *chunk = NULL;
219
        ExternalChunk *chunkaudio = NULL;
220
        
221
        char av_input[1024];
222
        int dest_width = -1;
223
        int dest_height = -1;
224
        
225
        static struct option long_options[] =
226
        {
227
                {"audio_stream", required_argument, 0, 0},
228
                {"video_stream", required_argument, 0, 0},
229
                {"avfilter", required_argument, 0, 0},
230
                {0, 0, 0, 0}
231
        };
232
        /* `getopt_long' stores the option index here. */
233
        int option_index = 0, c;
234
        int mandatories = 0;
235
        while ((c = getopt_long (argc, argv, "i:a:v:A:V:s:lop:q:tF:g:b:d:x:", long_options, &option_index)) != -1)
236
        {
237
                switch (c) {
238
                        case 0: //for long options
239
                                if( strcmp( "audio_stream", long_options[option_index].name ) == 0 ) { audioStream = atoi(optarg); }
240
                                if( strcmp( "video_stream", long_options[option_index].name ) == 0 ) { videoStream = atoi(optarg); }
241
                                if( strcmp( "avfilter", long_options[option_index].name ) == 0 ) { avfilter = strdup(optarg); }
242
                                break;
243
                        case 'i':
244
                                sprintf(av_input, "%s", optarg);
245
                                mandatories++;
246
                                break;
247
                        case 'a':
248
                                sscanf(optarg, "%d", &audio_bitrate);
249
                                mandatories++;
250
                                break;
251
                        case 'v':
252
                                sscanf(optarg, "%d", &video_bitrate);
253
                                mandatories++;
254
                                break;
255
                        case 'A':
256
                                audio_codec = strdup(optarg);
257
                                break;
258
                        case 'V':
259
                                video_codec = strdup(optarg);
260
                                break;
261
                        case 's':
262
                                sscanf(optarg, "%dx%d", &dest_width, &dest_height);
263
                                break;
264
                        case 'l':
265
                                live_source = 1;
266
                                break;
267
                        case 'o':
268
                                offset_av = 1;
269
                                break;
270
                        case 't':
271
                                ChunkerStreamerTestMode = 1;
272
                                break;
273
                        case 'p':
274
                                sscanf(optarg, "%d", &pts_anomaly_threshold);
275
                                break;
276
                        case 'q':
277
                                sscanf(optarg, "%d", &newtime_anomaly_threshold);
278
                                break;
279
                        case 'F':
280
                                outside_world_url = strdup(optarg);
281
                                break;
282
                        case 'g':
283
                                sscanf(optarg, "%d", &gop_size);
284
                                break;
285
                        case 'b':
286
                                sscanf(optarg, "%d", &max_b_frames);
287
                                break;
288
                        case 'd':
289
                                sscanf(optarg, "%ld", &delay_audio);
290
                                break;
291
                        case 'x':
292
                                codec_options = strdup(optarg);
293
                                break;
294
                        default:
295
                                print_usage(argc, argv);
296
                                return -1;
297
                }
298
        }
299
        
300
        if(mandatories < 3) 
301
        {
302
                print_usage(argc, argv);
303
                return -1;
304
        }
305

    
306
#ifdef YUV_RECORD_ENABLED
307
        if(ChunkerStreamerTestMode)
308
        {
309
                DELETE_DIR("yuv_data");
310
                CREATE_DIR("yuv_data");
311
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
312
                //fclose(pFile);
313
        }
314
#endif
315

    
316
restart:
317
        // read the configuration file
318
        cmeta = chunkerInit();
319
        if (!outside_world_url) {
320
                outside_world_url = strdup(cmeta->outside_world_url);
321
        }
322
        switch(cmeta->strategy)
323
        {
324
                case 1:
325
                        chunkFilled = chunkFilledSizeStrategy;
326
                        break;
327
                default:
328
                        chunkFilled = chunkFilledFramesStrategy;
329
        }
330
                
331
        if(live_source)
332
                fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
333
        if(offset_av)
334
                fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
335

    
336
        // Register all formats and codecs
337
        av_register_all();
338

    
339
        // Open input file
340
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
341
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
342
                exit(-1);
343
        }
344

    
345
        // Retrieve stream information
346
        if(av_find_stream_info(pFormatCtx) < 0) {
347
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
348
                exit(-1);
349
        }
350

    
351
        // Dump information about file onto standard error
352
        av_dump_format(pFormatCtx, 0, av_input, 0);
353

    
354
        // Find the video and audio stream numbers
355
        for(i=0; i<pFormatCtx->nb_streams; i++) {
356
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
357
                        videoStream=i;
358
                }
359
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
360
                        audioStream=i;
361
                }
362
        }
363

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

    
369
        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);
370

    
371
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
372
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
373

    
374

    
375
        // Get a pointer to the codec context for the input video stream
376
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
377
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
378
        //extract W and H
379
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
380

    
381
        // Get a pointer to the codec context for the input audio stream
382
        if(audioStream != -1) {
383
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
384
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
385
        }
386

    
387
        // Figure out size
388
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
389
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
390

    
391
        //setup video output encoder
392
 if (strcmp(video_codec, "copy") == 0) {
393
        vcopy = true;
394
 } else {
395
        pCodecEnc = avcodec_find_encoder_by_name(video_codec);
396
        if (pCodecEnc) {
397
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
398
        } else {
399
                fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
400
                return -1; // Codec not found
401
        }
402

    
403
        pCodecCtxEnc=avcodec_alloc_context();
404
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
405
        pCodecCtxEnc->codec_id = pCodecEnc->id;
406

    
407
        pCodecCtxEnc->bit_rate = video_bitrate;
408
        //~ pCodecCtxEnc->qmin = 30;
409
        //~ pCodecCtxEnc->qmax = 30;
410
        //times 20 follows the defaults, was not needed in previous versions of libavcodec
411
//        pCodecCtxEnc->crf = 20.0f;
412
        // resolution must be a multiple of two 
413
        pCodecCtxEnc->width = dest_width;
414
        pCodecCtxEnc->height = dest_height;
415
        // frames per second 
416
        //~ pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
417
        //printf("pCodecCtx->time_base=%d/%d\n", pCodecCtx->time_base.num, pCodecCtx->time_base.den);
418
        pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
419
        pCodecCtxEnc->gop_size = gop_size; // emit one intra frame every gop_size frames 
420
        pCodecCtxEnc->max_b_frames = max_b_frames;
421
        pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P;
422
        pCodecCtxEnc->flags |= CODEC_FLAG_PSNR;
423
        //~ pCodecCtxEnc->flags |= CODEC_FLAG_QSCALE;
424

    
425
        //some generic quality tuning
426
        pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD;
427

    
428
        //some rate control parameters for streaming, taken from ffserver.c
429
        {
430
        /* Bitrate tolerance is less for streaming */
431
        AVCodecContext *av = pCodecCtxEnc;
432
        if (av->bit_rate_tolerance == 0)
433
            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
434
                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);
435
        //if (av->qmin == 0)
436
        //    av->qmin = 3;
437
        //if (av->qmax == 0)
438
        //    av->qmax = 31;
439
        //if (av->max_qdiff == 0)
440
        //    av->max_qdiff = 3;
441
        //av->qcompress = 0.5;
442
        //av->qblur = 0.5;
443

    
444
        //if (!av->nsse_weight)
445
        //    av->nsse_weight = 8;
446

    
447
        //av->frame_skip_cmp = FF_CMP_DCTMAX;
448
        //if (!av->me_method)
449
        //    av->me_method = ME_EPZS;
450
        //av->rc_buffer_aggressivity = 1.0;
451

    
452
        //if (!av->rc_eq)
453
        //    av->rc_eq = "tex^qComp";
454
        //if (!av->i_quant_factor)
455
        //    av->i_quant_factor = -0.8;
456
        //if (!av->b_quant_factor)
457
        //    av->b_quant_factor = 1.25;
458
        //if (!av->b_quant_offset)
459
        //    av->b_quant_offset = 1.25;
460
        if (!av->rc_max_rate)
461
            av->rc_max_rate = av->bit_rate * 2;
462

    
463
        if (av->rc_max_rate && !av->rc_buffer_size) {
464
            av->rc_buffer_size = av->rc_max_rate;
465
        }
466
        }
467
        //end of code taken fromffserver.c
468

    
469
  switch (pCodecEnc->id) {
470
    case CODEC_ID_H264 :
471
        // Fast Profile
472
        // libx264-fast.ffpreset preset 
473
        pCodecCtxEnc->coder_type = FF_CODER_TYPE_AC; // coder = 1 -> enable CABAC
474
        pCodecCtxEnc->flags |= CODEC_FLAG_LOOP_FILTER; // flags=+loop -> deblock
475
        pCodecCtxEnc->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1
476
        pCodecCtxEnc->partitions |= X264_PART_I8X8|X264_PART_I4X4|X264_PART_P8X8|X264_PART_B8X8;        // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
477
        pCodecCtxEnc->me_method=ME_HEX; // me_method=hex
478
        pCodecCtxEnc->me_subpel_quality = 6; // subq=7
479
        pCodecCtxEnc->me_range = 16; // me_range=16
480
        //pCodecCtxEnc->gop_size = 250; // g=250
481
        //pCodecCtxEnc->keyint_min = 25; // keyint_min=25
482
        pCodecCtxEnc->scenechange_threshold = 40; // sc_threshold=40
483
        pCodecCtxEnc->i_quant_factor = 0.71; // i_qfactor=0.71
484
        pCodecCtxEnc->b_frame_strategy = 1; // b_strategy=1
485
        pCodecCtxEnc->qcompress = 0.6; // qcomp=0.6
486
        pCodecCtxEnc->qmin = 10; // qmin=10
487
        pCodecCtxEnc->qmax = 51; // qmax=51
488
        pCodecCtxEnc->max_qdiff = 4; // qdiff=4
489
        //pCodecCtxEnc->max_b_frames = 3; // bf=3
490
        pCodecCtxEnc->refs = 2; // refs=3
491
        //pCodecCtxEnc->directpred = 1; // directpred=1
492
        pCodecCtxEnc->directpred = 3; // directpred=1 in preset -> "directpred", "direct mv prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)"
493
        //pCodecCtxEnc->trellis = 1; // trellis=1
494
        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
495
        pCodecCtxEnc->weighted_p_pred = 2; // wpredp=2
496

    
497
        // libx264-main.ffpreset preset
498
        //pCodecCtxEnc->flags2|=CODEC_FLAG2_8X8DCT;
499
        //pCodecCtxEnc->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
500
        //pCodecCtxEnc->crf = 22;
501

    
502
#ifdef STREAMER_X264_USE_SSIM
503
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
504
#endif
505

    
506
        //pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
507
        // pCodecCtxEnc->rc_min_rate = 0;
508
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
509
        // pCodecCtxEnc->rc_buffer_size = 0;
510
        break;
511
    case CODEC_ID_MPEG4 :
512
        break;
513
    default:
514
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
515
  }
516

    
517
  if ((av_set_options_string(pCodecCtxEnc, codec_options, "=", ",")) < 0) {
518
    fprintf(stderr, "Error parsing options string: '%s'\n", codec_options);
519
    exit(1);
520
  }
521

    
522
        fprintf(stderr, "INIT: VIDEO timebase OUT:%d %d IN: %d %d\n", pCodecCtxEnc->time_base.num, pCodecCtxEnc->time_base.den, pCodecCtx->time_base.num, pCodecCtx->time_base.den);
523
 }
524

    
525
        if(pCodec==NULL) {
526
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
527
                return -1; // Codec not found
528
        }
529
        if(!vcopy && pCodecEnc==NULL) {
530
                fprintf(stderr, "INIT: Unsupported OUT VIDEO pcodecenc!\n");
531
                return -1; // Codec not found
532
        }
533
        if(avcodec_open(pCodecCtx, pCodec)<0) {
534
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
535
                return -1; // Could not open codec
536
        }
537
        if(!vcopy && avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
538
                fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
539
                return -1; // Could not open codec
540
        }
541
        if(audioStream!=-1) {
542
                //setup audio output encoder
543
                aCodecCtxEnc = avcodec_alloc_context();
544
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
545
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
546
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
547
                aCodecCtxEnc->channels = aCodecCtx->channels;
548
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
549

    
550
                // Find the decoder for the audio stream
551
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
552
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
553
                if(aCodec==NULL) {
554
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
555
                        return -1;
556
                }
557
                if(aCodecEnc==NULL) {
558
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
559
                        return -1;
560
                }
561
        
562
                if(avcodec_open(aCodecCtx, aCodec)<0) {
563
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
564
                        return -1; // Could not open codec
565
                }
566
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
567
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
568
                        return -1; // Could not open codec
569
                }
570
        }
571
        else {
572
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
573
        }
574

    
575
        // Allocate audio in and out buffers
576
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
577
        if(samples == NULL) {
578
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
579
                return -1;
580
        }
581
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
582
        audio_outbuf = av_malloc(audio_outbuf_size);
583
        if(audio_outbuf == NULL) {
584
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
585
                return -1;
586
        }
587

    
588
        // Allocate video in frame and out buffer
589
        pFrame1=avcodec_alloc_frame();
590
        pFrame2=avcodec_alloc_frame();
591
        scaledFrame=avcodec_alloc_frame();
592
        if(pFrame1==NULL || pFrame2==NULL || scaledFrame == NULL) {
593
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
594
                return -1;
595
        }
596
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
597
        video_outbuf = av_malloc(video_outbuf_size);
598
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, dest_width, dest_height);
599
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
600
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, dest_width, dest_height);
601
        if(!video_outbuf || !scaledFrame_buffer) {
602
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
603
                return -1;
604
        }
605

    
606
        //allocate Napa-Wine transport
607
        frame = (Frame *)malloc(sizeof(Frame));
608
        if(!frame) {
609
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
610
                return -1;
611
        }
612
        //create an empty first video chunk
613
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
614
        if(!chunk) {
615
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
616
                return -1;
617
        }
618
        chunk->data = NULL;
619
        chunk->seq = 0;
620
        //initChunk(chunk, &seq_current_chunk); if i init them now i get out of sequence
621
        dcprintf(DEBUG_CHUNKER, "INIT: chunk video %d\n", chunk->seq);
622
        //create empty first audio chunk
623
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
624
        if(!chunkaudio) {
625
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
626
                return -1;
627
        }
628
  chunkaudio->data=NULL;
629
        chunkaudio->seq = 0;
630
        //initChunk(chunkaudio, &seq_current_chunk);
631
        dcprintf(DEBUG_CHUNKER, "INIT: chunk audio %d\n", chunkaudio->seq);
632

    
633
#ifdef HTTPIO
634
        /* initialize the HTTP chunk pusher */
635
        initChunkPusher(); //TRIPLO
636
#endif
637

    
638
        long sleep=0;
639
        struct timeval now_tv;
640
        struct timeval tmp_tv;
641
        long long lateTime = 0;
642
        long long maxAudioInterval = 0;
643
        long long maxVDecodeTime = 0;
644
//        unsigned char lastIFrameDistance = 0;
645

    
646
#ifdef TCPIO
647
        static char peer_ip[16];
648
        static int peer_port;
649
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
650
        if (res < 2) {
651
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
652
                return -2;
653
        }
654
        
655
        initTCPPush(peer_ip, peer_port);
656
#endif
657
#ifdef UDPIO
658
        static char peer_ip[16];
659
        static int peer_port;
660
        int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
661
        if (res < 2) {
662
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
663
                return -2;
664
        }
665
        
666
        initUDPPush(peer_ip, peer_port);
667
#endif
668
        
669
        char videotrace_filename[255];
670
        char psnr_filename[255];
671
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
672
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
673
        FILE* videotrace = fopen(videotrace_filename, "w");
674
        FILE* psnrtrace = fopen(psnr_filename, "w");
675

    
676
#ifdef USE_AVFILTER
677
        //init AVFilter
678
        avfilter_register_all();
679
        init_filters(avfilter, pCodecCtx);
680
#endif
681

    
682
        //main loop to read from the input file
683
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
684
        {
685
                //detect if a strange number of anomalies is occurring
686
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
687
                        pts_anomalies_counter++;
688
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
689
                        if(pts_anomaly_threshold >=0 && live_source) { //reset just in case of live source
690
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
691
                                        dcprintf(DEBUG_ANOMALIES, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
692
                                        av_free_packet(&packet);
693
                                        goto close;
694
                                }
695
                        }
696
                }
697

    
698
                //newTime_video and _audio are in usec
699
                //if video and audio stamps differ more than 5sec
700
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
701
                        newtime_anomalies_counter++;
702
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
703
                }
704

    
705
                if(newtime_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) {
706
                        if(live_source) { //restart just in case of live source
707
                                dcprintf(DEBUG_ANOMALIES, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
708
                                av_free_packet(&packet);
709
                                goto close;
710
                        }
711
                }
712

    
713
                // Is this a packet from the video stream?
714
                if(packet.stream_index==videoStream)
715
                {
716
                        if(!live_source)
717
                        {
718
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
719
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
720
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
721
                                        // therefore, it's better to skip the frame
722
                                        if(timebank && (lateTime+maxVDecodeTime) >= 0)
723
                                        {
724
                                                dcprintf(DEBUG_ANOMALIES, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
725
                                                av_free_packet(&packet);
726
                                                continue;
727
                                        }
728
                                }
729
                        }
730
                        
731
                        gettimeofday(&tmp_tv, NULL);
732
                        
733
                        //decode the video packet into a raw pFrame
734
                        if(avcodec_decode_video2(pCodecCtx, pFrame1, &frameFinished, &packet)>0)
735
                        {
736
                                AVFrame *pFrame;
737
                                pFrame = pFrame1;
738

    
739
                                // usleep(5000);
740
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOin pkt: dts %"PRId64" pts %"PRId64" pts-dts %"PRId64"\n", packet.dts, packet.pts, packet.pts-packet.dts );
741
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame->pkt_dts, pFrame->pkt_pts, pFrame->pts);
742
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame->pict_type, pFrame->key_frame ? " (key)" : "");
743
                                if(frameFinished)
744
                                { // it must be true all the time else error
745
                                
746
                                        frame->number = ++contFrameVideo;
747

    
748
#ifdef VIDEO_DEINTERLACE
749
                                if (!vcopy) {
750
                                        avpicture_deinterlace(
751
                                                (AVPicture*) pFrame,
752
                                                (const AVPicture*) pFrame,
753
                                                pCodecCtxEnc->pix_fmt,
754
                                                pCodecCtxEnc->width,
755
                                                pCodecCtxEnc->height);
756
                                }
757
#endif
758

    
759

    
760
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: finished frame %d dts %"PRId64" pts %"PRId64"\n", frame->number, packet.dts, packet.pts);
761
                                        if(frame->number==0) {
762
                                                if(packet.dts==AV_NOPTS_VALUE)
763
                                                {
764
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
765
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
766
                                                        av_free_packet(&packet);
767
                                                        continue;
768
                                                }
769
                                                last_pkt_dts = packet.dts;
770
                                                newTime = 0;
771
                                        }
772
                                        else {
773
                                                if(packet.dts!=AV_NOPTS_VALUE) {
774
                                                        delta_video = packet.dts-last_pkt_dts;
775
                                                        last_pkt_dts = packet.dts;
776
                                                }
777
                                                else if(delta_video==0)
778
                                                {
779
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
780
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
781
                                                        av_free_packet(&packet);
782
                                                        continue;
783
                                                }
784
                                        }
785
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: deltavideo : %d\n", (int)delta_video);
786

    
787
                                        if(vcopy) {
788
                                                video_frame_size = packet.size;
789
                                                if (video_frame_size > video_outbuf_size) {
790
                                                        fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
791
                                                        av_free_packet(&packet);
792
                                                        continue;
793
                                                } else {
794
                                                        memcpy(video_outbuf, packet.data, video_frame_size);
795
                                                }
796

    
797
                                                if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
798
                                                        target_pts = pFrame->pkt_pts;
799
                                                }else {        //TODO: review this
800
                                                        target_pts = pFrame->pkt_dts;
801
                                                }
802
                                        } else {
803

    
804
                                            if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
805
                                                pFrame->pts = av_rescale_q(pFrame->pkt_pts, pFormatCtx->streams[videoStream]->time_base, pCodecCtxEnc->time_base);
806
                                            } else {        //try to figure out the pts //TODO: review this
807
                                                if (pFrame->pkt_dts != AV_NOPTS_VALUE) {
808
                                                        pFrame->pts = av_rescale_q(pFrame->pkt_dts, pFormatCtx->streams[videoStream]->time_base, pCodecCtxEnc->time_base);
809
                                                }
810
                                            }
811

    
812
#ifdef USE_AVFILTER
813
                                        //apply avfilters
814
                                        filter(pFrame,pFrame2);
815
                                        pFrame = pFrame2;
816
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame2->pkt_dts, pFrame2->pkt_pts, pFrame2->pts);
817
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame2->pict_type, pFrame2->key_frame ? " (key)" : "");
818
#endif
819

    
820
                                            if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
821
//                                                static AVPicture pict;
822
                                                static struct SwsContext *img_convert_ctx = NULL;
823
                                                
824
                                                pFrame->pict_type = 0;
825
                                                if(img_convert_ctx == NULL)
826
                                                {
827
                                                        img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, dest_width, dest_height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
828
                                                        if(img_convert_ctx == NULL) {
829
                                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
830
                                                                exit(1);
831
                                                        }
832
                                                }
833
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
834
                                                scaledFrame->pts = pFrame->pts;
835
                                                scaledFrame->pict_type = 0;
836
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
837
                                            } else {
838
                                                pFrame->pict_type = 0;
839
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
840
                                            }
841

    
842
                                            //use pts if dts is invalid
843
                                            if(pCodecCtxEnc->coded_frame->pts!=AV_NOPTS_VALUE)
844
                                                target_pts = av_rescale_q(pCodecCtxEnc->coded_frame->pts, pCodecCtxEnc->time_base, pFormatCtx->streams[videoStream]->time_base);
845
                                            else {        //TODO: review this
846
                                                av_free_packet(&packet);
847
                                                continue;
848
                                                //fprintf(stderr, "VIDEOout: pts error\n");
849
                                                //exit(1);
850
                                            }
851
                                        }
852

    
853
                                        if(video_frame_size <= 0)
854
                                        {
855
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
856
                                                av_free_packet(&packet);
857
                                                continue;
858
                                        }
859

    
860
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
861
                                                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);
862
                                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOout: outtype: %d%s\n", pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
863
                                        }
864
#ifdef DISPLAY_PSNR
865
                                        static double ist_psnr = 0;
866
                                        static double cum_psnr = 0;
867
                                        static int psnr_samples = 0;
868
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
869
                                                if(pCodecCtxEnc->flags&CODEC_FLAG_PSNR) {
870
                                                        ist_psnr = GET_PSNR(pCodecCtxEnc->coded_frame->error[0]/(pCodecCtxEnc->width*pCodecCtxEnc->height*255.0*255.0));
871
                                                        psnr_samples++;
872
                                                        cum_psnr += ist_psnr;
873
                                                        fprintf(stderr, "PSNR: ist %.4f avg: %.4f\n", ist_psnr, cum_psnr / (double)psnr_samples);
874
                                                }
875
                                        }
876
#endif
877

    
878
                                        if(offset_av)
879
                                        {
880
                                                if(FirstTimeVideo && target_pts>0) {
881
                                                        ptsvideo1 = target_pts;
882
                                                        FirstTimeVideo = 0;
883
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1);
884
                                                }
885
                                        }
886
                                        else //we want to compensate audio and video offset for this source
887
                                        {
888
                                                if(FirstTimeVideo && target_pts>0) {
889
                                                        //maintain the offset between audio pts and video pts
890
                                                        //because in case of live source they have the same numbering
891
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
892
                                                                ptsvideo1 = ptsaudio1;
893
                                                        else
894
                                                                ptsvideo1 = target_pts;
895
                                                        FirstTimeVideo = 0;
896
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1);
897
                                                }
898
                                        }
899
                                        //compute the new video timestamp in milliseconds
900
                                        if(frame->number>0) {
901
                                                newTime = (target_pts - ptsvideo1) * 1000 * pFormatCtx->streams[videoStream]->time_base.num / pFormatCtx->streams[videoStream]->time_base.den;
902
                                                // store timestamp in useconds for next frame sleep
903
                                                newTime_video = newTime*1000;
904
                                        }
905
                                        dcprintf(DEBUG_TIMESTAMPING, "VIDEO: NEWTIMESTAMP %lld\n", newTime);
906
                                        if(newTime<0) {
907
                                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: SKIPPING FRAME\n");
908
                                                newtime_anomalies_counter++;
909
                                                dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME negative video timestamp anomaly detected number %d\n", newtime_anomalies_counter);
910
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
911
                                                av_free_packet(&packet);
912
                                                continue; //SKIP THIS FRAME, bad timestamp
913
                                        }
914
                                        
915
                                        //~ printf("pCodecCtxEnc->error[0]=%"PRId64"\n", pFrame->error[0]);
916
        
917
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
918
                                        frame->timestamp.tv_usec = newTime%1000;
919
                                        frame->size = video_frame_size;
920
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
921
                                        frame->type = vcopy ? pFrame->pict_type : (unsigned char)pCodecCtxEnc->coded_frame->pict_type;
922

    
923
                                        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);
924
                                        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);
925

    
926
#ifdef YUV_RECORD_ENABLED
927
                                        if(!vcopy && ChunkerStreamerTestMode)
928
                                        {
929
                                                if(videotrace)
930
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pFrame->pict_type, frame->size);
931

    
932
                                                if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
933
                                                        SaveFrame(scaledFrame, dest_width, dest_height);
934
                                                else
935
                                                        SaveFrame(pFrame, dest_width, dest_height);
936

    
937
                                                ++savedVideoFrames;
938
                                                SaveEncodedFrame(frame, video_outbuf);
939

    
940
                                                if(!firstSavedVideoFrame)
941
                                                        firstSavedVideoFrame = frame->number;
942
                                                
943
                                                char tmp_filename[255];
944
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
945
                                                FILE* tmp = fopen(tmp_filename, "w");
946
                                                if(tmp)
947
                                                {
948
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
949
                                                                ,dest_width, dest_height
950
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
951
                                                        fclose(tmp);
952
                                                }
953
                                        }
954
#endif
955

    
956
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
957
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: timestamped sec %ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec);
958
                                        //contFrameVideo++; //lets increase the numbering of the frames
959

    
960
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
961
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
962
                                                exit(-1);
963
                                        }
964

    
965
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
966
                                                //calculate priority
967
                                                chunk->priority /= chunk->frames_num;
968

    
969
                                                //SAVE ON FILE
970
                                                //saveChunkOnFile(chunk);
971
                                                //Send the chunk to an external transport/player
972
                                                sendChunk(chunk);
973
                                                dctprintf(DEBUG_CHUNKER, "VIDEO: sent chunk video %d, prio:%f, size %d\n", chunk->seq, chunk->priority, chunk->len);
974
                                                chunk->seq = 0; //signal that we need an increase
975
                                                //initChunk(chunk, &seq_current_chunk);
976
                                        }
977

    
978
                                        //compute how long it took to encode video frame
979
                                        gettimeofday(&now_tv, NULL);
980
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
981
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
982
                                        if(usec > maxVDecodeTime)
983
                                                maxVDecodeTime = usec;
984

    
985
                                        //we DONT have an audio track, so we compute timings and determine
986
                                        //how much time we have to sleep at next VIDEO frame taking
987
                                        //also into account how much time was needed to encode the current
988
                                        //video frame
989
                                        //all this in case the video source is not live, i.e. not self-timing
990
                                        //and only in case there is no audio track
991
                                        if(audioStream == -1) {
992
                                                if(!live_source) {
993
                                                        if(newTime_prev != 0) {
994
                                                                //how much delay between video frames ideally
995
                                                                long long maxDelay = newTime_video - newTime_prev;
996
                                                                sleep = (maxDelay - usec);
997
                                                                dcprintf(DEBUG_ANOMALIES,"\tmaxDelay=%ld\n", ((long)maxDelay));
998
                                                                dcprintf(DEBUG_ANOMALIES,"\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
999
                                                        }
1000
                                                        else
1001
                                                                sleep = 0;
1002

    
1003
                                                        //update and store counters
1004
                                                        newTime_prev = newTime_video;
1005

    
1006
                                                        //i can also sleep now instead of at the beginning of
1007
                                                        //the next frame because in this case we only have video
1008
                                                        //frames, hence it would immediately be the next thing to do
1009
                                                        if(sleep > 0) {
1010
                                                                dcprintf(DEBUG_ANOMALIES, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
1011
                                                                usleep(sleep);
1012
                                                        }
1013

    
1014
                                                }
1015
                                        }
1016

    
1017
                                }
1018
                        }
1019
                }
1020
                else if(packet.stream_index==audioStream)
1021
                {
1022
                        if(sleep > 0)
1023
                        {
1024
                                dcprintf(DEBUG_ANOMALIES, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
1025
                                usleep(sleep);
1026
                        }
1027
                        
1028
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1029
                        //decode the audio packet into a raw audio source buffer
1030
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
1031
                        {
1032
                                dcprintf(DEBUG_AUDIO_FRAMES, "\n-------AUDIO FRAME\n");
1033
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
1034
                                if(audio_data_size>0) {
1035
                                        dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: datasizeaudio:%d\n", audio_data_size);
1036
                                        /* if a frame has been decoded, output it */
1037
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
1038
                                }
1039
                                else {
1040
                                        av_free_packet(&packet);
1041
                                        continue;
1042
                                }
1043
        
1044
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
1045
                                if(audio_frame_size <= 0) {
1046
                                        av_free_packet(&packet);
1047
                                        continue;
1048
                                }
1049
                                
1050
                                frame->number = contFrameAudio;
1051

    
1052
                                if(frame->number==0) {
1053
                                        if(packet.dts==AV_NOPTS_VALUE) {
1054
                                                av_free_packet(&packet);
1055
                                                continue;
1056
                                        }
1057
                                        last_pkt_dts_audio = packet.dts;
1058
                                        newTime = 0;
1059
                                }
1060
                                else {
1061
                                        if(packet.dts!=AV_NOPTS_VALUE) {
1062
                                                delta_audio = packet.dts-last_pkt_dts_audio;
1063
                                                last_pkt_dts_audio = packet.dts;
1064
                                        }
1065
                                        else if(delta_audio==0) {
1066
                                                av_free_packet(&packet);
1067
                                                continue;
1068
                                        }
1069
                                }
1070
                                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);
1071
                                //use pts if dts is invalid
1072
                                if(packet.dts!=AV_NOPTS_VALUE)
1073
                                        target_pts = packet.dts;
1074
                                else if(packet.pts!=AV_NOPTS_VALUE) {
1075
                                        target_pts = packet.pts;
1076
                                } else  {
1077
                                        av_free_packet(&packet);
1078
                                        continue;
1079
                                }
1080

    
1081
                                if(offset_av)
1082
                                {
1083
                                        if(FirstTimeAudio && packet.dts>0) {
1084
                                                ptsaudio1 = packet.dts;
1085
                                                FirstTimeAudio = 0;
1086
                                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1);
1087
                                        }
1088
                                }
1089
                                else //we want to compensate audio and video offset for this source
1090
                                {
1091
                                        if(FirstTimeAudio && packet.dts>0) {
1092
                                                //maintain the offset between audio pts and video pts
1093
                                                //because in case of live source they have the same numbering
1094
                                                if(ptsvideo1 > 0) //if we have already seen some video frames...
1095
                                                        ptsaudio1 = ptsvideo1;
1096
                                                else
1097
                                                        ptsaudio1 = packet.dts;
1098
                                                FirstTimeAudio = 0;
1099
                                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1);
1100
                                        }
1101
                                }
1102
                                //compute the new audio timestamps in milliseconds
1103
                                if(frame->number>0) {
1104
                                        newTime = ((target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio;
1105
                                        // store timestamp in useconds for next frame sleep
1106
                                        newTime_audio = newTime*1000;
1107
                                }
1108
                                dcprintf(DEBUG_TIMESTAMPING, "AUDIO: NEWTIMESTAMP %lld\n", newTime);
1109
                                if(newTime<0) {
1110
                                        dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SKIPPING FRAME\n");
1111
                                        newtime_anomalies_counter++;
1112
                                        dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d\n", newtime_anomalies_counter);
1113
                                        av_free_packet(&packet);
1114
                                        continue; //SKIP THIS FRAME, bad timestamp
1115
                                }
1116

    
1117
                                frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000;
1118
                                frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
1119
                                frame->size = audio_frame_size;
1120
                                frame->type = 5; // 5 is audio type
1121
                                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);
1122
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: timestamp sec:%ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec);
1123
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: deltaaudio %"PRId64"\n", delta_audio);        
1124
                                contFrameAudio++;
1125

    
1126
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1127
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1128
                                        exit(-1);
1129
                                }
1130
                                //set priority
1131
                                chunkaudio->priority = 1;
1132

    
1133
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1134
                                        // is chunk filled using current strategy?
1135
                                        //SAVE ON FILE
1136
                                        //saveChunkOnFile(chunkaudio);
1137
                                        //Send the chunk to an external transport/player
1138
                                        sendChunk(chunkaudio);
1139
                                        dctprintf(DEBUG_CHUNKER, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1140
                                        chunkaudio->seq = 0; //signal that we need an increase
1141
                                        //initChunk(chunkaudio, &seq_current_chunk);
1142
                                }
1143

    
1144
                                //we have an audio track, so we compute timings and determine
1145
                                //how much time we have to sleep at next audio frame taking
1146
                                //also into account how much time was needed to encode the
1147
                                //video frames
1148
                                //all this in case the video source is not live, i.e. not self-timing
1149
                                if(!live_source)
1150
                                {
1151
                                        if(newTime_prev != 0)
1152
                                        {
1153
                                                long long maxDelay = newTime_audio - newTime_prev;
1154

    
1155
                                                gettimeofday(&now_tv, NULL);
1156
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1157
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1158

    
1159
                                                if(usec > maxAudioInterval)
1160
                                                        maxAudioInterval = usec;
1161

    
1162
                                                lateTime -= (maxDelay - usec);
1163
                                                dcprintf(DEBUG_ANOMALIES,"\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1164
                                                dcprintf(DEBUG_ANOMALIES,"\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1165

    
1166
                                                if((lateTime+maxAudioInterval) < 0)
1167
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1168
                                                else
1169
                                                        sleep = 0;
1170
                                        }
1171
                                        else
1172
                                                sleep = 0;
1173

    
1174
                                        newTime_prev = newTime_audio;
1175
                                        gettimeofday(&lastAudioSent, NULL);
1176
                                }
1177
                        }
1178
                }
1179
                dcprintf(DEBUG_CHUNKER,"Free the packet that was allocated by av_read_frame\n");
1180
                av_free_packet(&packet);
1181
        }
1182
        
1183
        if(videotrace)
1184
                fclose(videotrace);
1185
        if(psnrtrace)
1186
                fclose(psnrtrace);
1187

    
1188
close:
1189
        if(chunk->seq != 0 && chunk->frames_num>0) {
1190
                //SAVE ON FILE
1191
                //saveChunkOnFile(chunk);
1192
                //Send the chunk to an external transport/player
1193
                sendChunk(chunk);
1194
                dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1195
                chunk->seq = 0; //signal that we need an increase just in case we will restart
1196
        }
1197
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1198
                //SAVE ON FILE     
1199
                //saveChunkOnFile(chunkaudio);
1200
                //Send the chunk via http to an external transport/player
1201
                sendChunk(chunkaudio);
1202
                dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1203
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1204
        }
1205

    
1206
#ifdef HTTPIO
1207
        /* finalize the HTTP chunk pusher */
1208
        finalizeChunkPusher();
1209
#endif
1210

    
1211
        free(chunk);
1212
        free(chunkaudio);
1213
        free(frame);
1214
        av_free(video_outbuf);
1215
        av_free(scaledFrame_buffer);
1216
        av_free(audio_outbuf);
1217
        free(cmeta);
1218

    
1219
        // Free the YUV frame
1220
        av_free(pFrame1);
1221
        av_free(pFrame2);
1222
        av_free(scaledFrame);
1223
        av_free(samples);
1224
  
1225
        // Close the codec
1226
        if (!vcopy) avcodec_close(pCodecCtx);
1227
        if (!vcopy) avcodec_close(pCodecCtxEnc);
1228

    
1229
        if(audioStream!=-1) {
1230
                avcodec_close(aCodecCtx);
1231
                avcodec_close(aCodecCtxEnc);
1232
        }
1233
  
1234
        // Close the video file
1235
        av_close_input_file(pFormatCtx);
1236

    
1237
        if(LOOP_MODE) {
1238
                //we want video to continue, but the av_read_frame stopped
1239
                //lets wait a 5 secs, and cycle in again
1240
                usleep(5000000);
1241
                dcprintf(DEBUG_CHUNKER, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
1242
                videoStream = -1;
1243
                audioStream = -1;
1244
                FirstTimeAudio=1;
1245
                FirstTimeVideo=1;
1246
                pts_anomalies_counter=0;
1247
                newtime_anomalies_counter=0;
1248
                newTime=0;
1249
                newTime_audio=0;
1250
                newTime_prev=0;
1251
                ptsvideo1=0;
1252
                ptsaudio1=0;
1253
                last_pkt_dts=0;
1254
                delta_video=0;
1255
                delta_audio=0;
1256
                last_pkt_dts_audio=0;
1257
                target_pts=0;
1258
                i=0;
1259
                //~ contFrameVideo = 0;
1260
                //~ contFrameAudio = 1;
1261
                
1262
#ifdef YUV_RECORD_ENABLED
1263
                if(ChunkerStreamerTestMode)
1264
                {
1265
                        video_record_count++;
1266
                        //~ savedVideoFrames = 0;
1267
                        
1268
                        //~ char tmp_filename[255];
1269
                        //~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
1270
                        //~ FILE *pFile=fopen(tmp_filename, "w");
1271
                        //~ if(pFile!=NULL)
1272
                                //~ fclose(pFile);
1273
                }
1274
#endif
1275

    
1276
                goto restart;
1277
        }
1278

    
1279
#ifdef TCPIO
1280
        finalizeTCPChunkPusher();
1281
#endif
1282

    
1283
#ifdef USE_AVFILTER
1284
        close_filters();
1285
#endif
1286

    
1287
        return 0;
1288
}
1289

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

    
1294
        //moving temp pointer to encode Frame on the wire
1295
        uint8_t *tempdata = NULL;
1296

    
1297
        if(chunk->seq == 0) {
1298
                initChunk(chunk, &seq_current_chunk);
1299
        }
1300
        //add frame priority to chunk priority (to be normalized later on)
1301
        chunk->priority += frame->type + 1; // I:2, P:3, B:4
1302

    
1303
        //HINT on malloc
1304
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1305
        if(!chunk->data)  {
1306
                fprintf(stderr, "Memory error in chunk!!!\n");
1307
                return -1;
1308
        }
1309
        chunk->frames_num++; // number of frames in the current chunk
1310

    
1311
/*
1312
        //package the Frame header
1313
        tempdata = chunk->data+chunk->payload_len;
1314
        *((int32_t *)tempdata) = frame->number;
1315
        tempdata+=sizeof(int32_t);
1316
        *((struct timeval *)tempdata) = frame->timestamp;
1317
        tempdata+=sizeof(struct timeval);
1318
        *((int32_t *)tempdata) = frame->size;
1319
        tempdata+=sizeof(int32_t);
1320
        *((int32_t *)tempdata) = frame->type;
1321
        tempdata+=sizeof(int32_t);
1322
*/
1323
        //package the Frame header: network order and platform independent
1324
        tempdata = chunk->data+chunk->payload_len;
1325
        bit32_encoded_push(frame->number, tempdata);
1326
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1327
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1328
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1329
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1330

    
1331
         //insert the new frame data
1332
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1333
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1334
        //chunk lenght is updated just prior to pushing it out because
1335
        //the chunk header len is better calculated there
1336
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1337

    
1338
        //update timestamps
1339
        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) {
1340
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1341
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1342
        }
1343
        
1344
        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) {
1345
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1346
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1347
        }
1348
        return 0;
1349
}
1350

    
1351
void SaveFrame(AVFrame *pFrame, int width, int height)
1352
{
1353
        FILE *pFile;
1354
        int  y;
1355

    
1356
         // Open file
1357
        char tmp_filename[255];
1358
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1359
        pFile=fopen(tmp_filename, "ab");
1360
        if(pFile==NULL)
1361
                return;
1362

    
1363
        // Write header
1364
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1365
  
1366
        // Write Y data
1367
        for(y=0; y<height; y++)
1368
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1369
                {
1370
                        printf("errno = %d\n", errno);
1371
                        exit(1);
1372
                }
1373
        // Write U data
1374
        for(y=0; y<height/2; y++)
1375
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1376
                  {
1377
                        printf("errno = %d\n", errno);
1378
                        exit(1);
1379
                }
1380
        // Write V data
1381
        for(y=0; y<height/2; y++)
1382
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1383
                  {
1384
                        printf("errno = %d\n", errno);
1385
                        exit(1);
1386
                }
1387
  
1388
        // Close file
1389
        fclose(pFile);
1390
}
1391

    
1392
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1393
{
1394
        static FILE* pFile = NULL;
1395
        
1396
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1397
        fwrite(frame, sizeof(Frame), 1, pFile);
1398
        fwrite(video_outbuf, frame->size, 1, pFile);
1399
        fclose(pFile);
1400
}