Statistics
| Branch: | Revision:

chunker-player / chunker_streamer.c @ 8de6681e

History | View | Annotate | Download (20.3 KB)

1
// ingestion.c
2
// Author 
3
// Diego Reforgiato
4
// Giuseppe Tropea
5
//
6
// Use the file compile to compile the program to build (assuming libavformat and libavcodec are 
7
// correctly installed your system).
8
//
9
// Run using
10
//
11
// ingestion myvideofile.mpg
12

    
13
#include <libavcodec/avcodec.h>
14
#include <libavformat/avformat.h>
15

    
16
#include <stdio.h>
17

    
18
#include <SDL.h>
19
#include <SDL_thread.h>
20

    
21
#include "chunker_streamer.h"
22

    
23
#ifdef __MINGW32__
24
#undef main /* Prevents SDL from overriding main() */
25
#endif
26

    
27
#define SDL_AUDIO_BUFFER_SIZE 1024
28

    
29
int alphasortNew(const struct dirent **a, const struct dirent **b) {
30
        int idx1 = atoi((*a)->d_name+5);
31
        int idx2 = atoi((*b)->d_name+5);
32
        return (idx2<idx1);
33
//        return (strcmp((*a)->d_name,(*b)->d_name));
34
}
35

    
36
int chunkFilled(ExternalChunk *echunk, ChunkerMetadata *cmeta) {
37
        // different strategies to implement
38
        if(cmeta->strategy==0) // number of frames per chunk constant
39
                if(echunk->frames_num==cmeta->val_strategy)
40
                        return 1;
41
        
42
        if(cmeta->strategy==1) // constant size. Note that for now each chunk will have a size just greater or equal than the required value - It can be considered as constant size. If that is not good we need to change the code. Also, to prevent too low values of strategy_val. This choice is more robust
43
                if(echunk->payload_len>=cmeta->val_strategy)
44
                        return 1;
45
        
46
        return 0;
47
        
48
}
49

    
50
void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame) {
51
        FILE *pFile;
52
        char szFilename[32];
53
        int  y;
54
  
55
  // Open file
56
        sprintf(szFilename, "frame%d.ppm", iFrame);
57

    
58
          pFile=fopen(szFilename, "wb");
59
          if(pFile==NULL)
60
                    return;
61
  
62
  // Write header
63
        fprintf(pFile, "P5\n%d %d\n255\n", width, height);
64
  
65
  // Write pixel data
66
          for(y=0; y<height; y++)
67
                    fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile);
68
  
69
  // Close file
70
          fclose(pFile);
71
}
72

    
73
void saveChunkOnFile(ExternalChunk *chunk) {
74
        char buf[1024], outfile[1024];
75
/*        FILE *fp;
76
        
77
        strcpy(buf,"chunks//CHUNK");
78
        strcat(buf,"\0");
79
        sprintf(outfile,"%s%d",buf,chunk->seq);
80
        fp = fopen(outfile,"wb");
81
        fwrite(&(chunk->seq),sizeof(int),1,fp);
82
        fwrite(&(chunk->frames_num),sizeof(int),1,fp);
83
        fwrite(&(chunk->start_time),sizeof(struct timeval),1,fp);
84
        fwrite(&(chunk->end_time),sizeof(struct timeval),1,fp);
85
        fwrite(&(chunk->payload_len),sizeof(int),1,fp);
86
        fwrite(&(chunk->len),sizeof(int),1,fp);
87
        fwrite(&(chunk->category),sizeof(int),1,fp);
88
        fwrite(&(chunk->priority),sizeof(double),1,fp);
89
        fwrite(&(chunk->_refcnt),sizeof(int),1,fp);
90
        fwrite(chunk->data,sizeof(uint8_t),sizeof(uint8_t)*chunk->payload_len,fp);
91
        fclose(fp);
92
*/
93
        /* send the chunk to the GRAPES peer application via HTTP */
94
        sprintf(buf, "%slocalhost:%d%s", UL_HTTP_PREFIX, UL_DEFAULT_CHUNKBUFFER_PORT, UL_DEFAULT_CHUNKBUFFER_PATH);
95
        pushChunkHttp(chunk, buf);
96
}
97

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

    
113
int main(int argc, char *argv[]) {
114
        int i, videoStream,outbuf_size,out_size,seq_current_chunk = 0,audioStream;
115
        int len1, data_size, stime;
116
        int frameFinished;
117
        int numBytes,outbuf_audio_size,audio_size;
118
        int sizeFrame = 0;
119
        int sizeChunk = 0;
120
        int dir_entries;
121
        int audio_bitrate;
122
        int video_bitrate;
123
        
124
        uint8_t *buffer,*outbuf,*outbuf_audio;
125
        uint8_t *outbuf_audi_audio,*tempdata;
126
        //uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2]; //TRIPLO
127
        uint16_t *audio_buf=NULL;; //TRIPLO
128
        unsigned int audio_buf_size = 0;
129
        long double newtimestamp;
130
        
131
        AVFormatContext *pFormatCtx;
132
        AVCodecContext  *pCodecCtx,*pCodecCtxEnc,*aCodecCtxEnc,*aCodecCtx;
133
        AVCodec         *pCodec,*pCodecEnc,*aCodec,*aCodecEnc;
134
        AVFrame         *pFrame; 
135
        AVFrame         *pFrameRGB;
136
        AVPacket         packet;
137

    
138
        Frame *frame=NULL;
139

    
140
        ExternalChunk *chunk=NULL;
141
        ExternalChunk *chunkaudio=NULL;
142
        ChunkerMetadata *cmeta=NULL;
143
        
144
        char buf[1024],outfile[1024], basedelfile[1024],delfile[1024];
145
        FILE *fp,*f1;
146

    
147
        long long Now;
148
        short int FirstTimeAudio=1, FirstTimeVideo=1;
149
        long long DeltaTimeAudio=0, DeltaTimeVideo=0, newTime;
150
        
151
        struct dirent **namelist;
152
        
153
        if(argc < 4) {
154
                printf("execute ./chunker_streamer moviefile audiobitrate videobitrate\n");
155
                return -1;
156
        }
157
        sscanf(argv[2],"%d",&audio_bitrate);
158
        sscanf(argv[3],"%d",&video_bitrate);
159

    
160
        cmeta = chunkerInit("configChunker.txt");
161
        
162
        dir_entries = scandir("chunks",&namelist,NULL,alphasortNew);
163
        if(dir_entries>0) {
164
                strcpy(basedelfile,"chunks/");
165
                for(i=0;i<dir_entries;i++) {
166
                        if(!strcmp(namelist[i]->d_name,".") || !strcmp(namelist[i]->d_name,".."))
167
                                continue;
168
                        strcpy(delfile,basedelfile);
169
                        strcat(delfile,namelist[i]->d_name);
170
                        unlink(delfile);
171
                        free(namelist[i]);
172
                }
173
                free(namelist);
174
                rmdir("chunks");
175
        }
176
        mkdir("chunks",0777);
177
        
178
        outbuf_audio_size = 10000;
179
        outbuf_audio = malloc(outbuf_audio_size);
180
        printf("Chunkbuffer Strategy:%d Value Strategy:%d\n", cmeta->strategy, cmeta->val_strategy);
181
        f1 = fopen("original.mpg","wb");
182

    
183
        // Register all formats and codecs
184
        av_register_all();
185

    
186
        // Open video file
187
        if(av_open_input_file(&pFormatCtx, argv[1], NULL, 0, NULL)!=0)
188
                return -1; // Couldn't open file
189
  
190
        // Retrieve stream information
191
        if(av_find_stream_info(pFormatCtx)<0)
192
                return -1; // Couldn't find stream information
193
  
194
        // Dump information about file onto standard error
195
        dump_format(pFormatCtx, 0, argv[1], 0);
196
  
197
        // Find the first video stream
198
        videoStream=-1;
199
        audioStream=-1;
200
        printf("Num streams : %d\n",pFormatCtx->nb_streams);
201
        for(i=0; i<pFormatCtx->nb_streams; i++) {
202
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
203
                        videoStream=i;
204
                }
205
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
206
                        audioStream=i;
207
                }
208
        }
209
        printf("Video stream has id : %d\n",videoStream);
210
        printf("Audio stream has id : %d\n",audioStream);
211

    
212
        if(videoStream==-1 && audioStream==-1)
213
                return -1; // Didn't find a video stream
214
  
215
        // Get a pointer to the codec context for the video stream
216
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
217
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
218

    
219
        printf("Width:%d Height:%d\n",pCodecCtx->width,pCodecCtx->height);
220

    
221
        if(audioStream!=-1) {
222
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
223
                printf("AUDIO Codecid: %d %d\n",aCodecCtx->codec_id,aCodecCtx->sample_rate);
224
                printf("AUDIO channels %d samplerate %d\n",aCodecCtx->channels,aCodecCtx->sample_rate);
225
        }
226

    
227

    
228

    
229
        pCodecCtxEnc=avcodec_alloc_context();
230
        //pCodecCtxEnc->me_range=16;
231
        //pCodecCtxEnc->max_qdiff=4;
232
        //pCodecCtxEnc->qmin=10;
233
        //pCodecCtxEnc->qmax=51;
234
        //pCodecCtxEnc->qcompress=0.6;
235
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
236
        pCodecCtxEnc->codec_id   = 13;//CODEC_ID_H264;//pCodecCtx->codec_id;
237
        pCodecCtxEnc->bit_rate = video_bitrate;///400000;
238
        // resolution must be a multiple of two 
239
        pCodecCtxEnc->width = pCodecCtx->width;
240
        pCodecCtxEnc->height = pCodecCtx->height;
241
        // frames per second 
242
        pCodecCtxEnc->time_base= (AVRational){1,25};
243
        pCodecCtxEnc->gop_size = 10; // emit one intra frame every ten frames 
244
        //pCodecCtxEnc->max_b_frames=1;
245
        pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P;
246

    
247
        aCodecCtxEnc = avcodec_alloc_context();
248
        aCodecCtxEnc->bit_rate = 64000;//audio_bitrate; //256000
249
        aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
250
        aCodecCtxEnc->sample_rate = 44100;//aCodecCtx->sample_rate;
251
        aCodecCtxEnc->channels = 2; //aCodecCtx->channels;
252
        printf("InitAUDIOFRAMESIZE:%d %d\n",aCodecCtxEnc->frame_size,av_rescale(44100,1,25));
253

    
254
        // Find the decoder for the video stream
255
        
256
        if(audioStream!=-1) {
257
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
258
                aCodecEnc = avcodec_find_encoder(CODEC_ID_MP2);//CODEC_ID_MP3
259
                if(aCodec==NULL) {
260
                        fprintf(stderr,"Unsupported acodec!\n");
261
                        return -1;
262
                }
263
                if(aCodecEnc==NULL) {
264
                        fprintf(stderr,"Unsupported acodecEnc!\n");
265
                        return -1;
266
                }
267
        
268
                if(avcodec_open(aCodecCtx, aCodec)<0) {
269
                        fprintf(stderr, "could not open codec\n");
270
                        return -1; // Could not open codec
271
                }
272
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
273
                        fprintf(stderr, "could not open codec\n");
274
                        return -1; // Could not open codec
275
                }
276

    
277
        }
278

    
279
        //printf("%d %d",pCodecCtx->codec_id,CODEC_ID_H264);
280
        pCodecEnc =avcodec_find_encoder(13);//(CODEC_ID_H264);//pCodecCtx->codec_id);
281

    
282
        if(pCodec==NULL) {
283
                fprintf(stderr, "Unsupported pcodec!\n");
284
                return -1; // Codec not found
285
        }
286
        if(pCodecEnc==NULL) {
287
                fprintf(stderr, "Unsupported pcodecenc!\n");
288
                return -1; // Codec not found
289
        }
290
        if(avcodec_open(pCodecCtx, pCodec)<0) {
291
                fprintf(stderr, "could not open codec\n");
292
                return -1; // Could not open codec
293
        }
294
        if(avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
295
                fprintf(stderr, "could not open codecEnc\n");
296
                return -1; // Could not open codec
297
        }
298

    
299
        // Allocate video frame
300
        pFrame=avcodec_alloc_frame();
301
        if(pFrame==NULL) {
302
                printf("Memory error!!!\n");
303
                return -1;
304
        }
305
  
306
        i=0;
307
        outbuf_size = 100000;
308
        outbuf = malloc(outbuf_size);
309
        if(!outbuf) {
310
                printf("Memory error!!!\n");
311
                return -1;
312
        }
313
        frame = (Frame *)malloc(sizeof(Frame));
314
        if(!frame) {
315
                printf("Memory error!!!\n");
316
                return -1;
317
        }
318
        sizeFrame = 3*sizeof(int)+sizeof(struct timeval);
319
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
320
        if(!chunk) {
321
                printf("Memory error!!!\n");
322
                return -1;
323
        }
324
        sizeChunk = 6*sizeof(int)+2*sizeof(struct timeval)+sizeof(double);
325
        initChunk(chunk,&seq_current_chunk);
326
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
327
        if(!chunkaudio) {
328
                printf("Memory error!!!\n");
329
                return -1;
330
        }
331
        initChunk(chunkaudio,&seq_current_chunk);
332
        stime = -1;
333
        
334
        av_init_packet(&packet); //TRIPLO
335
        
336
        if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
337
                fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
338
                return -1;
339
        }
340

    
341

    
342
        /* initialize the HTTP chunk pusher */
343
        initChunkPusher(); //TRIPLO
344
        audio_buf = (uint16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE); //TRIPLO
345

    
346

    
347
        while(av_read_frame(pFormatCtx, &packet)>=0) {
348
                //printf("reading\n");
349
                // Is this a packet from the video stream?
350
                if(packet.stream_index==videoStream) {
351
                        //printf("Videostream\n");
352
                        // Decode video frame
353
                        avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
354

    
355
                        // Did we get a video frame?
356
                        //stime = (int)packet.dts;
357
                        //printf("VIDEO: stime:%d %d\n",stime,(int)packet.dts);
358
                        if(frameFinished) { // it must be true all the time else error
359
                                out_size = avcodec_encode_video(pCodecCtxEnc, outbuf, outbuf_size, pFrame);
360
                                //printf("video frame size nuovo pippo : %d\n",pCodecCtxEnc->frame_size);
361
                                frame->number = pCodecCtx->frame_number;
362
                                
363
                                Now=(long long)SDL_GetTicks();
364
                                printf("dts:%d %d %d\n",(int)packet.dts,(int)packet.duration,pCodecCtxEnc->time_base.den);
365
                                if(packet.duration>0)
366
                                        newtimestamp = (((int)(packet.dts))/((double)(packet.duration*pCodecCtxEnc->time_base.den)));
367
                                else
368
                                        newtimestamp =(long double)(((double)(packet.dts))/1000);
369
                                //frame->timestamp.tv_sec = (long)packet.dts*1.e-5;
370
                                //frame->timestamp.tv_usec = ((long)packet.dts%100000/100);
371
                                printf("ts:%llf\n",newtimestamp);
372
                                if(FirstTimeVideo) {
373
                                        //printf("%lld\n",Now);
374
                                        DeltaTimeVideo=Now-((unsigned int)newtimestamp*(unsigned long long)1000+(newtimestamp-(unsigned int)newtimestamp)*1000);
375
                                        FirstTimeVideo = 0;
376
                                        //printf("DeltaTimeVideo : %lld\n",DeltaTimeVideo);
377
                                }
378

    
379
                                newTime = DeltaTimeVideo+((unsigned int)newtimestamp*(unsigned long long)1000+(newtimestamp-(unsigned int)newtimestamp)*1000);
380

    
381
                                printf("newTime : %d\n",newTime);
382

    
383
                                frame->timestamp.tv_sec = (unsigned int)newTime/1000;
384
                                frame->timestamp.tv_usec = newTime%1000;
385

    
386
                                frame->size = out_size;
387
                                frame->type = pFrame->pict_type;
388
                                //printf("video newt:%lf dts:%ld dur:%d sec:%d usec%d pts:%d\n",newtimestamp,(long)packet.dts,packet.duration,frame->timestamp.tv_sec,frame->timestamp.tv_usec,packet.pts);
389
                                //printf("num:%d size:%d type:%d\n",frame->number,frame->size,frame->type);
390

    
391
                                printf("VIDEO: tvsec:%d tvusec:%d\n",frame->timestamp.tv_sec,frame->timestamp.tv_usec);
392
                                // Save the frame to disk
393
                                ++i;
394
                                //SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height, i);
395
                                
396
                                //printf("out_size:%d outbuf_size:%d packet.size:%d\n",out_size,outbuf_size,packet.size);
397
                                //        printf("%d %d\n",pCodecCtxEnc->width,pCodecCtxEnc->height);
398
                                chunk->frames_num++; // number of frames in the current chunk
399
                                chunk->data = (uint8_t *)realloc(chunk->data,sizeof(uint8_t)*(chunk->payload_len+out_size+sizeFrame));
400
                                if(!chunk->data)  {
401
                                        printf("Memory error!!!\n");
402
                                        return -1;
403
                                }
404
        //printf("rialloco data di dim:%d con nuova dim:%d\n",chunk->payload_len,out_size);
405

    
406
                                tempdata = chunk->data+chunk->payload_len;
407
                                *((int *)tempdata) = frame->number;
408
                                tempdata+=sizeof(int);
409
                                *((struct timeval *)tempdata) = frame->timestamp;
410
                                tempdata+=sizeof(struct timeval);
411
                                *((int *)tempdata) = frame->size;
412
                                tempdata+=sizeof(int);
413
                                *((int *)tempdata) = frame->type;
414
                                tempdata+=sizeof(int);
415
                                
416
                                memcpy(chunk->data+chunk->payload_len+sizeFrame,outbuf,out_size); // insert new data
417
                                chunk->payload_len += out_size + sizeFrame; // update payload length
418
                                //printf("outsize:%d payload_len:%d\n",out_size,chunk->payload_len);
419
                                chunk->len = sizeChunk+chunk->payload_len ; // update overall length
420
                                
421
                                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) {
422
                                        chunk->start_time.tv_sec = frame->timestamp.tv_sec;
423
                                        chunk->start_time.tv_usec = frame->timestamp.tv_usec;
424
                                }
425
                                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) {
426
                                        chunk->end_time.tv_sec = frame->timestamp.tv_sec;
427
                                        chunk->end_time.tv_usec = frame->timestamp.tv_usec;
428
                                }
429
                                stime = -1;
430
                                //printf("Frame video %d stime:%d frame num:%d\n",stime,pCodecCtxEnc->frame_number);
431
                                if(chunkFilled(chunk, cmeta)) { // is chunk filled using current strategy?
432
                                        //chbAddChunk(chunkbuffer,chunk); // add a chunk to the chunkbuffer
433
                                        //SAVE ON FILE
434
                                        saveChunkOnFile(chunk);
435
                                        initChunk(chunk,&seq_current_chunk);
436
                                }
437
                                /* pict_type maybe 1 (I), 2 (P), 3 (B), 4 (AUDIO)*/
438

    
439
                                fwrite(outbuf, 1, out_size, f1); // reconstructing original video
440
                        }
441
                }
442
                else if(packet.stream_index==audioStream) {
443

    
444
                        //printf("packet audio dts:%d dts:%d\n",(int)packet.dts,(int)packet.dts);
445
                        data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
446
                        len1 = avcodec_decode_audio3(aCodecCtx, (short *)audio_buf, &data_size, &packet);
447
                        if(len1<0) {
448
                                fprintf(stderr, "Error while decoding\n");
449
                                return -1;
450
                        }
451
                        if(data_size>0) {
452
                                /* if a frame has been decoded, output it */
453
                                //fwrite(audio_buf, 1, data_size, outfileaudio);
454
                        }
455
                        else
456
                                printf("Error data_size!!\n");
457
                        audio_size = avcodec_encode_audio(aCodecCtxEnc,outbuf_audio,data_size,(short *)audio_buf);
458
                        //printf("audio frame size nuovo pippo : %d %d datasize:%d %d %d\n",aCodecCtxEnc->frame_size,aCodecCtxEnc->time_base.den,data_size,packet.size, len1);
459
                        //printf("oldaudiosize:%d Audio size : %d\n",len1,audio_size);
460
                        //printf("stream_index:%d flags:%d pos:%d conv_duration:%d dts:%d dts:%d duration:%d\n",packet.stream_index,packet.flags,packet.pos,packet.convergence_duration,packet.dts,packet.dts,packet.duration);
461
                        
462
                        frame->number = aCodecCtx->frame_number;
463

    
464
                        //newtimestamp = (double)((float)packet.dts/(packet.duration*34.100));
465
                        Now=(long long)SDL_GetTicks();
466
                        newtimestamp = (double)((double)packet.dts/(packet.duration*aCodecCtxEnc->time_base.den));
467
                        //frame->timestamp.tv_sec = (long)packet.dts*1.e-5;
468
                        //frame->timestamp.tv_usec = ((long)packet.dts%100000/100);
469

    
470
                        if(FirstTimeAudio) {
471
                                DeltaTimeAudio=Now-((unsigned int)newtimestamp*(unsigned long long)1000+(newtimestamp-(unsigned int)newtimestamp)*1000);
472
                                FirstTimeAudio = 0;
473
                        }
474

    
475
                        newTime = DeltaTimeAudio+((unsigned int)newtimestamp*(unsigned long long)1000+(newtimestamp-(unsigned int)newtimestamp)*1000);
476
                        //printf("%lld %lld\n",newTime/1000,newTime%1000);
477

    
478
                        frame->timestamp.tv_sec = (unsigned int)newTime/1000;
479
                        frame->timestamp.tv_usec = newTime%1000;
480

    
481
                        printf("AUDIO: tvsec:%d tvusec:%d\n",frame->timestamp.tv_sec,frame->timestamp.tv_usec);
482

    
483
                        //frame->timestamp.tv_sec = (unsigned int)newtimestamp;
484
                        //frame->timestamp.tv_usec = (newtimestamp-frame->timestamp.tv_sec)*1000;
485

    
486
                        //printf("Audio time nuovo :%lld %lld\n",Now,DeltaTimeAudio+((long long)frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec));
487

    
488
                        //printf("audio newt:%lf dts:%ld dur:%d sec:%d usec%d pts:%d\n",newtimestamp,(long)packet.dts,packet.duration,frame->timestamp.tv_sec,frame->timestamp.tv_usec,packet.pts);
489
                        frame->size = audio_size;
490
                        frame->type = 5; // 5 is audio type
491
                        
492
                        chunkaudio->frames_num++; // number of frames in the current chunk
493
                        
494
                        chunkaudio->data = (uint8_t *)realloc(chunkaudio->data,sizeof(uint8_t)*(chunkaudio->payload_len+audio_size+sizeFrame));
495
                        if(!chunkaudio->data) {
496
                                printf("Memory error!!!\n");
497
                                return -1;
498
                        }
499
                        tempdata = chunkaudio->data+chunkaudio->payload_len;
500
                        *((int *)tempdata) = frame->number;
501
                        tempdata+=sizeof(int);
502
                        *((struct timeval *)tempdata) = frame->timestamp;
503
                        tempdata+=sizeof(struct timeval);
504
                        *((int *)tempdata) = frame->size;
505
                        tempdata+=sizeof(int);
506
                        *((int *)tempdata) = frame->type;
507
                        tempdata+=sizeof(int);
508
                                
509
                        memcpy(chunkaudio->data+chunkaudio->payload_len+sizeFrame,outbuf_audio,audio_size);
510
                        chunkaudio->payload_len += audio_size + sizeFrame; // update payload length
511
                                //printf("outsize:%d payload_len:%d\n",out_size,chunk->payload_len);
512
                        chunkaudio->len = sizeChunk+chunkaudio->payload_len ; // update overall length
513
                        
514
//                        stime = (int)packet.dts;
515
                        //printf("AUDIO: stime:%d\n",stime);
516
                        if(((int)frame->timestamp.tv_sec < (int)chunkaudio->start_time.tv_sec) || ((int)frame->timestamp.tv_sec==(int)chunkaudio->start_time.tv_sec && (int)frame->timestamp.tv_usec < (int)chunkaudio->start_time.tv_usec) || (int)chunkaudio->start_time.tv_sec==-1) {
517
                                chunkaudio->start_time.tv_sec = frame->timestamp.tv_sec;
518
                                chunkaudio->start_time.tv_usec = frame->timestamp.tv_usec;
519
                        }
520
                        if(((int)frame->timestamp.tv_sec > (int)chunkaudio->end_time.tv_sec) || ((int)frame->timestamp.tv_sec==(int)chunkaudio->end_time.tv_sec && (int)frame->timestamp.tv_usec > (int)chunkaudio->end_time.tv_usec) || (int)chunkaudio->end_time.tv_sec==-1) {
521
                                chunkaudio->end_time.tv_sec = frame->timestamp.tv_sec;
522
                                chunkaudio->end_time.tv_usec = frame->timestamp.tv_usec;
523
                        }
524
        //                if(stime < chunkaudio->start_time.tv_usec || chunkaudio->start_time.tv_usec==-1)
525
                //                chunkaudio->start_time.tv_usec = stime;
526
                //        if(stime > chunkaudio->end_time.tv_usec || chunkaudio->end_time.tv_usec==-1)
527
                //                chunkaudio->end_time.tv_usec = stime;
528
                        stime=-1;
529
                        chunkaudio->priority = 1;
530
                        //printf("Frame audio stime:%d frame_num:%d\n",stime,aCodecCtxEnc->frame_number);
531
                        if(chunkFilled(chunkaudio, cmeta)) { // is chunk filled using current strategy?
532
                                //chbAddChunk(chunkbuffer,chunkaudio); // add a chunk to the chunkbuffer
533
                                //SAVE ON FILE
534
                                saveChunkOnFile(chunkaudio);
535
                                initChunk(chunkaudio,&seq_current_chunk);
536
                        }
537
                }
538
                else {
539
                        // Free the packet that was allocated by av_read_frame
540
                        av_free_packet(&packet);
541
                }
542
        }
543

    
544
        if(chunk->frames_num>0) {
545
                //chbAddChunk(chunkbuffer,chunk);
546
                //SAVE ON FILE
547
                saveChunkOnFile(chunk);        
548
        }
549
        if(chunkaudio->frames_num>0) {
550
                //chbAddChunk(chunkbuffer,chunkaudio);
551
                //SAVE ON FILE
552
                saveChunkOnFile(chunkaudio);
553
                
554
        }
555

    
556

    
557
        /* initialize the HTTP chunk pusher */
558
        finalizeChunkPusher();
559

    
560

    
561
        free(chunk);
562
        free(chunkaudio);
563
        free(frame);
564
        fclose(f1);
565

    
566
        // Writing chunk files
567
        printf("cmetasize:%d\n",cmeta->size);
568
        for(i=0;i<cmeta->size;i++) {
569
                printf("seq:%d pay_len:%d frames_num:%d priority:%f ssec:%d susec:%d esec:%d eusec:%d\n",cmeta->echunk[i].seq,cmeta->echunk[i].payload_len,cmeta->echunk[i].frames_num,cmeta->echunk[i].priority,(int)cmeta->echunk[i].start_time.tv_sec,(int)cmeta->echunk[i].start_time.tv_usec,(int)cmeta->echunk[i].end_time.tv_sec,(int)cmeta->echunk[i].end_time.tv_usec);
570
        }
571

    
572
        // Free the YUV frame
573
        av_free(pFrame);
574

    
575
        av_free(audio_buf); //TRIPLO
576
  
577
        // Close the codec
578
        avcodec_close(pCodecCtx);
579
        avcodec_close(pCodecCtxEnc);
580

    
581
        if(audioStream!=-1) {
582
                avcodec_close(aCodecCtx);
583
                avcodec_close(aCodecCtxEnc);
584
        }
585
  
586
        // Close the video file
587
        av_close_input_file(pFormatCtx);
588
  
589
        return 0;
590
}