Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ 8751781d

History | View | Annotate | Download (38.6 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 video_record_count = 0;
33
int savedVideoFrames = 0;
34
long int firstSavedVideoFrame = 0;
35
ChunkerStreamerTestMode = 0;
36

    
37
// Constant number of frames per chunk
38
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType)
39
{
40
#ifdef DEBUG_CHUNKER
41
        fprintf(stderr, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
42
#endif
43
        if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
44
                return 1;
45

    
46
        return 0;
47
}
48

    
49
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
50
// It can be considered as constant size.
51
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType)
52
{
53
#ifdef DEBUG_CHUNKER
54
        fprintf(stderr, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
55
#endif
56
        if(echunk->payload_len >= cmeta->targetChunkSize)
57
                return 1;
58
        
59
        return 0;
60
}
61

    
62
// Performace optimization.
63
// The chunkFilled function has been splitted into two functions (one for each strategy).
64
// Instead of continuously check the strategy flag (which is constant),
65
// 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)
66
int (*chunkFilled)(ExternalChunk *echunk, int chunkType);
67

    
68
void initChunk(ExternalChunk *chunk, int *seq_num) {
69
        chunk->seq = (*seq_num)++;
70
        chunk->frames_num = 0;
71
        chunk->payload_len = 0;
72
        chunk->len=0;
73
  if(chunk->data != NULL)
74
    free(chunk->data);
75
        chunk->data = NULL;
76
        chunk->start_time.tv_sec = -1;
77
        chunk->start_time.tv_usec = -1;
78
        chunk->end_time.tv_sec = -1;
79
        chunk->end_time.tv_usec = -1;
80
        chunk->priority = 0;
81
        chunk->category = 0;
82
        chunk->_refcnt = 0;
83
}
84

    
85
int quit = 0;
86

    
87
void sigproc()
88
{
89
        printf("you have pressed ctrl-c, terminating...\n");
90
        quit = 1;
91
}
92

    
93
static void print_usage(int argc, char *argv[])
94
{
95
  fprintf (stderr,
96
    "\nUsage:%s [options]\n"
97
    "\n"
98
    "Mandatory options:\n"
99
    "\t[-i input file]\n"
100
    "\t[-a audio bitrate]\n"
101
    "\t[-v video bitrate]\n\n"
102
    "Other options:\n"
103
    "\t[-A audioencoder]\n"
104
    "\t[-V videoencoder]\n"
105
    "\t[-s WxH]: force video size.\n"
106
    "\t[-l]: this is a live stream.\n"
107
    "\t[-o]: adjust av frames timestamps.\n"
108
    "\t[-t]: QoE test mode\n\n"
109
    "=======================================================\n", argv[0]
110
    );
111
  }
112

    
113
sendChunk(ExternalChunk *chunk) {
114
#ifdef HTTPIO
115
                                                pushChunkHttp(chunk, cmeta->outside_world_url);
116
#endif
117
#ifdef TCPIO
118
                                                pushChunkTcp(chunk);
119
#endif
120
#ifdef UDPIO
121
                                                pushChunkUDP(chunk);
122
#endif
123
}
124

    
125
int main(int argc, char *argv[]) {
126
        signal(SIGINT, sigproc);
127
        
128
        int i=0;
129

    
130
        //output variables
131
        uint8_t *video_outbuf = NULL;
132
        int video_outbuf_size, video_frame_size;
133
        uint8_t *audio_outbuf = NULL;
134
        int audio_outbuf_size, audio_frame_size;
135
        int audio_data_size;
136

    
137
        //numeric identifiers of input streams
138
        int videoStream = -1;
139
        int audioStream = -1;
140

    
141
        int len1;
142
        int frameFinished;
143
        //frame sequential counters
144
        int contFrameAudio=1, contFrameVideo=0;
145
        int numBytes;
146

    
147
        //command line parameters
148
        int audio_bitrate = -1;
149
        int video_bitrate = -1;
150
        char *audio_codec = "mp2";
151
        char *video_codec = "mpeg4";
152
        int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file)
153
        int offset_av = 0; //tells to compensate for offset between audio and video in the file
154
        
155
        //a raw buffer for decoded uncompressed audio samples
156
        int16_t *samples = NULL;
157
        //a raw uncompressed video picture
158
        AVFrame *pFrame = NULL;
159
        AVFrame *scaledFrame = NULL;
160

    
161
        AVFormatContext *pFormatCtx;
162
        AVCodecContext  *pCodecCtx,*pCodecCtxEnc,*aCodecCtxEnc,*aCodecCtx;
163
        AVCodec         *pCodec,*pCodecEnc,*aCodec,*aCodecEnc;
164
        AVPacket         packet;
165

    
166
        //stuff needed to compute the right timestamps
167
        short int FirstTimeAudio=1, FirstTimeVideo=1;
168
        short int pts_anomalies_counter=0;
169
        short int newtime_anomalies_counter=0;
170
        long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0;
171
        struct timeval lastAudioSent = {0, 0};
172
        double ptsvideo1=0.0;
173
        double ptsaudio1=0.0;
174
        int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0;
175

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

    
241
#ifdef YUV_RECORD_ENABLED
242
        if(ChunkerStreamerTestMode)
243
        {
244
                DELETE_DIR("yuv_data");
245
                CREATE_DIR("yuv_data");
246
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
247
                //fclose(pFile);
248
        }
249
#endif
250

    
251
restart:
252
        // read the configuration file
253
        cmeta = chunkerInit();
254
        switch(cmeta->strategy)
255
        {
256
                case 1:
257
                        chunkFilled = chunkFilledSizeStrategy;
258
                        break;
259
                default:
260
                        chunkFilled = chunkFilledFramesStrategy;
261
        }
262
                
263
        if(live_source)
264
                fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
265
        if(offset_av)
266
                fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
267

    
268
        // Register all formats and codecs
269
        av_register_all();
270

    
271
        // Open input file
272
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
273
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
274
                exit(-1);
275
        }
276

    
277
        // Retrieve stream information
278
        if(av_find_stream_info(pFormatCtx) < 0) {
279
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
280
                exit(-1);
281
        }
282

    
283
        // Dump information about file onto standard error
284
        dump_format(pFormatCtx, 0, av_input, 0);
285

    
286
        // Find the video and audio stream numbers
287
        for(i=0; i<pFormatCtx->nb_streams; i++) {
288
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
289
                        videoStream=i;
290
                }
291
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
292
                        audioStream=i;
293
                }
294
        }
295
        fprintf(stderr, "INIT: Num streams : %d TBR: %d %d RFRAMERATE:%d %d Duration:%d\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);
296

    
297
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
298
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
299

    
300
        if(videoStream==-1 && audioStream==-1) {
301
                fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
302
                exit(-1);
303
        }
304

    
305
        // Get a pointer to the codec context for the input video stream
306
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
307
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
308
        //extract W and H
309
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
310

    
311
        // Get a pointer to the codec context for the input audio stream
312
        if(audioStream != -1) {
313
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
314
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
315
        }
316

    
317
        //setup video output encoder
318
        pCodecEnc = avcodec_find_encoder_by_name(video_codec);
319
        if (pCodecEnc) {
320
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
321
        } else {
322
                fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
323
                return -1; // Codec not found
324
        }
325

    
326
        pCodecCtxEnc=avcodec_alloc_context();
327
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
328
        pCodecCtxEnc->codec_id = pCodecEnc->id;
329

    
330
        pCodecCtxEnc->bit_rate = video_bitrate;
331
        //~ pCodecCtxEnc->qmin = 30;
332
        //~ pCodecCtxEnc->qmax = 30;
333
        //times 20 follows the defaults, was not needed in previous versions of libavcodec
334
        pCodecCtxEnc->bit_rate_tolerance = video_bitrate*20;
335
//        pCodecCtxEnc->crf = 20.0f;
336
        // resolution must be a multiple of two 
337
        pCodecCtxEnc->width = (dest_width > 0) ? dest_width : pCodecCtx->width;
338
        pCodecCtxEnc->height = (dest_height > 0) ? dest_height : pCodecCtx->height;
339
        // frames per second 
340
        //~ pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
341
        //printf("pCodecCtx->time_base=%d/%d\n", pCodecCtx->time_base.num, pCodecCtx->time_base.den);
342
        pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
343
        pCodecCtxEnc->gop_size = 12; // emit one intra frame every twelve frames 
344
        pCodecCtxEnc->max_b_frames=1;
345
        pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P;
346
        pCodecCtxEnc->flags = CODEC_FLAG_PSNR;
347
        //~ pCodecCtxEnc->flags |= CODEC_FLAG_QSCALE;
348
  switch (pCodecEnc->id) {
349
    case CODEC_ID_H264 :
350
        pCodecCtxEnc->me_range=16;
351
        pCodecCtxEnc->max_qdiff=4;
352
        pCodecCtxEnc->qmin=1;
353
        pCodecCtxEnc->qmax=30;
354
        pCodecCtxEnc->qcompress=0.6;
355
        // frames per second 
356

    
357
//        pCodecCtxEnc->rc_min_rate = 0;
358
//        pCodecCtxEnc->rc_max_rate = 0;
359
//        pCodecCtxEnc->rc_buffer_size = 0;
360
//        pCodecCtxEnc->partitions = X264_PART_I4X4 | X264_PART_I8X8 | X264_PART_P8X8 | X264_PART_P4X4 | X264_PART_B8X8;
361
//        pCodecCtxEnc->crf = 0.0f;
362
        
363
#ifdef STREAMER_X264_USE_SSIM
364
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
365
#endif
366

    
367
        pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
368
        // pCodecCtxEnc->rc_min_rate = 0;
369
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
370
        // pCodecCtxEnc->rc_buffer_size = 0;
371
        break;
372
    case CODEC_ID_MPEG4 :
373
        break;
374
    default:
375
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
376
  }
377

    
378
        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);
379

    
380
        if(pCodec==NULL) {
381
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
382
                return -1; // Codec not found
383
        }
384
        if(pCodecEnc==NULL) {
385
                fprintf(stderr, "INIT: Unsupported OUT VIDEO pcodecenc!\n");
386
                return -1; // Codec not found
387
        }
388
        if(avcodec_open(pCodecCtx, pCodec)<0) {
389
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
390
                return -1; // Could not open codec
391
        }
392
        if(avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
393
                fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
394
                return -1; // Could not open codec
395
        }
396

    
397
        if(audioStream!=-1) {
398
                //setup audio output encoder
399
                aCodecCtxEnc = avcodec_alloc_context();
400
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
401
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
402
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
403
                aCodecCtxEnc->channels = aCodecCtx->channels;
404
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
405

    
406
                // Find the decoder for the audio stream
407
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
408
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
409
                if(aCodec==NULL) {
410
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
411
                        return -1;
412
                }
413
                if(aCodecEnc==NULL) {
414
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
415
                        return -1;
416
                }
417
        
418
                if(avcodec_open(aCodecCtx, aCodec)<0) {
419
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
420
                        return -1; // Could not open codec
421
                }
422
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
423
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
424
                        return -1; // Could not open codec
425
                }
426
        }
427
        else {
428
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
429
        }
430

    
431
        // Allocate audio in and out buffers
432
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
433
        if(samples == NULL) {
434
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
435
                return -1;
436
        }
437
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
438
        audio_outbuf = av_malloc(audio_outbuf_size);
439
        if(audio_outbuf == NULL) {
440
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
441
                return -1;
442
        }
443

    
444
        // Allocate video in frame and out buffer
445
        pFrame=avcodec_alloc_frame();
446
        scaledFrame=avcodec_alloc_frame();
447
        if(pFrame==NULL || scaledFrame == NULL) {
448
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
449
                return -1;
450
        }
451
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
452
        video_outbuf = av_malloc(video_outbuf_size);
453
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height);
454
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
455
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height);
456
        if(!video_outbuf || !scaledFrame_buffer) {
457
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
458
                return -1;
459
        }
460

    
461
        //allocate Napa-Wine transport
462
        frame = (Frame *)malloc(sizeof(Frame));
463
        if(!frame) {
464
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
465
                return -1;
466
        }
467
        //create an empty first video chunk
468
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
469
        if(!chunk) {
470
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
471
                return -1;
472
        }
473
        chunk->data = NULL;
474
        chunk->seq = 0;
475
        //initChunk(chunk, &seq_current_chunk); if i init them now i get out of sequence
476
#ifdef DEBUG_CHUNKER
477
        fprintf(stderr, "INIT: chunk video %d\n", chunk->seq);
478
#endif
479
        //create empty first audio chunk
480
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
481
        if(!chunkaudio) {
482
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
483
                return -1;
484
        }
485
  chunkaudio->data=NULL;
486
        chunkaudio->seq = 0;
487
        //initChunk(chunkaudio, &seq_current_chunk);
488
#ifdef DEBUG_CHUNKER
489
        fprintf(stderr, "INIT: chunk audio %d\n", chunkaudio->seq);
490
#endif
491

    
492
#ifdef HTTPIO
493
        /* initialize the HTTP chunk pusher */
494
        initChunkPusher(); //TRIPLO
495
#endif
496

    
497
        long sleep=0;
498
        struct timeval now_tv;
499
        struct timeval tmp_tv;
500
        long long lateTime = 0;
501
        long long maxAudioInterval = 0;
502
        long long maxVDecodeTime = 0;
503
        unsigned char lastIFrameDistance = 0;
504

    
505
#ifdef TCPIO
506
        static char peer_ip[16];
507
        static int peer_port;
508
        int res = sscanf(cmeta->outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
509
        if (res < 2) {
510
                fprintf(stderr,"error parsing output url: %s\n", cmeta->outside_world_url);
511
                return -2;
512
        }
513
        
514
        initTCPPush(peer_ip, peer_port);
515
#endif
516
#ifdef UDPIO
517
        static char peer_ip[16];
518
        static int peer_port;
519
        int res = sscanf(cmeta->outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
520
        if (res < 2) {
521
                fprintf(stderr,"error parsing output url: %s\n", cmeta->outside_world_url);
522
                return -2;
523
        }
524
        
525
        initUDPPush(peer_ip, peer_port);
526
#endif
527
        
528
        char videotrace_filename[255];
529
        char psnr_filename[255];
530
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
531
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
532
        FILE* videotrace = fopen(videotrace_filename, "w");
533
        FILE* psnrtrace = fopen(psnr_filename, "w");
534

    
535
        //main loop to read from the input file
536
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
537
        {
538
                //detect if a strange number of anomalies is occurring
539
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
540
                        pts_anomalies_counter++;
541
#ifdef DEBUG_ANOMALIES
542
                        fprintf(stderr, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
543
#endif
544
                        if(live_source) { //reset just in case of live source
545
                                if(pts_anomalies_counter > 25) { //just a random threshold
546
                                        pts_anomalies_counter = 0;
547
                                        FirstTimeVideo = 1;
548
                                        FirstTimeAudio = 1;
549
#ifdef DEBUG_ANOMALIES
550
                                        fprintf(stderr, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
551
#endif
552
                                }
553
                        }
554
                }
555

    
556
                //newTime_video and _audio are in usec
557
                //if video and audio stamps differ more than 5sec
558
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
559
                        newtime_anomalies_counter++;
560
#ifdef DEBUG_ANOMALIES
561
                        fprintf(stderr, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
562
#endif
563
                }
564

    
565
                if(newtime_anomalies_counter > 50) { //just a random threshold
566
                        if(live_source) { //restart just in case of live source
567
#ifdef DEBUG_ANOMALIES
568
                                fprintf(stderr, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
569
#endif
570
                                goto close;
571
                        }
572
                }
573

    
574
                // Is this a packet from the video stream?
575
                if(packet.stream_index==videoStream)
576
                {
577
                        if(!live_source)
578
                        {
579
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
580
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
581
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
582
                                        // therefore, it's better to skip the frame
583
                                        if((lateTime+maxVDecodeTime) >= 0)
584
                                        {
585
#ifdef DEBUG_ANOMALIES
586
                                                fprintf(stderr, "\n\n\t\t************************* SKIPPING VIDEO FRAME ***********************************\n\n", sleep);
587
#endif
588
                                                continue;
589
                                        }
590
                                }
591
                        }
592
                        
593
                        gettimeofday(&tmp_tv, NULL);
594
                        
595
                        //decode the video packet into a raw pFrame
596
                        if(avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet)>0)
597
                        {
598
                                // usleep(5000);
599
#ifdef DEBUG_VIDEO_FRAMES
600
                                fprintf(stderr, "\n-------VIDEO FRAME type %d\n", pFrame->pict_type);
601
                                fprintf(stderr, "VIDEO: dts %lld pts %lld\n", packet.dts, packet.pts);
602
#endif
603
                                if(frameFinished)
604
                                { // it must be true all the time else error
605
                                
606
                                        frame->number = ++contFrameVideo;
607

    
608
#ifdef VIDEO_DEINTERLACE
609
                                        avpicture_deinterlace(
610
                                                (AVPicture*) pFrame,
611
                                                (const AVPicture*) pFrame,
612
                                                pCodecCtxEnc->pix_fmt,
613
                                                pCodecCtxEnc->width,
614
                                                pCodecCtxEnc->height);
615
#endif
616

    
617
#ifdef DEBUG_VIDEO_FRAMES
618
                                        fprintf(stderr, "VIDEO: finished frame %d dts %lld pts %lld\n", frame->number, packet.dts, packet.pts);
619
#endif
620
                                        if(frame->number==0) {
621
                                                if(packet.dts==AV_NOPTS_VALUE)
622
                                                {
623
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
624
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
625
                                                        continue;
626
                                                }
627
                                                last_pkt_dts = packet.dts;
628
                                                newTime = 0;
629
                                        }
630
                                        else {
631
                                                if(packet.dts!=AV_NOPTS_VALUE) {
632
                                                        delta_video = packet.dts-last_pkt_dts;
633
                                                        last_pkt_dts = packet.dts;
634
                                                }
635
                                                else if(delta_video==0)
636
                                                {
637
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
638
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
639
                                                        continue;
640
                                                }
641
                                        }
642
#ifdef DEBUG_VIDEO_FRAMES
643
                                        fprintf(stderr, "VIDEO: deltavideo : %d\n", (int)delta_video);
644
#endif
645

    
646
                                        if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
647
                                        {
648
                                                static AVPicture pict;
649
                                                static struct SwsContext *img_convert_ctx = NULL;
650
                                                
651
                                                if(img_convert_ctx == NULL)
652
                                                {
653
                                                        img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
654
                                                        if(img_convert_ctx == NULL) {
655
                                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
656
                                                                exit(1);
657
                                                        }
658
                                                }
659
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
660
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
661
                                        }
662
                                        else
663
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
664
                                        
665
                                        if(video_frame_size <= 0)
666
                                        {
667
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
668
                                                continue;
669
                                        }
670

    
671
#ifdef DEBUG_VIDEO_FRAMES
672
                                        if(pCodecCtxEnc->coded_frame) {
673
                                                fprintf(stderr, "\n-------VIDEO FRAME intype %d%s -> outtype: %d%s\n",
674
                                                        pFrame->pict_type, pFrame->key_frame ? " (key)" : "",
675
                                                        pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
676
                                        }
677
#endif
678

    
679
                                        //use pts if dts is invalid
680
                                        if(packet.dts!=AV_NOPTS_VALUE)
681
                                                target_pts = packet.dts;
682
                                        else if(packet.pts!=AV_NOPTS_VALUE)
683
                                                target_pts = packet.pts;
684
                                        else
685
                                        {
686
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
687
                                                continue;
688
                                        }
689

    
690
                                        if(!offset_av)
691
                                        {
692
                                                if(FirstTimeVideo && packet.dts>0) {
693
                                                        ptsvideo1 = (double)packet.dts;
694
                                                        FirstTimeVideo = 0;
695
#ifdef DEBUG_VIDEO_FRAMES
696
                                                        fprintf(stderr, "VIDEO: SET PTS BASE OFFSET %f\n", ptsvideo1);
697
#endif
698
                                                }
699
                                        }
700
                                        else //we want to compensate audio and video offset for this source
701
                                        {
702
                                                if(FirstTimeVideo && packet.dts>0) {
703
                                                        //maintain the offset between audio pts and video pts
704
                                                        //because in case of live source they have the same numbering
705
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
706
                                                                ptsvideo1 = ptsaudio1;
707
                                                        else
708
                                                                ptsvideo1 = (double)packet.dts;
709
                                                        FirstTimeVideo = 0;
710
#ifdef DEBUG_VIDEO_FRAMES
711
                                                        fprintf(stderr, "VIDEO LIVE: SET PTS BASE OFFSET %f\n", ptsvideo1);
712
#endif
713
                                                }
714
                                        }
715
                                        //compute the new video timestamp in milliseconds
716
                                        if(frame->number>0) {
717
                                                newTime = ((double)target_pts-ptsvideo1)*1000.0/((double)delta_video*(double)av_q2d(pFormatCtx->streams[videoStream]->r_frame_rate));
718
                                                // store timestamp in useconds for next frame sleep
719
                                                newTime_video = newTime*1000;
720
                                        }
721
#ifdef DEBUG_TIMESTAMPING
722
                                        fprintf(stderr, "VIDEO: NEWTIMESTAMP %ld\n", newTime);
723
#endif
724
                                        if(newTime<0) {
725
#ifdef DEBUG_VIDEO_FRAMES
726
                                                fprintf(stderr, "VIDEO: SKIPPING FRAME\n");
727
#endif
728
                                                newtime_anomalies_counter++;
729
#ifdef DEBUG_ANOMALIES
730
                                                fprintf(stderr, "READLOOP: NEWTIME negative video timestamp anomaly detected number %d\n", newtime_anomalies_counter);
731
#endif
732
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
733
                                                continue; //SKIP THIS FRAME, bad timestamp
734
                                        }
735
                                        
736
                                        //~ printf("pCodecCtxEnc->error[0]=%lld\n", pFrame->error[0]);
737
        
738
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
739
                                        frame->timestamp.tv_usec = newTime%1000;
740
                                        frame->size = video_frame_size;
741
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
742
                                        frame->type = (unsigned char)pCodecCtxEnc->coded_frame->pict_type;
743

    
744
#ifdef DEBUG_VIDEO_FRAMES
745
                                        fprintf(stderr, "VIDEO: original codec frame number %d vs. encoded %d vs. packed %d\n", pCodecCtx->frame_number, pCodecCtxEnc->frame_number, frame->number);
746
                                        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);
747
#endif
748

    
749
#ifdef YUV_RECORD_ENABLED
750
                                        if(ChunkerStreamerTestMode)
751
                                        {
752
                                                if(videotrace)
753
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pFrame->pict_type, frame->size);
754

    
755
                                                if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
756
                                                        SaveFrame(scaledFrame, pCodecCtxEnc->width, pCodecCtxEnc->height);
757
                                                else
758
                                                        SaveFrame(pFrame, pCodecCtxEnc->width, pCodecCtxEnc->height);
759

    
760
                                                ++savedVideoFrames;
761
                                                SaveEncodedFrame(frame, video_outbuf);
762

    
763
                                                if(!firstSavedVideoFrame)
764
                                                        firstSavedVideoFrame = frame->number;
765
                                                
766
                                                char tmp_filename[255];
767
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
768
                                                FILE* tmp = fopen(tmp_filename, "w");
769
                                                if(tmp)
770
                                                {
771
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %d\nlast_frame_number = %d\n"
772
                                                                ,pCodecCtxEnc->width, pCodecCtxEnc->height
773
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
774
                                                        fclose(tmp);
775
                                                }
776
                                        }
777
#endif
778

    
779
#ifdef DEBUG_VIDEO_FRAMES
780
                                        fprintf(stderr, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
781
                                        fprintf(stderr, "VIDEO: timestamped sec %d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
782
#endif
783
                                        //contFrameVideo++; //lets increase the numbering of the frames
784

    
785
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
786
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
787
                                                exit(-1);
788
                                        }
789

    
790
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
791
                                                //SAVE ON FILE
792
                                                //saveChunkOnFile(chunk);
793
                                                //Send the chunk to an external transport/player
794
                                                sendChunk(chunk);
795
#ifdef DEBUG_CHUNKER
796
                                                fprintf(stderr, "VIDEO: sent chunk video %d\n", chunk->seq);
797
#endif
798
                                                chunk->seq = 0; //signal that we need an increase
799
                                                //initChunk(chunk, &seq_current_chunk);
800
                                        }
801

    
802
                                        //compute how long it took to encode video frame
803
                                        gettimeofday(&now_tv, NULL);
804
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
805
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
806
                                        if(usec > maxVDecodeTime)
807
                                                maxVDecodeTime = usec;
808

    
809
                                        //we DONT have an audio track, so we compute timings and determine
810
                                        //how much time we have to sleep at next VIDEO frame taking
811
                                        //also into account how much time was needed to encode the current
812
                                        //video frame
813
                                        //all this in case the video source is not live, i.e. not self-timing
814
                                        //and only in case there is no audio track
815
                                        if(audioStream == -1) {
816
                                                if(!live_source) {
817
                                                        if(newTime_prev != 0) {
818
                                                                //how much delay between video frames ideally
819
                                                                long long maxDelay = newTime_video - newTime_prev;
820
                                                                sleep = (maxDelay - usec);
821
#ifdef DEBUG_ANOMALIES
822
                                                                printf("\tmaxDelay=%ld\n", ((long)maxDelay));
823
                                                                printf("\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
824
#endif
825
                                                        }
826
                                                        else
827
                                                                sleep = 0;
828

    
829
                                                        //update and store counters
830
                                                        newTime_prev = newTime_video;
831

    
832
                                                        //i can also sleep now instead of at the beginning of
833
                                                        //the next frame because in this case we only have video
834
                                                        //frames, hence it would immediately be the next thing to do
835
                                                        if(sleep > 0) {
836
#ifdef DEBUG_ANOMALIES
837
                                                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
838
#endif
839
                                                                usleep(sleep);
840
                                                        }
841

    
842
                                                }
843
                                        }
844

    
845
                                }
846
                        }
847
                }
848
                else if(packet.stream_index==audioStream)
849
                {
850
                        if(sleep > 0)
851
                        {
852
#ifdef DEBUG_ANOMALIES
853
                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
854
#endif
855
                                usleep(sleep);
856
                        }
857
                        
858
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
859
                        //decode the audio packet into a raw audio source buffer
860
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
861
                        {
862
#ifdef DEBUG_AUDIO_FRAMES
863
                                fprintf(stderr, "\n-------AUDIO FRAME\n");
864
                                fprintf(stderr, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
865
#endif
866
                                if(audio_data_size>0) {
867
#ifdef DEBUG_AUDIO_FRAMES
868
                                        fprintf(stderr, "AUDIO: datasizeaudio:%d\n", audio_data_size);
869
#endif
870
                                        /* if a frame has been decoded, output it */
871
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
872
                                }
873
                                else
874
                                        continue;
875
        
876
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
877
                                if(audio_frame_size <= 0)
878
                                        continue;
879
                                
880
                                frame->number = contFrameAudio;
881

    
882
                                if(frame->number==0) {
883
                                        if(packet.dts==AV_NOPTS_VALUE)
884
                                                continue;
885
                                        last_pkt_dts_audio = packet.dts;
886
                                        newTime = 0;
887
                                }
888
                                else {
889
                                        if(packet.dts!=AV_NOPTS_VALUE) {
890
                                                delta_audio = packet.dts-last_pkt_dts_audio;
891
                                                last_pkt_dts_audio = packet.dts;
892
                                        }
893
                                        else if(delta_audio==0)
894
                                                continue;
895
                                }
896
#ifdef DEBUG_AUDIO_FRAMES
897
                                fprintf(stderr, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
898
#endif
899
                                //use pts if dts is invalid
900
                                if(packet.dts!=AV_NOPTS_VALUE)
901
                                        target_pts = packet.dts;
902
                                else if(packet.pts!=AV_NOPTS_VALUE)
903
                                        target_pts = packet.pts;
904
                                else
905
                                        continue;
906

    
907
                                if(!offset_av)
908
                                {
909
                                        if(FirstTimeAudio && packet.dts>0) {
910
                                                ptsaudio1 = (double)packet.dts;
911
                                                FirstTimeAudio = 0;
912
#ifdef DEBUG_AUDIO_FRAMES
913
                                                fprintf(stderr, "AUDIO: SET PTS BASE OFFSET %f\n", ptsaudio1);
914
#endif
915
                                        }
916
                                }
917
                                else //we want to compensate audio and video offset for this source
918
                                {
919
                                        if(FirstTimeAudio && packet.dts>0) {
920
                                                //maintain the offset between audio pts and video pts
921
                                                //because in case of live source they have the same numbering
922
                                                if(ptsvideo1 > 0) //if we have already seen some video frames...
923
                                                        ptsaudio1 = ptsvideo1;
924
                                                else
925
                                                        ptsaudio1 = (double)packet.dts;
926
                                                FirstTimeAudio = 0;
927
#ifdef DEBUG_AUDIO_FRAMES
928
                                                fprintf(stderr, "AUDIO LIVE: SET PTS BASE OFFSET %f\n", ptsaudio1);
929
#endif
930
                                        }
931
                                }
932
                                //compute the new audio timestamps in milliseconds
933
                                if(frame->number>0) {
934
                                        newTime = (((double)target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio;
935
                                        // store timestamp in useconds for next frame sleep
936
                                        newTime_audio = newTime*1000;
937
                                }
938
#ifdef DEBUG_TIMESTAMPING
939
                                fprintf(stderr, "AUDIO: NEWTIMESTAMP %d\n", newTime);
940
#endif
941
                                if(newTime<0) {
942
#ifdef DEBUG_AUDIO_FRAMES
943
                                        fprintf(stderr, "AUDIO: SKIPPING FRAME\n");
944
#endif
945
                                        newtime_anomalies_counter++;
946
#ifdef DEBUG_ANOMALIES
947
                                        fprintf(stderr, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d\n", newtime_anomalies_counter);
948
#endif
949
                                        continue; //SKIP THIS FRAME, bad timestamp
950
                                }
951

    
952
                                frame->timestamp.tv_sec = (unsigned int)newTime/1000;
953
                                frame->timestamp.tv_usec = newTime%1000;
954
                                frame->size = audio_frame_size;
955
                                frame->type = 5; // 5 is audio type
956
#ifdef DEBUG_AUDIO_FRAMES
957
                                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);
958
                                fprintf(stderr, "AUDIO: timestamp sec:%d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
959
                                fprintf(stderr, "AUDIO: deltaaudio %lld\n", delta_audio);        
960
#endif
961
                                contFrameAudio++;
962

    
963
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
964
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
965
                                        exit(-1);
966
                                }
967
                                //set priority
968
                                chunkaudio->priority = 1;
969

    
970
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
971
                                        // is chunk filled using current strategy?
972
                                        //SAVE ON FILE
973
                                        //saveChunkOnFile(chunkaudio);
974
                                        //Send the chunk to an external transport/player
975
                                        sendChunk(chunkaudio);
976
#ifdef DEBUG_CHUNKER
977
                                        fprintf(stderr, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
978
#endif
979
                                        chunkaudio->seq = 0; //signal that we need an increase
980
                                        //initChunk(chunkaudio, &seq_current_chunk);
981
                                }
982

    
983
                                //we have an audio track, so we compute timings and determine
984
                                //how much time we have to sleep at next audio frame taking
985
                                //also into account how much time was needed to encode the
986
                                //video frames
987
                                //all this in case the video source is not live, i.e. not self-timing
988
                                if(!live_source)
989
                                {
990
                                        if(newTime_prev != 0)
991
                                        {
992
                                                long long maxDelay = newTime_audio - newTime_prev;
993

    
994
                                                gettimeofday(&now_tv, NULL);
995
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
996
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
997

    
998
                                                if(usec > maxAudioInterval)
999
                                                        maxAudioInterval = usec;
1000

    
1001
                                                lateTime -= (maxDelay - usec);
1002
#ifdef DEBUG_ANOMALIES
1003
                                                printf("\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1004
                                                printf("\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1005
#endif
1006

    
1007
                                                if((lateTime+maxAudioInterval) < 0)
1008
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1009
                                                else
1010
                                                        sleep = 0;
1011
                                        }
1012
                                        else
1013
                                                sleep = 0;
1014

    
1015
                                        newTime_prev = newTime_audio;
1016
                                        gettimeofday(&lastAudioSent, NULL);
1017
                                }
1018
                        }
1019
                }
1020
                else {
1021
#ifdef DEBUG_CHUNKER
1022
                        fprintf(stderr,"Free the packet that was allocated by av_read_frame\n");
1023
#endif
1024
                        av_free_packet(&packet);
1025
                }
1026
        }
1027
        
1028
        if(videotrace)
1029
                fclose(videotrace);
1030
        if(psnrtrace)
1031
                fclose(psnrtrace);
1032

    
1033
close:
1034
        if(chunk->seq != 0 && chunk->frames_num>0) {
1035
                //SAVE ON FILE
1036
                //saveChunkOnFile(chunk);
1037
                //Send the chunk to an external transport/player
1038
                sendChunk(chunk);
1039
#ifdef DEBUG_CHUNKER
1040
                fprintf(stderr, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1041
#endif
1042
                chunk->seq = 0; //signal that we need an increase just in case we will restart
1043
        }
1044
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1045
                //SAVE ON FILE     
1046
                //saveChunkOnFile(chunkaudio);
1047
                //Send the chunk via http to an external transport/player
1048
                sendChunk(chunkaudio);
1049
#ifdef DEBUG_CHUNKER
1050
                fprintf(stderr, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1051
#endif
1052
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1053
        }
1054

    
1055
#ifdef HTTPIO
1056
        /* finalize the HTTP chunk pusher */
1057
        finalizeChunkPusher();
1058
#elif TCPIO
1059
        finalizeTCPChunkPusher();
1060
#endif
1061

    
1062
        free(chunk);
1063
        free(chunkaudio);
1064
        free(frame);
1065
        av_free(video_outbuf);
1066
        av_free(scaledFrame_buffer);
1067
        av_free(audio_outbuf);
1068
        free(cmeta);
1069

    
1070
        // Free the YUV frame
1071
        av_free(pFrame);
1072
        av_free(scaledFrame);
1073
        av_free(samples);
1074
  
1075
        // Close the codec
1076
        avcodec_close(pCodecCtx);
1077
        avcodec_close(pCodecCtxEnc);
1078

    
1079
        if(audioStream!=-1) {
1080
                avcodec_close(aCodecCtx);
1081
                avcodec_close(aCodecCtxEnc);
1082
        }
1083
  
1084
        // Close the video file
1085
        av_close_input_file(pFormatCtx);
1086

    
1087
        if(LOOP_MODE) {
1088
                //we want video to continue, but the av_read_frame stopped
1089
                //lets wait a 5 secs, and cycle in again
1090
                usleep(5000000);
1091
#ifdef DEBUG_CHUNKER
1092
                fprintf(stderr, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
1093
#endif
1094
                videoStream = -1;
1095
                audioStream = -1;
1096
                FirstTimeAudio=1;
1097
                FirstTimeVideo=1;
1098
                pts_anomalies_counter=0;
1099
                newtime_anomalies_counter=0;
1100
                newTime=0;
1101
                newTime_audio=0;
1102
                newTime_prev=0;
1103
                ptsvideo1=0.0;
1104
                ptsaudio1=0.0;
1105
                last_pkt_dts=0;
1106
                delta_video=0;
1107
                delta_audio=0;
1108
                last_pkt_dts_audio=0;
1109
                target_pts=0;
1110
                i=0;
1111
                //~ contFrameVideo = 0;
1112
                //~ contFrameAudio = 1;
1113
                
1114
#ifdef YUV_RECORD_ENABLED
1115
                if(ChunkerStreamerTestMode)
1116
                {
1117
                        video_record_count++;
1118
                        //~ savedVideoFrames = 0;
1119
                        
1120
                        //~ char tmp_filename[255];
1121
                        //~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
1122
                        //~ FILE *pFile=fopen(tmp_filename, "w");
1123
                        //~ if(pFile!=NULL)
1124
                                //~ fclose(pFile);
1125
                }
1126
#endif
1127

    
1128
                goto restart;
1129
        }
1130

    
1131
        return 0;
1132
}
1133

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

    
1138
        //moving temp pointer to encode Frame on the wire
1139
        uint8_t *tempdata = NULL;
1140

    
1141
        if(chunk->seq == 0) {
1142
                initChunk(chunk, &seq_current_chunk);
1143
        }
1144
        //HINT on malloc
1145
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1146
        if(!chunk->data)  {
1147
                fprintf(stderr, "Memory error in chunk!!!\n");
1148
                return -1;
1149
        }
1150
        chunk->frames_num++; // number of frames in the current chunk
1151

    
1152
/*
1153
        //package the Frame header
1154
        tempdata = chunk->data+chunk->payload_len;
1155
        *((int32_t *)tempdata) = frame->number;
1156
        tempdata+=sizeof(int32_t);
1157
        *((struct timeval *)tempdata) = frame->timestamp;
1158
        tempdata+=sizeof(struct timeval);
1159
        *((int32_t *)tempdata) = frame->size;
1160
        tempdata+=sizeof(int32_t);
1161
        *((int32_t *)tempdata) = frame->type;
1162
        tempdata+=sizeof(int32_t);
1163
*/
1164
        //package the Frame header: network order and platform independent
1165
        tempdata = chunk->data+chunk->payload_len;
1166
        bit32_encoded_push(frame->number, tempdata);
1167
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1168
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1169
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1170
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1171

    
1172
         //insert the new frame data
1173
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1174
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1175
        //chunk lenght is updated just prior to pushing it out because
1176
        //the chunk header len is better calculated there
1177
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1178

    
1179
        //update timestamps
1180
        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) {
1181
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1182
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1183
        }
1184
        
1185
        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) {
1186
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1187
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1188
        }
1189
        return 0;
1190
}
1191

    
1192
void SaveFrame(AVFrame *pFrame, int width, int height)
1193
{
1194
        FILE *pFile;
1195
        int  y;
1196

    
1197
         // Open file
1198
        char tmp_filename[255];
1199
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1200
        pFile=fopen(tmp_filename, "ab");
1201
        if(pFile==NULL)
1202
                return;
1203

    
1204
        // Write header
1205
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1206
  
1207
        // Write Y data
1208
        for(y=0; y<height; y++)
1209
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1210
                {
1211
                        printf("errno = %d\n", errno);
1212
                        exit(1);
1213
                }
1214
        // Write U data
1215
        for(y=0; y<height/2; y++)
1216
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1217
                  {
1218
                        printf("errno = %d\n", errno);
1219
                        exit(1);
1220
                }
1221
        // Write V data
1222
        for(y=0; y<height/2; y++)
1223
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1224
                  {
1225
                        printf("errno = %d\n", errno);
1226
                        exit(1);
1227
                }
1228
  
1229
        // Close file
1230
        fclose(pFile);
1231
}
1232

    
1233
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1234
{
1235
        static FILE* pFile = NULL;
1236
        
1237
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1238
        fwrite(frame, sizeof(Frame), 1, pFile);
1239
        fwrite(video_outbuf, frame->size, 1, pFile);
1240
        fclose(pFile);
1241
}