Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ 80515685

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

    
14
#define STREAMER_MAX(a,b) ((a>b)?(a):(b))
15
#define STREAMER_MIN(a,b) ((a<b)?(a):(b))
16

    
17
//#define DEBUG_AUDIO_FRAMES
18
//#define DEBUG_VIDEO_FRAMES
19
//#define DEBUG_CHUNKER
20
#define DEBUG_ANOMALIES
21
//~ #define DEBUG_TIMESTAMPING
22
#define GET_PSNR(x) ((x==0) ? 0 : (-10.0*log(x)/log(10)))
23

    
24
ChunkerMetadata *cmeta = NULL;
25
int seq_current_chunk = 1; //chunk numbering starts from 1; HINT do i need more bytes?
26

    
27
#define AUDIO_CHUNK 0
28
#define VIDEO_CHUNK 1
29

    
30
void SaveFrame(AVFrame *pFrame, int width, int height);
31
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf);
32
int pushChunkTcp(ExternalChunk *echunk);
33
void initTCPPush(char* ip, int port);
34
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf);
35
void finalizeTCPChunkPusher();
36
void bit32_encoded_push(uint32_t v, uint8_t *p);
37

    
38
int video_record_count = 0;
39
int savedVideoFrames = 0;
40
long int firstSavedVideoFrame = 0;
41
int ChunkerStreamerTestMode = 0;
42

    
43
int pts_anomaly_threshold = -1;
44
int newtime_anomaly_threshold = -1;
45
bool timebank = false;
46
char *outside_world_url = NULL;
47

    
48
int gop_size = 12;
49
int max_b_frames = 1;
50
bool vcopy = false;
51

    
52
long delay_audio = 0; //delay audio by x millisec
53

    
54
// Constant number of frames per chunk
55
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType)
56
{
57
#ifdef DEBUG_CHUNKER
58
        fprintf(stderr, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
59
#endif
60
        if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
61
                return 1;
62

    
63
        return 0;
64
}
65

    
66
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
67
// It can be considered as constant size.
68
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType)
69
{
70
#ifdef DEBUG_CHUNKER
71
        fprintf(stderr, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
72
#endif
73
        if(echunk->payload_len >= cmeta->targetChunkSize)
74
                return 1;
75
        
76
        return 0;
77
}
78

    
79
// Performace optimization.
80
// The chunkFilled function has been splitted into two functions (one for each strategy).
81
// Instead of continuously check the strategy flag (which is constant),
82
// 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)
83
int (*chunkFilled)(ExternalChunk *echunk, int chunkType);
84

    
85
void initChunk(ExternalChunk *chunk, int *seq_num) {
86
        chunk->seq = (*seq_num)++;
87
        chunk->frames_num = 0;
88
        chunk->payload_len = 0;
89
        chunk->len=0;
90
  if(chunk->data != NULL)
91
    free(chunk->data);
92
        chunk->data = NULL;
93
        chunk->start_time.tv_sec = -1;
94
        chunk->start_time.tv_usec = -1;
95
        chunk->end_time.tv_sec = -1;
96
        chunk->end_time.tv_usec = -1;
97
        chunk->priority = 0;
98
        chunk->category = 0;
99
        chunk->_refcnt = 0;
100
}
101

    
102
int quit = 0;
103

    
104
void sigproc()
105
{
106
        printf("you have pressed ctrl-c, terminating...\n");
107
        quit = 1;
108
}
109

    
110
static void print_usage(int argc, char *argv[])
111
{
112
  fprintf (stderr,
113
    "\nUsage:%s [options]\n"
114
    "\n"
115
    "Mandatory options:\n"
116
    "\t[-i input file]\n"
117
    "\t[-a audio bitrate]\n"
118
    "\t[-v video bitrate]\n\n"
119
    "Other options:\n"
120
    "\t[-F output] (overrides config file)\n"
121
    "\t[-A audioencoder]\n"
122
    "\t[-V videoencoder]\n"
123
    "\t[-s WxH]: force video size.\n"
124
    "\t[-l]: this is a live stream.\n"
125
    "\t[-o]: adjust av frames timestamps.\n"
126
    "\t[-p]: pts anomaly threshold (default: -1=off).\n"
127
    "\t[-q]: sync anomaly threshold ((default: -1=off).\n"
128
    "\t[-t]: QoE test mode\n\n"
129
    "Codec options:\n"
130
    "\t[-g GOP]: gop size\n"
131
    "\t[-b frames]: max number of consecutive b frames\n\n"
132
    "=======================================================\n", argv[0]
133
    );
134
  }
135

    
136
int sendChunk(ExternalChunk *chunk) {
137
#ifdef HTTPIO
138
                                                return pushChunkHttp(chunk, outside_world_url);
139
#endif
140
#ifdef TCPIO
141
                                                return pushChunkTcp(chunk);
142
#endif
143
#ifdef UDPIO
144
                                                return pushChunkUDP(chunk);
145
#endif
146
}
147

    
148
int main(int argc, char *argv[]) {
149
        signal(SIGINT, sigproc);
150
        
151
        int i=0;
152

    
153
        //output variables
154
        uint8_t *video_outbuf = NULL;
155
        int video_outbuf_size, video_frame_size;
156
        uint8_t *audio_outbuf = NULL;
157
        int audio_outbuf_size, audio_frame_size;
158
        int audio_data_size;
159

    
160
        //numeric identifiers of input streams
161
        int videoStream = -1;
162
        int audioStream = -1;
163

    
164
//        int len1;
165
        int frameFinished;
166
        //frame sequential counters
167
        int contFrameAudio=1, contFrameVideo=0;
168
//        int numBytes;
169

    
170
        //command line parameters
171
        int audio_bitrate = -1;
172
        int video_bitrate = -1;
173
        char *audio_codec = "mp2";
174
        char *video_codec = "mpeg4";
175
        int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file)
176
        int offset_av = 0; //tells to compensate for offset between audio and video in the file
177
        
178
        //a raw buffer for decoded uncompressed audio samples
179
        int16_t *samples = NULL;
180
        //a raw uncompressed video picture
181
        AVFrame *pFrame = NULL;
182
        AVFrame *scaledFrame = NULL;
183

    
184
        AVFormatContext *pFormatCtx;
185
        AVCodecContext  *pCodecCtx = NULL ,*pCodecCtxEnc = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL;
186
        AVCodec         *pCodec = NULL ,*pCodecEnc = NULL ,*aCodec = NULL ,*aCodecEnc = NULL;
187
        AVPacket         packet;
188

    
189
        //stuff needed to compute the right timestamps
190
        short int FirstTimeAudio=1, FirstTimeVideo=1;
191
        short int pts_anomalies_counter=0;
192
        short int newtime_anomalies_counter=0;
193
        long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0;
194
        struct timeval lastAudioSent = {0, 0};
195
        double ptsvideo1=0.0;
196
        double ptsaudio1=0.0;
197
        int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0;
198

    
199
        //Napa-Wine specific Frame and Chunk structures for transport
200
        Frame *frame = NULL;
201
        ExternalChunk *chunk = NULL;
202
        ExternalChunk *chunkaudio = NULL;
203
        
204
        char av_input[1024];
205
        int dest_width = -1;
206
        int dest_height = -1;
207
        
208
        static struct option long_options[] =
209
        {
210
                /* These options set a flag. */
211
                {"long_option", required_argument, 0, 0},
212
                {0, 0, 0, 0}
213
        };
214
        /* `getopt_long' stores the option index here. */
215
        int option_index = 0, c;
216
        int mandatories = 0;
217
        while ((c = getopt_long (argc, argv, "i:a:v:A:V:s:lop:q:tF:g:b:d:", long_options, &option_index)) != -1)
218
        {
219
                switch (c) {
220
                        case 0: //for long options
221
                                break;
222
                        case 'i':
223
                                sprintf(av_input, "%s", optarg);
224
                                mandatories++;
225
                                break;
226
                        case 'a':
227
                                sscanf(optarg, "%d", &audio_bitrate);
228
                                mandatories++;
229
                                break;
230
                        case 'v':
231
                                sscanf(optarg, "%d", &video_bitrate);
232
                                mandatories++;
233
                                break;
234
                        case 'A':
235
                                audio_codec = strdup(optarg);
236
                                break;
237
                        case 'V':
238
                                video_codec = strdup(optarg);
239
                                break;
240
                        case 's':
241
                                sscanf(optarg, "%dx%d", &dest_width, &dest_height);
242
                                break;
243
                        case 'l':
244
                                live_source = 1;
245
                                break;
246
                        case 'o':
247
                                offset_av = 1;
248
                                break;
249
                        case 't':
250
                                ChunkerStreamerTestMode = 1;
251
                                break;
252
                        case 'p':
253
                                sscanf(optarg, "%d", &pts_anomaly_threshold);
254
                                break;
255
                        case 'q':
256
                                sscanf(optarg, "%d", &newtime_anomaly_threshold);
257
                                break;
258
                        case 'F':
259
                                outside_world_url = strdup(optarg);
260
                                break;
261
                        case 'g':
262
                                sscanf(optarg, "%d", &gop_size);
263
                                break;
264
                        case 'b':
265
                                sscanf(optarg, "%d", &max_b_frames);
266
                                break;
267
                        case 'd':
268
                                sscanf(optarg, "%d", &delay_audio);
269
                                break;
270
                        default:
271
                                print_usage(argc, argv);
272
                                return -1;
273
                }
274
        }
275
        
276
        if(mandatories < 3) 
277
        {
278
                print_usage(argc, argv);
279
                return -1;
280
        }
281

    
282
#ifdef YUV_RECORD_ENABLED
283
        if(ChunkerStreamerTestMode)
284
        {
285
                DELETE_DIR("yuv_data");
286
                CREATE_DIR("yuv_data");
287
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
288
                //fclose(pFile);
289
        }
290
#endif
291

    
292
restart:
293
        // read the configuration file
294
        cmeta = chunkerInit();
295
        if (!outside_world_url) {
296
                outside_world_url = strdup(cmeta->outside_world_url);
297
        }
298
        switch(cmeta->strategy)
299
        {
300
                case 1:
301
                        chunkFilled = chunkFilledSizeStrategy;
302
                        break;
303
                default:
304
                        chunkFilled = chunkFilledFramesStrategy;
305
        }
306
                
307
        if(live_source)
308
                fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
309
        if(offset_av)
310
                fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
311

    
312
        // Register all formats and codecs
313
        av_register_all();
314

    
315
        // Open input file
316
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
317
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
318
                exit(-1);
319
        }
320

    
321
        // Retrieve stream information
322
        if(av_find_stream_info(pFormatCtx) < 0) {
323
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
324
                exit(-1);
325
        }
326

    
327
        // Dump information about file onto standard error
328
        dump_format(pFormatCtx, 0, av_input, 0);
329

    
330
        // Find the video and audio stream numbers
331
        for(i=0; i<pFormatCtx->nb_streams; i++) {
332
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
333
                        videoStream=i;
334
                }
335
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
336
                        audioStream=i;
337
                }
338
        }
339
        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, pFormatCtx->streams[videoStream]->duration);
340

    
341
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
342
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
343

    
344
        if(videoStream==-1 && audioStream==-1) {
345
                fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
346
                exit(-1);
347
        }
348

    
349
        // Get a pointer to the codec context for the input video stream
350
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
351
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
352
        //extract W and H
353
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
354

    
355
        // Get a pointer to the codec context for the input audio stream
356
        if(audioStream != -1) {
357
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
358
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
359
        }
360

    
361
        // Figure out size
362
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
363
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
364

    
365
        //setup video output encoder
366
 if (strcmp(video_codec, "copy") == 0) {
367
        vcopy = true;
368
 } else {
369
        pCodecEnc = avcodec_find_encoder_by_name(video_codec);
370
        if (pCodecEnc) {
371
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
372
        } else {
373
                fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
374
                return -1; // Codec not found
375
        }
376

    
377
        pCodecCtxEnc=avcodec_alloc_context();
378
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
379
        pCodecCtxEnc->codec_id = pCodecEnc->id;
380

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

    
400
        //some generic quality tuning
401
        pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD;
402

    
403
  switch (pCodecEnc->id) {
404
    case CODEC_ID_H264 :
405
        pCodecCtxEnc->me_range=16;
406
        pCodecCtxEnc->max_qdiff=4;
407
        pCodecCtxEnc->qmin=1;
408
        pCodecCtxEnc->qmax=30;
409
        pCodecCtxEnc->qcompress=0.6;
410
        // frames per second 
411

    
412
//        pCodecCtxEnc->rc_min_rate = 0;
413
//        pCodecCtxEnc->rc_max_rate = 0;
414
//        pCodecCtxEnc->rc_buffer_size = 0;
415
//        pCodecCtxEnc->partitions = X264_PART_I4X4 | X264_PART_I8X8 | X264_PART_P8X8 | X264_PART_P4X4 | X264_PART_B8X8;
416
//        pCodecCtxEnc->crf = 0.0f;
417
        
418
#ifdef STREAMER_X264_USE_SSIM
419
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
420
#endif
421

    
422
        pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
423
        // pCodecCtxEnc->rc_min_rate = 0;
424
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
425
        // pCodecCtxEnc->rc_buffer_size = 0;
426
        break;
427
    case CODEC_ID_MPEG4 :
428
        break;
429
    default:
430
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
431
  }
432
 
433
        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);
434
 }
435

    
436
        if(pCodec==NULL) {
437
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
438
                return -1; // Codec not found
439
        }
440
        if(!vcopy && pCodecEnc==NULL) {
441
                fprintf(stderr, "INIT: Unsupported OUT VIDEO pcodecenc!\n");
442
                return -1; // Codec not found
443
        }
444
        if(avcodec_open(pCodecCtx, pCodec)<0) {
445
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
446
                return -1; // Could not open codec
447
        }
448
        if(!vcopy && avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
449
                fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
450
                return -1; // Could not open codec
451
        }
452
        if(audioStream!=-1) {
453
                //setup audio output encoder
454
                aCodecCtxEnc = avcodec_alloc_context();
455
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
456
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
457
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
458
                aCodecCtxEnc->channels = aCodecCtx->channels;
459
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
460

    
461
                // Find the decoder for the audio stream
462
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
463
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
464
                if(aCodec==NULL) {
465
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
466
                        return -1;
467
                }
468
                if(aCodecEnc==NULL) {
469
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
470
                        return -1;
471
                }
472
        
473
                if(avcodec_open(aCodecCtx, aCodec)<0) {
474
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
475
                        return -1; // Could not open codec
476
                }
477
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
478
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
479
                        return -1; // Could not open codec
480
                }
481
        }
482
        else {
483
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
484
        }
485

    
486
        // Allocate audio in and out buffers
487
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
488
        if(samples == NULL) {
489
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
490
                return -1;
491
        }
492
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
493
        audio_outbuf = av_malloc(audio_outbuf_size);
494
        if(audio_outbuf == NULL) {
495
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
496
                return -1;
497
        }
498

    
499
        // Allocate video in frame and out buffer
500
        pFrame=avcodec_alloc_frame();
501
        scaledFrame=avcodec_alloc_frame();
502
        if(pFrame==NULL || scaledFrame == NULL) {
503
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
504
                return -1;
505
        }
506
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
507
        video_outbuf = av_malloc(video_outbuf_size);
508
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, dest_width, dest_height);
509
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
510
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, dest_width, dest_height);
511
        if(!video_outbuf || !scaledFrame_buffer) {
512
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
513
                return -1;
514
        }
515

    
516
        //allocate Napa-Wine transport
517
        frame = (Frame *)malloc(sizeof(Frame));
518
        if(!frame) {
519
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
520
                return -1;
521
        }
522
        //create an empty first video chunk
523
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
524
        if(!chunk) {
525
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
526
                return -1;
527
        }
528
        chunk->data = NULL;
529
        chunk->seq = 0;
530
        //initChunk(chunk, &seq_current_chunk); if i init them now i get out of sequence
531
#ifdef DEBUG_CHUNKER
532
        fprintf(stderr, "INIT: chunk video %d\n", chunk->seq);
533
#endif
534
        //create empty first audio chunk
535
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
536
        if(!chunkaudio) {
537
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
538
                return -1;
539
        }
540
  chunkaudio->data=NULL;
541
        chunkaudio->seq = 0;
542
        //initChunk(chunkaudio, &seq_current_chunk);
543
#ifdef DEBUG_CHUNKER
544
        fprintf(stderr, "INIT: chunk audio %d\n", chunkaudio->seq);
545
#endif
546

    
547
#ifdef HTTPIO
548
        /* initialize the HTTP chunk pusher */
549
        initChunkPusher(); //TRIPLO
550
#endif
551

    
552
        long sleep=0;
553
        struct timeval now_tv;
554
        struct timeval tmp_tv;
555
        long long lateTime = 0;
556
        long long maxAudioInterval = 0;
557
        long long maxVDecodeTime = 0;
558
//        unsigned char lastIFrameDistance = 0;
559

    
560
#ifdef TCPIO
561
        static char peer_ip[16];
562
        static int peer_port;
563
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
564
        if (res < 2) {
565
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
566
                return -2;
567
        }
568
        
569
        initTCPPush(peer_ip, peer_port);
570
#endif
571
#ifdef UDPIO
572
        static char peer_ip[16];
573
        static int peer_port;
574
        int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
575
        if (res < 2) {
576
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
577
                return -2;
578
        }
579
        
580
        initUDPPush(peer_ip, peer_port);
581
#endif
582
        
583
        char videotrace_filename[255];
584
        char psnr_filename[255];
585
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
586
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
587
        FILE* videotrace = fopen(videotrace_filename, "w");
588
        FILE* psnrtrace = fopen(psnr_filename, "w");
589

    
590
        //main loop to read from the input file
591
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
592
        {
593
                //detect if a strange number of anomalies is occurring
594
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
595
                        pts_anomalies_counter++;
596
#ifdef DEBUG_ANOMALIES
597
                        fprintf(stderr, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
598
#endif
599
                        if(newtime_anomaly_threshold >=0 && live_source) { //reset just in case of live source
600
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
601
                                        pts_anomalies_counter = 0;
602
                                        FirstTimeVideo = 1;
603
                                        FirstTimeAudio = 1;
604
#ifdef DEBUG_ANOMALIES
605
                                        fprintf(stderr, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
606
#endif
607
                                }
608
                        }
609
                }
610

    
611
                //newTime_video and _audio are in usec
612
                //if video and audio stamps differ more than 5sec
613
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
614
                        newtime_anomalies_counter++;
615
#ifdef DEBUG_ANOMALIES
616
                        fprintf(stderr, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
617
#endif
618
                }
619

    
620
                if(pts_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) {
621
                        if(live_source) { //restart just in case of live source
622
#ifdef DEBUG_ANOMALIES
623
                                fprintf(stderr, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
624
#endif
625
                                av_free_packet(&packet);
626
                                goto close;
627
                        }
628
                }
629

    
630
                // Is this a packet from the video stream?
631
                if(packet.stream_index==videoStream)
632
                {
633
                        if(!live_source)
634
                        {
635
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
636
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
637
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
638
                                        // therefore, it's better to skip the frame
639
                                        if(timebank && (lateTime+maxVDecodeTime) >= 0)
640
                                        {
641
#ifdef DEBUG_ANOMALIES
642
                                                fprintf(stderr, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
643
#endif
644
                                                av_free_packet(&packet);
645
                                                continue;
646
                                        }
647
                                }
648
                        }
649
                        
650
                        gettimeofday(&tmp_tv, NULL);
651
                        
652
                        //decode the video packet into a raw pFrame
653
                        if(avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet)>0)
654
                        {
655
                                // usleep(5000);
656
#ifdef DEBUG_VIDEO_FRAMES
657
                                fprintf(stderr, "\n-------VIDEO FRAME intype %d%s\n", pFrame->pict_type, pFrame->key_frame ? " (key)" : "");
658
                                fprintf(stderr, "VIDEO: dts %lld pts %lld\n", packet.dts, packet.pts);
659
#endif
660
                                if(frameFinished)
661
                                { // it must be true all the time else error
662
                                
663
                                        frame->number = ++contFrameVideo;
664

    
665
#ifdef VIDEO_DEINTERLACE
666
                                if (!vcopy) {
667
                                        avpicture_deinterlace(
668
                                                (AVPicture*) pFrame,
669
                                                (const AVPicture*) pFrame,
670
                                                pCodecCtxEnc->pix_fmt,
671
                                                pCodecCtxEnc->width,
672
                                                pCodecCtxEnc->height);
673
                                }
674
#endif
675

    
676
#ifdef DEBUG_VIDEO_FRAMES
677
                                        fprintf(stderr, "VIDEO: finished frame %d dts %lld pts %lld\n", frame->number, packet.dts, packet.pts);
678
#endif
679
                                        if(frame->number==0) {
680
                                                if(packet.dts==AV_NOPTS_VALUE)
681
                                                {
682
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
683
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
684
                                                        av_free_packet(&packet);
685
                                                        continue;
686
                                                }
687
                                                last_pkt_dts = packet.dts;
688
                                                newTime = 0;
689
                                        }
690
                                        else {
691
                                                if(packet.dts!=AV_NOPTS_VALUE) {
692
                                                        delta_video = packet.dts-last_pkt_dts;
693
                                                        last_pkt_dts = packet.dts;
694
                                                }
695
                                                else if(delta_video==0)
696
                                                {
697
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
698
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
699
                                                        av_free_packet(&packet);
700
                                                        continue;
701
                                                }
702
                                        }
703
#ifdef DEBUG_VIDEO_FRAMES
704
                                        fprintf(stderr, "VIDEO: deltavideo : %d\n", (int)delta_video);
705
#endif
706

    
707
                                        if(vcopy) {
708
                                                video_frame_size = packet.size;
709
                                                if (video_frame_size > video_outbuf_size) {
710
                                                        fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
711
                                                        av_free_packet(&packet);
712
                                                        continue;
713
                                                } else {
714
                                                        memcpy(video_outbuf, packet.data, video_frame_size);
715
                                                }
716
                                        } else if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
717
//                                                static AVPicture pict;
718
                                                static struct SwsContext *img_convert_ctx = NULL;
719
                                                
720
                                                pFrame->pict_type = 0;
721
                                                if(img_convert_ctx == NULL)
722
                                                {
723
                                                        img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, dest_width, dest_height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
724
                                                        if(img_convert_ctx == NULL) {
725
                                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
726
                                                                exit(1);
727
                                                        }
728
                                                }
729
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
730
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
731
                                        } else {
732
                                                pFrame->pict_type = 0;
733
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
734
                                        }
735

    
736
                                        if(video_frame_size <= 0)
737
                                        {
738
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
739
                                                av_free_packet(&packet);
740
                                                continue;
741
                                        }
742

    
743
#ifdef DEBUG_VIDEO_FRAMES
744
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
745
                                                fprintf(stderr, "\n-------VIDEO FRAME outtype: %d%s\n",
746
                                                        pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
747
                                        }
748
#endif
749

    
750
                                        //use pts if dts is invalid
751
                                        if(packet.dts!=AV_NOPTS_VALUE)
752
                                                target_pts = packet.dts;
753
                                        else if(packet.pts!=AV_NOPTS_VALUE)
754
                                                target_pts = packet.pts;
755
                                        else
756
                                        {
757
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
758
                                                av_free_packet(&packet);
759
                                                continue;
760
                                        }
761

    
762
                                        if(!offset_av)
763
                                        {
764
                                                if(FirstTimeVideo && packet.dts>0) {
765
                                                        ptsvideo1 = (double)packet.dts;
766
                                                        FirstTimeVideo = 0;
767
#ifdef DEBUG_VIDEO_FRAMES
768
                                                        fprintf(stderr, "VIDEO: SET PTS BASE OFFSET %f\n", ptsvideo1);
769
#endif
770
                                                }
771
                                        }
772
                                        else //we want to compensate audio and video offset for this source
773
                                        {
774
                                                if(FirstTimeVideo && packet.dts>0) {
775
                                                        //maintain the offset between audio pts and video pts
776
                                                        //because in case of live source they have the same numbering
777
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
778
                                                                ptsvideo1 = ptsaudio1;
779
                                                        else
780
                                                                ptsvideo1 = (double)packet.dts;
781
                                                        FirstTimeVideo = 0;
782
#ifdef DEBUG_VIDEO_FRAMES
783
                                                        fprintf(stderr, "VIDEO LIVE: SET PTS BASE OFFSET %f\n", ptsvideo1);
784
#endif
785
                                                }
786
                                        }
787
                                        //compute the new video timestamp in milliseconds
788
                                        if(frame->number>0) {
789
                                                newTime = ((double)target_pts-ptsvideo1)*1000.0/((double)delta_video*(double)av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate));
790
                                                // store timestamp in useconds for next frame sleep
791
                                                newTime_video = newTime*1000;
792
                                        }
793
#ifdef DEBUG_TIMESTAMPING
794
                                        fprintf(stderr, "VIDEO: NEWTIMESTAMP %ld\n", newTime);
795
#endif
796
                                        if(newTime<0) {
797
#ifdef DEBUG_VIDEO_FRAMES
798
                                                fprintf(stderr, "VIDEO: SKIPPING FRAME\n");
799
#endif
800
                                                newtime_anomalies_counter++;
801
#ifdef DEBUG_ANOMALIES
802
                                                fprintf(stderr, "READLOOP: NEWTIME negative video timestamp anomaly detected number %d\n", newtime_anomalies_counter);
803
#endif
804
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
805
                                                av_free_packet(&packet);
806
                                                continue; //SKIP THIS FRAME, bad timestamp
807
                                        }
808
                                        
809
                                        //~ printf("pCodecCtxEnc->error[0]=%lld\n", pFrame->error[0]);
810
        
811
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
812
                                        frame->timestamp.tv_usec = newTime%1000;
813
                                        frame->size = video_frame_size;
814
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
815
                                        frame->type = vcopy ? pFrame->pict_type : (unsigned char)pCodecCtxEnc->coded_frame->pict_type;
816

    
817
#ifdef DEBUG_VIDEO_FRAMES
818
                                        if (!vcopy) fprintf(stderr, "VIDEO: original codec frame number %d vs. encoded %d vs. packed %d\n", pCodecCtx->frame_number, pCodecCtxEnc->frame_number, frame->number);
819
                                        if (!vcopy) fprintf(stderr, "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);
820
#endif
821

    
822
#ifdef YUV_RECORD_ENABLED
823
                                        if(!vcopy && ChunkerStreamerTestMode)
824
                                        {
825
                                                if(videotrace)
826
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pFrame->pict_type, frame->size);
827

    
828
                                                if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
829
                                                        SaveFrame(scaledFrame, dest_width, dest_height);
830
                                                else
831
                                                        SaveFrame(pFrame, dest_width, dest_height);
832

    
833
                                                ++savedVideoFrames;
834
                                                SaveEncodedFrame(frame, video_outbuf);
835

    
836
                                                if(!firstSavedVideoFrame)
837
                                                        firstSavedVideoFrame = frame->number;
838
                                                
839
                                                char tmp_filename[255];
840
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
841
                                                FILE* tmp = fopen(tmp_filename, "w");
842
                                                if(tmp)
843
                                                {
844
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
845
                                                                ,dest_width, dest_height
846
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
847
                                                        fclose(tmp);
848
                                                }
849
                                        }
850
#endif
851

    
852
#ifdef DEBUG_VIDEO_FRAMES
853
                                        fprintf(stderr, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
854
                                        fprintf(stderr, "VIDEO: timestamped sec %d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
855
#endif
856
                                        //contFrameVideo++; //lets increase the numbering of the frames
857

    
858
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
859
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
860
                                                exit(-1);
861
                                        }
862

    
863
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
864
                                                //calculate priority
865
                                                chunk->priority /= chunk->frames_num;
866

    
867
                                                //SAVE ON FILE
868
                                                //saveChunkOnFile(chunk);
869
                                                //Send the chunk to an external transport/player
870
                                                sendChunk(chunk);
871
#ifdef DEBUG_CHUNKER
872
                                                fprintf(stderr, "VIDEO: sent chunk video %d, prio:%f\n", chunk->seq, chunk->priority);
873
#endif
874
                                                chunk->seq = 0; //signal that we need an increase
875
                                                //initChunk(chunk, &seq_current_chunk);
876
                                        }
877

    
878
                                        //compute how long it took to encode video frame
879
                                        gettimeofday(&now_tv, NULL);
880
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
881
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
882
                                        if(usec > maxVDecodeTime)
883
                                                maxVDecodeTime = usec;
884

    
885
                                        //we DONT have an audio track, so we compute timings and determine
886
                                        //how much time we have to sleep at next VIDEO frame taking
887
                                        //also into account how much time was needed to encode the current
888
                                        //video frame
889
                                        //all this in case the video source is not live, i.e. not self-timing
890
                                        //and only in case there is no audio track
891
                                        if(audioStream == -1) {
892
                                                if(!live_source) {
893
                                                        if(newTime_prev != 0) {
894
                                                                //how much delay between video frames ideally
895
                                                                long long maxDelay = newTime_video - newTime_prev;
896
                                                                sleep = (maxDelay - usec);
897
#ifdef DEBUG_ANOMALIES
898
                                                                printf("\tmaxDelay=%ld\n", ((long)maxDelay));
899
                                                                printf("\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
900
#endif
901
                                                        }
902
                                                        else
903
                                                                sleep = 0;
904

    
905
                                                        //update and store counters
906
                                                        newTime_prev = newTime_video;
907

    
908
                                                        //i can also sleep now instead of at the beginning of
909
                                                        //the next frame because in this case we only have video
910
                                                        //frames, hence it would immediately be the next thing to do
911
                                                        if(sleep > 0) {
912
#ifdef DEBUG_ANOMALIES
913
                                                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
914
#endif
915
                                                                usleep(sleep);
916
                                                        }
917

    
918
                                                }
919
                                        }
920

    
921
                                }
922
                        }
923
                }
924
                else if(packet.stream_index==audioStream)
925
                {
926
                        if(sleep > 0)
927
                        {
928
#ifdef DEBUG_ANOMALIES
929
                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
930
#endif
931
                                usleep(sleep);
932
                        }
933
                        
934
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
935
                        //decode the audio packet into a raw audio source buffer
936
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
937
                        {
938
#ifdef DEBUG_AUDIO_FRAMES
939
                                fprintf(stderr, "\n-------AUDIO FRAME\n");
940
                                fprintf(stderr, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
941
#endif
942
                                if(audio_data_size>0) {
943
#ifdef DEBUG_AUDIO_FRAMES
944
                                        fprintf(stderr, "AUDIO: datasizeaudio:%d\n", audio_data_size);
945
#endif
946
                                        /* if a frame has been decoded, output it */
947
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
948
                                }
949
                                else {
950
                                        av_free_packet(&packet);
951
                                        continue;
952
                                }
953
        
954
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
955
                                if(audio_frame_size <= 0) {
956
                                        av_free_packet(&packet);
957
                                        continue;
958
                                }
959
                                
960
                                frame->number = contFrameAudio;
961

    
962
                                if(frame->number==0) {
963
                                        if(packet.dts==AV_NOPTS_VALUE) {
964
                                                av_free_packet(&packet);
965
                                                continue;
966
                                        }
967
                                        last_pkt_dts_audio = packet.dts;
968
                                        newTime = 0;
969
                                }
970
                                else {
971
                                        if(packet.dts!=AV_NOPTS_VALUE) {
972
                                                delta_audio = packet.dts-last_pkt_dts_audio;
973
                                                last_pkt_dts_audio = packet.dts;
974
                                        }
975
                                        else if(delta_audio==0) {
976
                                                av_free_packet(&packet);
977
                                                continue;
978
                                        }
979
                                }
980
#ifdef DEBUG_AUDIO_FRAMES
981
                                fprintf(stderr, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
982
#endif
983
                                //use pts if dts is invalid
984
                                if(packet.dts!=AV_NOPTS_VALUE)
985
                                        target_pts = packet.dts;
986
                                else if(packet.pts!=AV_NOPTS_VALUE) {
987
                                        target_pts = packet.pts;
988
                                } else  {
989
                                        av_free_packet(&packet);
990
                                        continue;
991
                                }
992

    
993
                                if(!offset_av)
994
                                {
995
                                        if(FirstTimeAudio && packet.dts>0) {
996
                                                ptsaudio1 = (double)packet.dts;
997
                                                FirstTimeAudio = 0;
998
#ifdef DEBUG_AUDIO_FRAMES
999
                                                fprintf(stderr, "AUDIO: SET PTS BASE OFFSET %f\n", ptsaudio1);
1000
#endif
1001
                                        }
1002
                                }
1003
                                else //we want to compensate audio and video offset for this source
1004
                                {
1005
                                        if(FirstTimeAudio && packet.dts>0) {
1006
                                                //maintain the offset between audio pts and video pts
1007
                                                //because in case of live source they have the same numbering
1008
                                                if(ptsvideo1 > 0) //if we have already seen some video frames...
1009
                                                        ptsaudio1 = ptsvideo1;
1010
                                                else
1011
                                                        ptsaudio1 = (double)packet.dts;
1012
                                                FirstTimeAudio = 0;
1013
#ifdef DEBUG_AUDIO_FRAMES
1014
                                                fprintf(stderr, "AUDIO LIVE: SET PTS BASE OFFSET %f\n", ptsaudio1);
1015
#endif
1016
                                        }
1017
                                }
1018
                                //compute the new audio timestamps in milliseconds
1019
                                if(frame->number>0) {
1020
                                        newTime = (((double)target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio;
1021
                                        // store timestamp in useconds for next frame sleep
1022
                                        newTime_audio = newTime*1000;
1023
                                }
1024
#ifdef DEBUG_TIMESTAMPING
1025
                                fprintf(stderr, "AUDIO: NEWTIMESTAMP %d\n", newTime);
1026
#endif
1027
                                if(newTime<0) {
1028
#ifdef DEBUG_AUDIO_FRAMES
1029
                                        fprintf(stderr, "AUDIO: SKIPPING FRAME\n");
1030
#endif
1031
                                        newtime_anomalies_counter++;
1032
#ifdef DEBUG_ANOMALIES
1033
                                        fprintf(stderr, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d\n", newtime_anomalies_counter);
1034
#endif
1035
                                        av_free_packet(&packet);
1036
                                        continue; //SKIP THIS FRAME, bad timestamp
1037
                                }
1038

    
1039
                                frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000;
1040
                                frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
1041
                                frame->size = audio_frame_size;
1042
                                frame->type = 5; // 5 is audio type
1043
#ifdef DEBUG_AUDIO_FRAMES
1044
                                fprintf(stderr, "AUDIO: pts %lld duration %d timebase %d %lld dts %d\n", packet.pts, (int)packet.duration, pFormatCtx->streams[audioStream]->time_base.num, pFormatCtx->streams[audioStream]->time_base.den, packet.dts);
1045
                                fprintf(stderr, "AUDIO: timestamp sec:%d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
1046
                                fprintf(stderr, "AUDIO: deltaaudio %lld\n", delta_audio);        
1047
#endif
1048
                                contFrameAudio++;
1049

    
1050
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1051
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1052
                                        exit(-1);
1053
                                }
1054
                                //set priority
1055
                                chunkaudio->priority = 1;
1056

    
1057
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1058
                                        // is chunk filled using current strategy?
1059
                                        //SAVE ON FILE
1060
                                        //saveChunkOnFile(chunkaudio);
1061
                                        //Send the chunk to an external transport/player
1062
                                        sendChunk(chunkaudio);
1063
#ifdef DEBUG_CHUNKER
1064
                                        fprintf(stderr, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1065
#endif
1066
                                        chunkaudio->seq = 0; //signal that we need an increase
1067
                                        //initChunk(chunkaudio, &seq_current_chunk);
1068
                                }
1069

    
1070
                                //we have an audio track, so we compute timings and determine
1071
                                //how much time we have to sleep at next audio frame taking
1072
                                //also into account how much time was needed to encode the
1073
                                //video frames
1074
                                //all this in case the video source is not live, i.e. not self-timing
1075
                                if(!live_source)
1076
                                {
1077
                                        if(newTime_prev != 0)
1078
                                        {
1079
                                                long long maxDelay = newTime_audio - newTime_prev;
1080

    
1081
                                                gettimeofday(&now_tv, NULL);
1082
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1083
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1084

    
1085
                                                if(usec > maxAudioInterval)
1086
                                                        maxAudioInterval = usec;
1087

    
1088
                                                lateTime -= (maxDelay - usec);
1089
#ifdef DEBUG_ANOMALIES
1090
                                                printf("\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1091
                                                printf("\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1092
#endif
1093

    
1094
                                                if((lateTime+maxAudioInterval) < 0)
1095
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1096
                                                else
1097
                                                        sleep = 0;
1098
                                        }
1099
                                        else
1100
                                                sleep = 0;
1101

    
1102
                                        newTime_prev = newTime_audio;
1103
                                        gettimeofday(&lastAudioSent, NULL);
1104
                                }
1105
                        }
1106
                }
1107
#ifdef DEBUG_CHUNKER
1108
                fprintf(stderr,"Free the packet that was allocated by av_read_frame\n");
1109
#endif
1110
                av_free_packet(&packet);
1111
        }
1112
        
1113
        if(videotrace)
1114
                fclose(videotrace);
1115
        if(psnrtrace)
1116
                fclose(psnrtrace);
1117

    
1118
close:
1119
        if(chunk->seq != 0 && chunk->frames_num>0) {
1120
                //SAVE ON FILE
1121
                //saveChunkOnFile(chunk);
1122
                //Send the chunk to an external transport/player
1123
                sendChunk(chunk);
1124
#ifdef DEBUG_CHUNKER
1125
                fprintf(stderr, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1126
#endif
1127
                chunk->seq = 0; //signal that we need an increase just in case we will restart
1128
        }
1129
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1130
                //SAVE ON FILE     
1131
                //saveChunkOnFile(chunkaudio);
1132
                //Send the chunk via http to an external transport/player
1133
                sendChunk(chunkaudio);
1134
#ifdef DEBUG_CHUNKER
1135
                fprintf(stderr, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1136
#endif
1137
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1138
        }
1139

    
1140
#ifdef HTTPIO
1141
        /* finalize the HTTP chunk pusher */
1142
        finalizeChunkPusher();
1143
#endif
1144

    
1145
        free(chunk);
1146
        free(chunkaudio);
1147
        free(frame);
1148
        av_free(video_outbuf);
1149
        av_free(scaledFrame_buffer);
1150
        av_free(audio_outbuf);
1151
        free(cmeta);
1152

    
1153
        // Free the YUV frame
1154
        av_free(pFrame);
1155
        av_free(scaledFrame);
1156
        av_free(samples);
1157
  
1158
        // Close the codec
1159
        if (!vcopy) avcodec_close(pCodecCtx);
1160
        if (!vcopy) avcodec_close(pCodecCtxEnc);
1161

    
1162
        if(audioStream!=-1) {
1163
                avcodec_close(aCodecCtx);
1164
                avcodec_close(aCodecCtxEnc);
1165
        }
1166
  
1167
        // Close the video file
1168
        av_close_input_file(pFormatCtx);
1169

    
1170
        if(LOOP_MODE) {
1171
                //we want video to continue, but the av_read_frame stopped
1172
                //lets wait a 5 secs, and cycle in again
1173
                usleep(5000000);
1174
#ifdef DEBUG_CHUNKER
1175
                fprintf(stderr, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
1176
#endif
1177
                videoStream = -1;
1178
                audioStream = -1;
1179
                FirstTimeAudio=1;
1180
                FirstTimeVideo=1;
1181
                pts_anomalies_counter=0;
1182
                newtime_anomalies_counter=0;
1183
                newTime=0;
1184
                newTime_audio=0;
1185
                newTime_prev=0;
1186
                ptsvideo1=0.0;
1187
                ptsaudio1=0.0;
1188
                last_pkt_dts=0;
1189
                delta_video=0;
1190
                delta_audio=0;
1191
                last_pkt_dts_audio=0;
1192
                target_pts=0;
1193
                i=0;
1194
                //~ contFrameVideo = 0;
1195
                //~ contFrameAudio = 1;
1196
                
1197
#ifdef YUV_RECORD_ENABLED
1198
                if(ChunkerStreamerTestMode)
1199
                {
1200
                        video_record_count++;
1201
                        //~ savedVideoFrames = 0;
1202
                        
1203
                        //~ char tmp_filename[255];
1204
                        //~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
1205
                        //~ FILE *pFile=fopen(tmp_filename, "w");
1206
                        //~ if(pFile!=NULL)
1207
                                //~ fclose(pFile);
1208
                }
1209
#endif
1210

    
1211
                goto restart;
1212
        }
1213

    
1214
#ifdef TCPIO
1215
        finalizeTCPChunkPusher();
1216
#endif
1217

    
1218
        return 0;
1219
}
1220

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

    
1225
        //moving temp pointer to encode Frame on the wire
1226
        uint8_t *tempdata = NULL;
1227

    
1228
        if(chunk->seq == 0) {
1229
                initChunk(chunk, &seq_current_chunk);
1230
        }
1231
        //add frame priority to chunk priority (to be normalized later on)
1232
        chunk->priority += frame->type + 1; // I:2, P:3, B:4
1233

    
1234
        //HINT on malloc
1235
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1236
        if(!chunk->data)  {
1237
                fprintf(stderr, "Memory error in chunk!!!\n");
1238
                return -1;
1239
        }
1240
        chunk->frames_num++; // number of frames in the current chunk
1241

    
1242
/*
1243
        //package the Frame header
1244
        tempdata = chunk->data+chunk->payload_len;
1245
        *((int32_t *)tempdata) = frame->number;
1246
        tempdata+=sizeof(int32_t);
1247
        *((struct timeval *)tempdata) = frame->timestamp;
1248
        tempdata+=sizeof(struct timeval);
1249
        *((int32_t *)tempdata) = frame->size;
1250
        tempdata+=sizeof(int32_t);
1251
        *((int32_t *)tempdata) = frame->type;
1252
        tempdata+=sizeof(int32_t);
1253
*/
1254
        //package the Frame header: network order and platform independent
1255
        tempdata = chunk->data+chunk->payload_len;
1256
        bit32_encoded_push(frame->number, tempdata);
1257
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1258
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1259
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1260
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1261

    
1262
         //insert the new frame data
1263
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1264
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1265
        //chunk lenght is updated just prior to pushing it out because
1266
        //the chunk header len is better calculated there
1267
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1268

    
1269
        //update timestamps
1270
        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) {
1271
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1272
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1273
        }
1274
        
1275
        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) {
1276
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1277
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1278
        }
1279
        return 0;
1280
}
1281

    
1282
void SaveFrame(AVFrame *pFrame, int width, int height)
1283
{
1284
        FILE *pFile;
1285
        int  y;
1286

    
1287
         // Open file
1288
        char tmp_filename[255];
1289
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1290
        pFile=fopen(tmp_filename, "ab");
1291
        if(pFile==NULL)
1292
                return;
1293

    
1294
        // Write header
1295
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1296
  
1297
        // Write Y data
1298
        for(y=0; y<height; y++)
1299
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1300
                {
1301
                        printf("errno = %d\n", errno);
1302
                        exit(1);
1303
                }
1304
        // Write U data
1305
        for(y=0; y<height/2; y++)
1306
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1307
                  {
1308
                        printf("errno = %d\n", errno);
1309
                        exit(1);
1310
                }
1311
        // Write V data
1312
        for(y=0; y<height/2; y++)
1313
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1314
                  {
1315
                        printf("errno = %d\n", errno);
1316
                        exit(1);
1317
                }
1318
  
1319
        // Close file
1320
        fclose(pFile);
1321
}
1322

    
1323
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1324
{
1325
        static FILE* pFile = NULL;
1326
        
1327
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1328
        fwrite(frame, sizeof(Frame), 1, pFile);
1329
        fwrite(video_outbuf, frame->size, 1, pFile);
1330
        fclose(pFile);
1331
}