Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ 0fe99630

History | View | Annotate | Download (40.2 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 = 0;
44
int newtime_anomaly_threshold = 0;
45
bool timebank = false;
46
char *outside_world_url = NULL;
47

    
48
bool vcopy = false;
49

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

    
59
        return 0;
60
}
61

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

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

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

    
98
int quit = 0;
99

    
100
void sigproc()
101
{
102
        printf("you have pressed ctrl-c, terminating...\n");
103
        quit = 1;
104
}
105

    
106
static void print_usage(int argc, char *argv[])
107
{
108
  fprintf (stderr,
109
    "\nUsage:%s [options]\n"
110
    "\n"
111
    "Mandatory options:\n"
112
    "\t[-i input file]\n"
113
    "\t[-a audio bitrate]\n"
114
    "\t[-v video bitrate]\n\n"
115
    "Other options:\n"
116
    "\t[-F output] (overrides config file)\n"
117
    "\t[-A audioencoder]\n"
118
    "\t[-V videoencoder]\n"
119
    "\t[-s WxH]: force video size.\n"
120
    "\t[-l]: this is a live stream.\n"
121
    "\t[-o]: adjust av frames timestamps.\n"
122
    "\t[-t]: QoE test mode\n\n"
123
    "=======================================================\n", argv[0]
124
    );
125
  }
126

    
127
int sendChunk(ExternalChunk *chunk) {
128
#ifdef HTTPIO
129
                                                return pushChunkHttp(chunk, outside_world_url);
130
#endif
131
#ifdef TCPIO
132
                                                return pushChunkTcp(chunk);
133
#endif
134
#ifdef UDPIO
135
                                                return pushChunkUDP(chunk);
136
#endif
137
}
138

    
139
int main(int argc, char *argv[]) {
140
        signal(SIGINT, sigproc);
141
        
142
        int i=0;
143

    
144
        //output variables
145
        uint8_t *video_outbuf = NULL;
146
        int video_outbuf_size, video_frame_size;
147
        uint8_t *audio_outbuf = NULL;
148
        int audio_outbuf_size, audio_frame_size;
149
        int audio_data_size;
150

    
151
        //numeric identifiers of input streams
152
        int videoStream = -1;
153
        int audioStream = -1;
154

    
155
//        int len1;
156
        int frameFinished;
157
        //frame sequential counters
158
        int contFrameAudio=1, contFrameVideo=0;
159
//        int numBytes;
160

    
161
        //command line parameters
162
        int audio_bitrate = -1;
163
        int video_bitrate = -1;
164
        char *audio_codec = "mp2";
165
        char *video_codec = "mpeg4";
166
        int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file)
167
        int offset_av = 0; //tells to compensate for offset between audio and video in the file
168
        
169
        //a raw buffer for decoded uncompressed audio samples
170
        int16_t *samples = NULL;
171
        //a raw uncompressed video picture
172
        AVFrame *pFrame = NULL;
173
        AVFrame *scaledFrame = NULL;
174

    
175
        AVFormatContext *pFormatCtx;
176
        AVCodecContext  *pCodecCtx = NULL ,*pCodecCtxEnc = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL;
177
        AVCodec         *pCodec = NULL ,*pCodecEnc = NULL ,*aCodec = NULL ,*aCodecEnc = NULL;
178
        AVPacket         packet;
179

    
180
        //stuff needed to compute the right timestamps
181
        short int FirstTimeAudio=1, FirstTimeVideo=1;
182
        short int pts_anomalies_counter=0;
183
        short int newtime_anomalies_counter=0;
184
        long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0;
185
        struct timeval lastAudioSent = {0, 0};
186
        double ptsvideo1=0.0;
187
        double ptsaudio1=0.0;
188
        int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0;
189

    
190
        //Napa-Wine specific Frame and Chunk structures for transport
191
        Frame *frame = NULL;
192
        ExternalChunk *chunk = NULL;
193
        ExternalChunk *chunkaudio = NULL;
194
        
195
        char av_input[1024];
196
        int dest_width = -1;
197
        int dest_height = -1;
198
        
199
        static struct option long_options[] =
200
        {
201
                /* These options set a flag. */
202
                {"long_option", required_argument, 0, 0},
203
                {0, 0, 0, 0}
204
        };
205
        /* `getopt_long' stores the option index here. */
206
        int option_index = 0, c;
207
        int mandatories = 0;
208
        while ((c = getopt_long (argc, argv, "i:a:v:A:V:s:lotF:", long_options, &option_index)) != -1)
209
        {
210
                switch (c) {
211
                        case 0: //for long options
212
                                break;
213
                        case 'i':
214
                                sprintf(av_input, "%s", optarg);
215
                                mandatories++;
216
                                break;
217
                        case 'a':
218
                                sscanf(optarg, "%d", &audio_bitrate);
219
                                mandatories++;
220
                                break;
221
                        case 'v':
222
                                sscanf(optarg, "%d", &video_bitrate);
223
                                mandatories++;
224
                                break;
225
                        case 'A':
226
                                audio_codec = strdup(optarg);
227
                                break;
228
                        case 'V':
229
                                video_codec = strdup(optarg);
230
                                break;
231
                        case 's':
232
                                sscanf(optarg, "%dx%d", &dest_width, &dest_height);
233
                                break;
234
                        case 'l':
235
                                live_source = 1;
236
                                break;
237
                        case 'o':
238
                                offset_av = 1;
239
                                break;
240
                        case 't':
241
                                ChunkerStreamerTestMode = 1;
242
                                break;
243
                        case 'F':
244
                                outside_world_url = strdup(optarg);
245
                                break;
246
                        default:
247
                                print_usage(argc, argv);
248
                                return -1;
249
                }
250
        }
251
        
252
        if(mandatories < 3) 
253
        {
254
                print_usage(argc, argv);
255
                return -1;
256
        }
257

    
258
#ifdef YUV_RECORD_ENABLED
259
        if(ChunkerStreamerTestMode)
260
        {
261
                DELETE_DIR("yuv_data");
262
                CREATE_DIR("yuv_data");
263
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
264
                //fclose(pFile);
265
        }
266
#endif
267

    
268
restart:
269
        // read the configuration file
270
        cmeta = chunkerInit();
271
        if (!outside_world_url) {
272
                outside_world_url = strdup(cmeta->outside_world_url);
273
        }
274
        switch(cmeta->strategy)
275
        {
276
                case 1:
277
                        chunkFilled = chunkFilledSizeStrategy;
278
                        break;
279
                default:
280
                        chunkFilled = chunkFilledFramesStrategy;
281
        }
282
                
283
        if(live_source)
284
                fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
285
        if(offset_av)
286
                fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
287

    
288
        // Register all formats and codecs
289
        av_register_all();
290

    
291
        // Open input file
292
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
293
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
294
                exit(-1);
295
        }
296

    
297
        // Retrieve stream information
298
        if(av_find_stream_info(pFormatCtx) < 0) {
299
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
300
                exit(-1);
301
        }
302

    
303
        // Dump information about file onto standard error
304
        dump_format(pFormatCtx, 0, av_input, 0);
305

    
306
        // Find the video and audio stream numbers
307
        for(i=0; i<pFormatCtx->nb_streams; i++) {
308
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
309
                        videoStream=i;
310
                }
311
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
312
                        audioStream=i;
313
                }
314
        }
315
        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);
316

    
317
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
318
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
319

    
320
        if(videoStream==-1 && audioStream==-1) {
321
                fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
322
                exit(-1);
323
        }
324

    
325
        // Get a pointer to the codec context for the input video stream
326
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
327
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
328
        //extract W and H
329
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
330

    
331
        // Get a pointer to the codec context for the input audio stream
332
        if(audioStream != -1) {
333
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
334
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
335
        }
336

    
337
        // Figure out size
338
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
339
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
340

    
341
        //setup video output encoder
342
 if (strcmp(video_codec, "copy") == 0) {
343
        vcopy = true;
344
 } else {
345
        pCodecEnc = avcodec_find_encoder_by_name(video_codec);
346
        if (pCodecEnc) {
347
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
348
        } else {
349
                fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
350
                return -1; // Codec not found
351
        }
352

    
353
        pCodecCtxEnc=avcodec_alloc_context();
354
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
355
        pCodecCtxEnc->codec_id = pCodecEnc->id;
356

    
357
        pCodecCtxEnc->bit_rate = video_bitrate;
358
        //~ pCodecCtxEnc->qmin = 30;
359
        //~ pCodecCtxEnc->qmax = 30;
360
        //times 20 follows the defaults, was not needed in previous versions of libavcodec
361
        pCodecCtxEnc->bit_rate_tolerance = video_bitrate*20;
362
//        pCodecCtxEnc->crf = 20.0f;
363
        // resolution must be a multiple of two 
364
        pCodecCtxEnc->width = dest_width;
365
        pCodecCtxEnc->height = dest_height;
366
        // frames per second 
367
        //~ pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
368
        //printf("pCodecCtx->time_base=%d/%d\n", pCodecCtx->time_base.num, pCodecCtx->time_base.den);
369
        pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
370
        pCodecCtxEnc->gop_size = 12; // emit one intra frame every twelve frames 
371
        pCodecCtxEnc->max_b_frames=1;
372
        pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P;
373
        pCodecCtxEnc->flags = CODEC_FLAG_PSNR;
374
        //~ pCodecCtxEnc->flags |= CODEC_FLAG_QSCALE;
375
  switch (pCodecEnc->id) {
376
    case CODEC_ID_H264 :
377
        pCodecCtxEnc->me_range=16;
378
        pCodecCtxEnc->max_qdiff=4;
379
        pCodecCtxEnc->qmin=1;
380
        pCodecCtxEnc->qmax=30;
381
        pCodecCtxEnc->qcompress=0.6;
382
        // frames per second 
383

    
384
//        pCodecCtxEnc->rc_min_rate = 0;
385
//        pCodecCtxEnc->rc_max_rate = 0;
386
//        pCodecCtxEnc->rc_buffer_size = 0;
387
//        pCodecCtxEnc->partitions = X264_PART_I4X4 | X264_PART_I8X8 | X264_PART_P8X8 | X264_PART_P4X4 | X264_PART_B8X8;
388
//        pCodecCtxEnc->crf = 0.0f;
389
        
390
#ifdef STREAMER_X264_USE_SSIM
391
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
392
#endif
393

    
394
        pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
395
        // pCodecCtxEnc->rc_min_rate = 0;
396
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
397
        // pCodecCtxEnc->rc_buffer_size = 0;
398
        break;
399
    case CODEC_ID_MPEG4 :
400
        break;
401
    default:
402
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
403
  }
404
 
405
        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);
406
 }
407

    
408
        if(pCodec==NULL) {
409
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
410
                return -1; // Codec not found
411
        }
412
        if(!vcopy && pCodecEnc==NULL) {
413
                fprintf(stderr, "INIT: Unsupported OUT VIDEO pcodecenc!\n");
414
                return -1; // Codec not found
415
        }
416
        if(avcodec_open(pCodecCtx, pCodec)<0) {
417
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
418
                return -1; // Could not open codec
419
        }
420
        if(!vcopy && avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
421
                fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
422
                return -1; // Could not open codec
423
        }
424
        if(audioStream!=-1) {
425
                //setup audio output encoder
426
                aCodecCtxEnc = avcodec_alloc_context();
427
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
428
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
429
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
430
                aCodecCtxEnc->channels = aCodecCtx->channels;
431
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
432

    
433
                // Find the decoder for the audio stream
434
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
435
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
436
                if(aCodec==NULL) {
437
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
438
                        return -1;
439
                }
440
                if(aCodecEnc==NULL) {
441
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
442
                        return -1;
443
                }
444
        
445
                if(avcodec_open(aCodecCtx, aCodec)<0) {
446
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
447
                        return -1; // Could not open codec
448
                }
449
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
450
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
451
                        return -1; // Could not open codec
452
                }
453
        }
454
        else {
455
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
456
        }
457

    
458
        // Allocate audio in and out buffers
459
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
460
        if(samples == NULL) {
461
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
462
                return -1;
463
        }
464
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
465
        audio_outbuf = av_malloc(audio_outbuf_size);
466
        if(audio_outbuf == NULL) {
467
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
468
                return -1;
469
        }
470

    
471
        // Allocate video in frame and out buffer
472
        pFrame=avcodec_alloc_frame();
473
        scaledFrame=avcodec_alloc_frame();
474
        if(pFrame==NULL || scaledFrame == NULL) {
475
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
476
                return -1;
477
        }
478
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
479
        video_outbuf = av_malloc(video_outbuf_size);
480
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, dest_width, dest_height);
481
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
482
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, dest_width, dest_height);
483
        if(!video_outbuf || !scaledFrame_buffer) {
484
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
485
                return -1;
486
        }
487

    
488
        //allocate Napa-Wine transport
489
        frame = (Frame *)malloc(sizeof(Frame));
490
        if(!frame) {
491
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
492
                return -1;
493
        }
494
        //create an empty first video chunk
495
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
496
        if(!chunk) {
497
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
498
                return -1;
499
        }
500
        chunk->data = NULL;
501
        chunk->seq = 0;
502
        //initChunk(chunk, &seq_current_chunk); if i init them now i get out of sequence
503
#ifdef DEBUG_CHUNKER
504
        fprintf(stderr, "INIT: chunk video %d\n", chunk->seq);
505
#endif
506
        //create empty first audio chunk
507
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
508
        if(!chunkaudio) {
509
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
510
                return -1;
511
        }
512
  chunkaudio->data=NULL;
513
        chunkaudio->seq = 0;
514
        //initChunk(chunkaudio, &seq_current_chunk);
515
#ifdef DEBUG_CHUNKER
516
        fprintf(stderr, "INIT: chunk audio %d\n", chunkaudio->seq);
517
#endif
518

    
519
#ifdef HTTPIO
520
        /* initialize the HTTP chunk pusher */
521
        initChunkPusher(); //TRIPLO
522
#endif
523

    
524
        long sleep=0;
525
        struct timeval now_tv;
526
        struct timeval tmp_tv;
527
        long long lateTime = 0;
528
        long long maxAudioInterval = 0;
529
        long long maxVDecodeTime = 0;
530
//        unsigned char lastIFrameDistance = 0;
531

    
532
#ifdef TCPIO
533
        static char peer_ip[16];
534
        static int peer_port;
535
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
536
        if (res < 2) {
537
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
538
                return -2;
539
        }
540
        
541
        initTCPPush(peer_ip, peer_port);
542
#endif
543
#ifdef UDPIO
544
        static char peer_ip[16];
545
        static int peer_port;
546
        int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
547
        if (res < 2) {
548
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
549
                return -2;
550
        }
551
        
552
        initUDPPush(peer_ip, peer_port);
553
#endif
554
        
555
        char videotrace_filename[255];
556
        char psnr_filename[255];
557
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
558
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
559
        FILE* videotrace = fopen(videotrace_filename, "w");
560
        FILE* psnrtrace = fopen(psnr_filename, "w");
561

    
562
        //main loop to read from the input file
563
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
564
        {
565
                //detect if a strange number of anomalies is occurring
566
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
567
                        pts_anomalies_counter++;
568
#ifdef DEBUG_ANOMALIES
569
                        fprintf(stderr, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
570
#endif
571
                        if(live_source) { //reset just in case of live source
572
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
573
                                        pts_anomalies_counter = 0;
574
                                        FirstTimeVideo = 1;
575
                                        FirstTimeAudio = 1;
576
#ifdef DEBUG_ANOMALIES
577
                                        fprintf(stderr, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
578
#endif
579
                                }
580
                        }
581
                }
582

    
583
                //newTime_video and _audio are in usec
584
                //if video and audio stamps differ more than 5sec
585
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
586
                        newtime_anomalies_counter++;
587
#ifdef DEBUG_ANOMALIES
588
                        fprintf(stderr, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
589
#endif
590
                }
591

    
592
                if(newtime_anomalies_counter > newtime_anomaly_threshold) {
593
                        if(live_source) { //restart just in case of live source
594
#ifdef DEBUG_ANOMALIES
595
                                fprintf(stderr, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
596
#endif
597
                                goto close;
598
                        }
599
                }
600

    
601
                // Is this a packet from the video stream?
602
                if(packet.stream_index==videoStream)
603
                {
604
                        if(!live_source)
605
                        {
606
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
607
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
608
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
609
                                        // therefore, it's better to skip the frame
610
                                        if(timebank && (lateTime+maxVDecodeTime) >= 0)
611
                                        {
612
#ifdef DEBUG_ANOMALIES
613
                                                fprintf(stderr, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
614
#endif
615
                                                av_free_packet(&packet);
616
                                                continue;
617
                                        }
618
                                }
619
                        }
620
                        
621
                        gettimeofday(&tmp_tv, NULL);
622
                        
623
                        //decode the video packet into a raw pFrame
624
                        if(avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet)>0)
625
                        {
626
                                // usleep(5000);
627
#ifdef DEBUG_VIDEO_FRAMES
628
                                fprintf(stderr, "\n-------VIDEO FRAME type %d\n", pFrame->pict_type);
629
                                fprintf(stderr, "VIDEO: dts %lld pts %lld\n", packet.dts, packet.pts);
630
#endif
631
                                if(frameFinished)
632
                                { // it must be true all the time else error
633
                                
634
                                        frame->number = ++contFrameVideo;
635

    
636
#ifdef VIDEO_DEINTERLACE
637
                                if (!vcopy) {
638
                                        avpicture_deinterlace(
639
                                                (AVPicture*) pFrame,
640
                                                (const AVPicture*) pFrame,
641
                                                pCodecCtxEnc->pix_fmt,
642
                                                pCodecCtxEnc->width,
643
                                                pCodecCtxEnc->height);
644
                                }
645
#endif
646

    
647
#ifdef DEBUG_VIDEO_FRAMES
648
                                        fprintf(stderr, "VIDEO: finished frame %d dts %lld pts %lld\n", frame->number, packet.dts, packet.pts);
649
#endif
650
                                        if(frame->number==0) {
651
                                                if(packet.dts==AV_NOPTS_VALUE)
652
                                                {
653
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
654
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
655
                                                        av_free_packet(&packet);
656
                                                        continue;
657
                                                }
658
                                                last_pkt_dts = packet.dts;
659
                                                newTime = 0;
660
                                        }
661
                                        else {
662
                                                if(packet.dts!=AV_NOPTS_VALUE) {
663
                                                        delta_video = packet.dts-last_pkt_dts;
664
                                                        last_pkt_dts = packet.dts;
665
                                                }
666
                                                else if(delta_video==0)
667
                                                {
668
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
669
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
670
                                                        av_free_packet(&packet);
671
                                                        continue;
672
                                                }
673
                                        }
674
#ifdef DEBUG_VIDEO_FRAMES
675
                                        fprintf(stderr, "VIDEO: deltavideo : %d\n", (int)delta_video);
676
#endif
677

    
678
                                        if(vcopy) {
679
                                                video_frame_size = packet.size;
680
                                                if (video_frame_size > video_outbuf_size) {
681
                                                        fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
682
                                                        av_free_packet(&packet);
683
                                                        continue;
684
                                                } else {
685
                                                        memcpy(video_outbuf, packet.data, video_frame_size);
686
                                                }
687
                                        } else if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
688
//                                                static AVPicture pict;
689
                                                static struct SwsContext *img_convert_ctx = NULL;
690
                                                
691
                                                if(img_convert_ctx == NULL)
692
                                                {
693
                                                        img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, dest_width, dest_height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
694
                                                        if(img_convert_ctx == NULL) {
695
                                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
696
                                                                exit(1);
697
                                                        }
698
                                                }
699
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
700
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
701
                                        }
702
                                        else
703
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
704
                                        
705
                                        if(video_frame_size <= 0)
706
                                        {
707
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
708
                                                av_free_packet(&packet);
709
                                                continue;
710
                                        }
711

    
712
#ifdef DEBUG_VIDEO_FRAMES
713
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
714
                                                fprintf(stderr, "\n-------VIDEO FRAME intype %d%s -> outtype: %d%s\n",
715
                                                        pFrame->pict_type, pFrame->key_frame ? " (key)" : "",
716
                                                        pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
717
                                        }
718
#endif
719

    
720
                                        //use pts if dts is invalid
721
                                        if(packet.dts!=AV_NOPTS_VALUE)
722
                                                target_pts = packet.dts;
723
                                        else if(packet.pts!=AV_NOPTS_VALUE)
724
                                                target_pts = packet.pts;
725
                                        else
726
                                        {
727
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
728
                                                av_free_packet(&packet);
729
                                                continue;
730
                                        }
731

    
732
                                        if(!offset_av)
733
                                        {
734
                                                if(FirstTimeVideo && packet.dts>0) {
735
                                                        ptsvideo1 = (double)packet.dts;
736
                                                        FirstTimeVideo = 0;
737
#ifdef DEBUG_VIDEO_FRAMES
738
                                                        fprintf(stderr, "VIDEO: SET PTS BASE OFFSET %f\n", ptsvideo1);
739
#endif
740
                                                }
741
                                        }
742
                                        else //we want to compensate audio and video offset for this source
743
                                        {
744
                                                if(FirstTimeVideo && packet.dts>0) {
745
                                                        //maintain the offset between audio pts and video pts
746
                                                        //because in case of live source they have the same numbering
747
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
748
                                                                ptsvideo1 = ptsaudio1;
749
                                                        else
750
                                                                ptsvideo1 = (double)packet.dts;
751
                                                        FirstTimeVideo = 0;
752
#ifdef DEBUG_VIDEO_FRAMES
753
                                                        fprintf(stderr, "VIDEO LIVE: SET PTS BASE OFFSET %f\n", ptsvideo1);
754
#endif
755
                                                }
756
                                        }
757
                                        //compute the new video timestamp in milliseconds
758
                                        if(frame->number>0) {
759
                                                newTime = ((double)target_pts-ptsvideo1)*1000.0/((double)delta_video*(double)av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate));
760
                                                // store timestamp in useconds for next frame sleep
761
                                                newTime_video = newTime*1000;
762
                                        }
763
#ifdef DEBUG_TIMESTAMPING
764
                                        fprintf(stderr, "VIDEO: NEWTIMESTAMP %ld\n", newTime);
765
#endif
766
                                        if(newTime<0) {
767
#ifdef DEBUG_VIDEO_FRAMES
768
                                                fprintf(stderr, "VIDEO: SKIPPING FRAME\n");
769
#endif
770
                                                newtime_anomalies_counter++;
771
#ifdef DEBUG_ANOMALIES
772
                                                fprintf(stderr, "READLOOP: NEWTIME negative video timestamp anomaly detected number %d\n", newtime_anomalies_counter);
773
#endif
774
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
775
                                                av_free_packet(&packet);
776
                                                continue; //SKIP THIS FRAME, bad timestamp
777
                                        }
778
                                        
779
                                        //~ printf("pCodecCtxEnc->error[0]=%lld\n", pFrame->error[0]);
780
        
781
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
782
                                        frame->timestamp.tv_usec = newTime%1000;
783
                                        frame->size = video_frame_size;
784
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
785
                                        frame->type = vcopy ? pFrame->pict_type : (unsigned char)pCodecCtxEnc->coded_frame->pict_type;
786

    
787
#ifdef DEBUG_VIDEO_FRAMES
788
                                        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);
789
                                        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);
790
#endif
791

    
792
#ifdef YUV_RECORD_ENABLED
793
                                        if(!vcopy && ChunkerStreamerTestMode)
794
                                        {
795
                                                if(videotrace)
796
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pFrame->pict_type, frame->size);
797

    
798
                                                if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
799
                                                        SaveFrame(scaledFrame, dest_width, dest_height);
800
                                                else
801
                                                        SaveFrame(pFrame, dest_width, dest_height);
802

    
803
                                                ++savedVideoFrames;
804
                                                SaveEncodedFrame(frame, video_outbuf);
805

    
806
                                                if(!firstSavedVideoFrame)
807
                                                        firstSavedVideoFrame = frame->number;
808
                                                
809
                                                char tmp_filename[255];
810
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
811
                                                FILE* tmp = fopen(tmp_filename, "w");
812
                                                if(tmp)
813
                                                {
814
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
815
                                                                ,dest_width, dest_height
816
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
817
                                                        fclose(tmp);
818
                                                }
819
                                        }
820
#endif
821

    
822
#ifdef DEBUG_VIDEO_FRAMES
823
                                        fprintf(stderr, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
824
                                        fprintf(stderr, "VIDEO: timestamped sec %d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
825
#endif
826
                                        //contFrameVideo++; //lets increase the numbering of the frames
827

    
828
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
829
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
830
                                                exit(-1);
831
                                        }
832

    
833
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
834
                                                //SAVE ON FILE
835
                                                //saveChunkOnFile(chunk);
836
                                                //Send the chunk to an external transport/player
837
                                                sendChunk(chunk);
838
#ifdef DEBUG_CHUNKER
839
                                                fprintf(stderr, "VIDEO: sent chunk video %d\n", chunk->seq);
840
#endif
841
                                                chunk->seq = 0; //signal that we need an increase
842
                                                //initChunk(chunk, &seq_current_chunk);
843
                                        }
844

    
845
                                        //compute how long it took to encode video frame
846
                                        gettimeofday(&now_tv, NULL);
847
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
848
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
849
                                        if(usec > maxVDecodeTime)
850
                                                maxVDecodeTime = usec;
851

    
852
                                        //we DONT have an audio track, so we compute timings and determine
853
                                        //how much time we have to sleep at next VIDEO frame taking
854
                                        //also into account how much time was needed to encode the current
855
                                        //video frame
856
                                        //all this in case the video source is not live, i.e. not self-timing
857
                                        //and only in case there is no audio track
858
                                        if(audioStream == -1) {
859
                                                if(!live_source) {
860
                                                        if(newTime_prev != 0) {
861
                                                                //how much delay between video frames ideally
862
                                                                long long maxDelay = newTime_video - newTime_prev;
863
                                                                sleep = (maxDelay - usec);
864
#ifdef DEBUG_ANOMALIES
865
                                                                printf("\tmaxDelay=%ld\n", ((long)maxDelay));
866
                                                                printf("\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
867
#endif
868
                                                        }
869
                                                        else
870
                                                                sleep = 0;
871

    
872
                                                        //update and store counters
873
                                                        newTime_prev = newTime_video;
874

    
875
                                                        //i can also sleep now instead of at the beginning of
876
                                                        //the next frame because in this case we only have video
877
                                                        //frames, hence it would immediately be the next thing to do
878
                                                        if(sleep > 0) {
879
#ifdef DEBUG_ANOMALIES
880
                                                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
881
#endif
882
                                                                usleep(sleep);
883
                                                        }
884

    
885
                                                }
886
                                        }
887

    
888
                                }
889
                        }
890
                }
891
                else if(packet.stream_index==audioStream)
892
                {
893
                        if(sleep > 0)
894
                        {
895
#ifdef DEBUG_ANOMALIES
896
                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
897
#endif
898
                                usleep(sleep);
899
                        }
900
                        
901
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
902
                        //decode the audio packet into a raw audio source buffer
903
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
904
                        {
905
#ifdef DEBUG_AUDIO_FRAMES
906
                                fprintf(stderr, "\n-------AUDIO FRAME\n");
907
                                fprintf(stderr, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
908
#endif
909
                                if(audio_data_size>0) {
910
#ifdef DEBUG_AUDIO_FRAMES
911
                                        fprintf(stderr, "AUDIO: datasizeaudio:%d\n", audio_data_size);
912
#endif
913
                                        /* if a frame has been decoded, output it */
914
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
915
                                }
916
                                else {
917
                                        av_free_packet(&packet);
918
                                        continue;
919
                                }
920
        
921
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
922
                                if(audio_frame_size <= 0) {
923
                                        av_free_packet(&packet);
924
                                        continue;
925
                                }
926
                                
927
                                frame->number = contFrameAudio;
928

    
929
                                if(frame->number==0) {
930
                                        if(packet.dts==AV_NOPTS_VALUE) {
931
                                                av_free_packet(&packet);
932
                                                continue;
933
                                        }
934
                                        last_pkt_dts_audio = packet.dts;
935
                                        newTime = 0;
936
                                }
937
                                else {
938
                                        if(packet.dts!=AV_NOPTS_VALUE) {
939
                                                delta_audio = packet.dts-last_pkt_dts_audio;
940
                                                last_pkt_dts_audio = packet.dts;
941
                                        }
942
                                        else if(delta_audio==0) {
943
                                                av_free_packet(&packet);
944
                                                continue;
945
                                        }
946
                                }
947
#ifdef DEBUG_AUDIO_FRAMES
948
                                fprintf(stderr, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
949
#endif
950
                                //use pts if dts is invalid
951
                                if(packet.dts!=AV_NOPTS_VALUE)
952
                                        target_pts = packet.dts;
953
                                else if(packet.pts!=AV_NOPTS_VALUE) {
954
                                        target_pts = packet.pts;
955
                                } else  {
956
                                        av_free_packet(&packet);
957
                                        continue;
958
                                }
959

    
960
                                if(!offset_av)
961
                                {
962
                                        if(FirstTimeAudio && packet.dts>0) {
963
                                                ptsaudio1 = (double)packet.dts;
964
                                                FirstTimeAudio = 0;
965
#ifdef DEBUG_AUDIO_FRAMES
966
                                                fprintf(stderr, "AUDIO: SET PTS BASE OFFSET %f\n", ptsaudio1);
967
#endif
968
                                        }
969
                                }
970
                                else //we want to compensate audio and video offset for this source
971
                                {
972
                                        if(FirstTimeAudio && packet.dts>0) {
973
                                                //maintain the offset between audio pts and video pts
974
                                                //because in case of live source they have the same numbering
975
                                                if(ptsvideo1 > 0) //if we have already seen some video frames...
976
                                                        ptsaudio1 = ptsvideo1;
977
                                                else
978
                                                        ptsaudio1 = (double)packet.dts;
979
                                                FirstTimeAudio = 0;
980
#ifdef DEBUG_AUDIO_FRAMES
981
                                                fprintf(stderr, "AUDIO LIVE: SET PTS BASE OFFSET %f\n", ptsaudio1);
982
#endif
983
                                        }
984
                                }
985
                                //compute the new audio timestamps in milliseconds
986
                                if(frame->number>0) {
987
                                        newTime = (((double)target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio;
988
                                        // store timestamp in useconds for next frame sleep
989
                                        newTime_audio = newTime*1000;
990
                                }
991
#ifdef DEBUG_TIMESTAMPING
992
                                fprintf(stderr, "AUDIO: NEWTIMESTAMP %d\n", newTime);
993
#endif
994
                                if(newTime<0) {
995
#ifdef DEBUG_AUDIO_FRAMES
996
                                        fprintf(stderr, "AUDIO: SKIPPING FRAME\n");
997
#endif
998
                                        newtime_anomalies_counter++;
999
#ifdef DEBUG_ANOMALIES
1000
                                        fprintf(stderr, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d\n", newtime_anomalies_counter);
1001
#endif
1002
                                        av_free_packet(&packet);
1003
                                        continue; //SKIP THIS FRAME, bad timestamp
1004
                                }
1005

    
1006
                                frame->timestamp.tv_sec = (unsigned int)newTime/1000;
1007
                                frame->timestamp.tv_usec = newTime%1000;
1008
                                frame->size = audio_frame_size;
1009
                                frame->type = 5; // 5 is audio type
1010
#ifdef DEBUG_AUDIO_FRAMES
1011
                                fprintf(stderr, "AUDIO: pts %d duration %d timebase %d %d dts %d\n", (int)packet.pts, (int)packet.duration, pFormatCtx->streams[audioStream]->time_base.num, pFormatCtx->streams[audioStream]->time_base.den, (int)packet.dts);
1012
                                fprintf(stderr, "AUDIO: timestamp sec:%d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
1013
                                fprintf(stderr, "AUDIO: deltaaudio %lld\n", delta_audio);        
1014
#endif
1015
                                contFrameAudio++;
1016

    
1017
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1018
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1019
                                        exit(-1);
1020
                                }
1021
                                //set priority
1022
                                chunkaudio->priority = 1;
1023

    
1024
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1025
                                        // is chunk filled using current strategy?
1026
                                        //SAVE ON FILE
1027
                                        //saveChunkOnFile(chunkaudio);
1028
                                        //Send the chunk to an external transport/player
1029
                                        sendChunk(chunkaudio);
1030
#ifdef DEBUG_CHUNKER
1031
                                        fprintf(stderr, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1032
#endif
1033
                                        chunkaudio->seq = 0; //signal that we need an increase
1034
                                        //initChunk(chunkaudio, &seq_current_chunk);
1035
                                }
1036

    
1037
                                //we have an audio track, so we compute timings and determine
1038
                                //how much time we have to sleep at next audio frame taking
1039
                                //also into account how much time was needed to encode the
1040
                                //video frames
1041
                                //all this in case the video source is not live, i.e. not self-timing
1042
                                if(!live_source)
1043
                                {
1044
                                        if(newTime_prev != 0)
1045
                                        {
1046
                                                long long maxDelay = newTime_audio - newTime_prev;
1047

    
1048
                                                gettimeofday(&now_tv, NULL);
1049
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1050
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1051

    
1052
                                                if(usec > maxAudioInterval)
1053
                                                        maxAudioInterval = usec;
1054

    
1055
                                                lateTime -= (maxDelay - usec);
1056
#ifdef DEBUG_ANOMALIES
1057
                                                printf("\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1058
                                                printf("\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1059
#endif
1060

    
1061
                                                if((lateTime+maxAudioInterval) < 0)
1062
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1063
                                                else
1064
                                                        sleep = 0;
1065
                                        }
1066
                                        else
1067
                                                sleep = 0;
1068

    
1069
                                        newTime_prev = newTime_audio;
1070
                                        gettimeofday(&lastAudioSent, NULL);
1071
                                }
1072
                        }
1073
                }
1074
                else {
1075
#ifdef DEBUG_CHUNKER
1076
                        fprintf(stderr,"Free the packet that was allocated by av_read_frame\n");
1077
#endif
1078
                        av_free_packet(&packet);
1079
                }
1080
        }
1081
        
1082
        if(videotrace)
1083
                fclose(videotrace);
1084
        if(psnrtrace)
1085
                fclose(psnrtrace);
1086

    
1087
close:
1088
        if(chunk->seq != 0 && chunk->frames_num>0) {
1089
                //SAVE ON FILE
1090
                //saveChunkOnFile(chunk);
1091
                //Send the chunk to an external transport/player
1092
                sendChunk(chunk);
1093
#ifdef DEBUG_CHUNKER
1094
                fprintf(stderr, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1095
#endif
1096
                chunk->seq = 0; //signal that we need an increase just in case we will restart
1097
        }
1098
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1099
                //SAVE ON FILE     
1100
                //saveChunkOnFile(chunkaudio);
1101
                //Send the chunk via http to an external transport/player
1102
                sendChunk(chunkaudio);
1103
#ifdef DEBUG_CHUNKER
1104
                fprintf(stderr, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1105
#endif
1106
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1107
        }
1108

    
1109
#ifdef HTTPIO
1110
        /* finalize the HTTP chunk pusher */
1111
        finalizeChunkPusher();
1112
#elif TCPIO
1113
        finalizeTCPChunkPusher();
1114
#endif
1115

    
1116
        free(chunk);
1117
        free(chunkaudio);
1118
        free(frame);
1119
        av_free(video_outbuf);
1120
        av_free(scaledFrame_buffer);
1121
        av_free(audio_outbuf);
1122
        free(cmeta);
1123

    
1124
        // Free the YUV frame
1125
        av_free(pFrame);
1126
        av_free(scaledFrame);
1127
        av_free(samples);
1128
  
1129
        // Close the codec
1130
        if (!vcopy) avcodec_close(pCodecCtx);
1131
        if (!vcopy) avcodec_close(pCodecCtxEnc);
1132

    
1133
        if(audioStream!=-1) {
1134
                avcodec_close(aCodecCtx);
1135
                avcodec_close(aCodecCtxEnc);
1136
        }
1137
  
1138
        // Close the video file
1139
        av_close_input_file(pFormatCtx);
1140

    
1141
        if(LOOP_MODE) {
1142
                //we want video to continue, but the av_read_frame stopped
1143
                //lets wait a 5 secs, and cycle in again
1144
                usleep(5000000);
1145
#ifdef DEBUG_CHUNKER
1146
                fprintf(stderr, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
1147
#endif
1148
                videoStream = -1;
1149
                audioStream = -1;
1150
                FirstTimeAudio=1;
1151
                FirstTimeVideo=1;
1152
                pts_anomalies_counter=0;
1153
                newtime_anomalies_counter=0;
1154
                newTime=0;
1155
                newTime_audio=0;
1156
                newTime_prev=0;
1157
                ptsvideo1=0.0;
1158
                ptsaudio1=0.0;
1159
                last_pkt_dts=0;
1160
                delta_video=0;
1161
                delta_audio=0;
1162
                last_pkt_dts_audio=0;
1163
                target_pts=0;
1164
                i=0;
1165
                //~ contFrameVideo = 0;
1166
                //~ contFrameAudio = 1;
1167
                
1168
#ifdef YUV_RECORD_ENABLED
1169
                if(ChunkerStreamerTestMode)
1170
                {
1171
                        video_record_count++;
1172
                        //~ savedVideoFrames = 0;
1173
                        
1174
                        //~ char tmp_filename[255];
1175
                        //~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
1176
                        //~ FILE *pFile=fopen(tmp_filename, "w");
1177
                        //~ if(pFile!=NULL)
1178
                                //~ fclose(pFile);
1179
                }
1180
#endif
1181

    
1182
                goto restart;
1183
        }
1184

    
1185
        return 0;
1186
}
1187

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

    
1192
        //moving temp pointer to encode Frame on the wire
1193
        uint8_t *tempdata = NULL;
1194

    
1195
        if(chunk->seq == 0) {
1196
                initChunk(chunk, &seq_current_chunk);
1197
        }
1198
        //HINT on malloc
1199
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1200
        if(!chunk->data)  {
1201
                fprintf(stderr, "Memory error in chunk!!!\n");
1202
                return -1;
1203
        }
1204
        chunk->frames_num++; // number of frames in the current chunk
1205

    
1206
/*
1207
        //package the Frame header
1208
        tempdata = chunk->data+chunk->payload_len;
1209
        *((int32_t *)tempdata) = frame->number;
1210
        tempdata+=sizeof(int32_t);
1211
        *((struct timeval *)tempdata) = frame->timestamp;
1212
        tempdata+=sizeof(struct timeval);
1213
        *((int32_t *)tempdata) = frame->size;
1214
        tempdata+=sizeof(int32_t);
1215
        *((int32_t *)tempdata) = frame->type;
1216
        tempdata+=sizeof(int32_t);
1217
*/
1218
        //package the Frame header: network order and platform independent
1219
        tempdata = chunk->data+chunk->payload_len;
1220
        bit32_encoded_push(frame->number, tempdata);
1221
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1222
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1223
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1224
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1225

    
1226
         //insert the new frame data
1227
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1228
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1229
        //chunk lenght is updated just prior to pushing it out because
1230
        //the chunk header len is better calculated there
1231
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1232

    
1233
        //update timestamps
1234
        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) {
1235
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1236
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1237
        }
1238
        
1239
        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) {
1240
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1241
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1242
        }
1243
        return 0;
1244
}
1245

    
1246
void SaveFrame(AVFrame *pFrame, int width, int height)
1247
{
1248
        FILE *pFile;
1249
        int  y;
1250

    
1251
         // Open file
1252
        char tmp_filename[255];
1253
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1254
        pFile=fopen(tmp_filename, "ab");
1255
        if(pFile==NULL)
1256
                return;
1257

    
1258
        // Write header
1259
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1260
  
1261
        // Write Y data
1262
        for(y=0; y<height; y++)
1263
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1264
                {
1265
                        printf("errno = %d\n", errno);
1266
                        exit(1);
1267
                }
1268
        // Write U data
1269
        for(y=0; y<height/2; y++)
1270
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1271
                  {
1272
                        printf("errno = %d\n", errno);
1273
                        exit(1);
1274
                }
1275
        // Write V data
1276
        for(y=0; y<height/2; y++)
1277
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1278
                  {
1279
                        printf("errno = %d\n", errno);
1280
                        exit(1);
1281
                }
1282
  
1283
        // Close file
1284
        fclose(pFile);
1285
}
1286

    
1287
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1288
{
1289
        static FILE* pFile = NULL;
1290
        
1291
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1292
        fwrite(frame, sizeof(Frame), 1, pFile);
1293
        fwrite(video_outbuf, frame->size, 1, pFile);
1294
        fclose(pFile);
1295
}