Statistics
| Branch: | Revision:

chunker-player / chunker_streamer.c @ 1e69ae95

History | View | Annotate | Download (20.1 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];
127
        unsigned int audio_buf_size = 0;
128
        long double newtimestamp;
129
        
130
        AVFormatContext *pFormatCtx;
131
        AVCodecContext  *pCodecCtx,*pCodecCtxEnc,*aCodecCtxEnc,*aCodecCtx;
132
        AVCodec         *pCodec,*pCodecEnc,*aCodec,*aCodecEnc;
133
        AVFrame         *pFrame; 
134
        AVFrame         *pFrameRGB;
135
        AVPacket         packet;
136

    
137
        Frame *frame=NULL;
138

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

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

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

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

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

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

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

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

    
225
        printf("AUDIO channels %d samplerate %d\n",aCodecCtx->channels,aCodecCtx->sample_rate);
226

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

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

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

    
275
        }
276

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

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

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

    
339

    
340
        /* initialize the HTTP chunk pusher */
341
        initChunkPusher();
342

    
343

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

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

    
376
                                newTime = DeltaTimeVideo+((unsigned int)newtimestamp*(unsigned long long)1000+(newtimestamp-(unsigned int)newtimestamp)*1000);
377

    
378
                                printf("newTime : %d\n",newTime);
379

    
380
                                frame->timestamp.tv_sec = (unsigned int)newTime/1000;
381
                                frame->timestamp.tv_usec = newTime%1000;
382

    
383
                                frame->size = out_size;
384
                                frame->type = pFrame->pict_type;
385
                                //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);
386
                                //printf("num:%d size:%d type:%d\n",frame->number,frame->size,frame->type);
387

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

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

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

    
441
                        //printf("packet audio dts:%d dts:%d\n",(int)packet.dts,(int)packet.dts);
442
                        data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
443
                        len1 = avcodec_decode_audio3(aCodecCtx, (short *)audio_buf, &data_size, &packet);
444
                        if(len1<0) {
445
                                fprintf(stderr, "Error while decoding\n");
446
                                return -1;
447
                        }
448
                        if(data_size>0) {
449
                                /* if a frame has been decoded, output it */
450
                                //fwrite(audio_buf, 1, data_size, outfileaudio);
451
                        }
452
                        else
453
                                printf("Error data_size!!\n");
454
                        audio_size = avcodec_encode_audio(aCodecCtxEnc,outbuf_audio,data_size,(short *)audio_buf);
455
                        //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);
456
                        //printf("oldaudiosize:%d Audio size : %d\n",len1,audio_size);
457
                        //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);
458
                        
459
                        frame->number = aCodecCtx->frame_number;
460

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

    
467
                        if(FirstTimeAudio) {
468
                                DeltaTimeAudio=Now-((unsigned int)newtimestamp*(unsigned long long)1000+(newtimestamp-(unsigned int)newtimestamp)*1000);
469
                                FirstTimeAudio = 0;
470
                        }
471

    
472
                        newTime = DeltaTimeAudio+((unsigned int)newtimestamp*(unsigned long long)1000+(newtimestamp-(unsigned int)newtimestamp)*1000);
473
                        //printf("%lld %lld\n",newTime/1000,newTime%1000);
474

    
475
                        frame->timestamp.tv_sec = (unsigned int)newTime/1000;
476
                        frame->timestamp.tv_usec = newTime%1000;
477

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

    
480
                        //frame->timestamp.tv_sec = (unsigned int)newtimestamp;
481
                        //frame->timestamp.tv_usec = (newtimestamp-frame->timestamp.tv_sec)*1000;
482

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

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

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

    
553

    
554
        /* initialize the HTTP chunk pusher */
555
        initChunkPusher();
556

    
557

    
558
        free(chunk);
559
        free(chunkaudio);
560
        free(frame);
561
        fclose(f1);
562

    
563
        // Writing chunk files
564
        printf("cmetasize:%d\n",cmeta->size);
565
        for(i=0;i<cmeta->size;i++) {
566
                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);
567
        }
568

    
569
        // Free the YUV frame
570
        av_free(pFrame);
571
  
572
        // Close the codec
573
        avcodec_close(pCodecCtx);
574
        avcodec_close(pCodecCtxEnc);
575

    
576
        if(audioStream!=-1) {
577
                avcodec_close(aCodecCtx);
578
                avcodec_close(aCodecCtxEnc);
579
        }
580
  
581
        // Close the video file
582
        av_close_input_file(pFormatCtx);
583
  
584
        return 0;
585
}