/*
 * video.c: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 *
 * This is a software output driver.
 * It scales the image more or less perfect in sw and sends it over the network.
 */

#include <sys/mman.h>
#include <sys/ioctl.h>
#include <fcntl.h> 
#include <vdr/plugin.h>
#include "video-net.h"
#include "utils.h"

//const char filename[] = "http://localhost:8090/feed1.ffm";
//const char filename[] = "udp://192.168.10.10:1234/test.ts";
//const char filename[] = "/hddpool/video/avformat.mpg";

#define DEST_WIDTH 352
#define DEST_HEIGHT 288



/* add a video output stream */
AVStream *cFBVideoOut::add_video_stream(AVFormatContext *oc, int codec_id)
{
    AVCodecContext *c;
    AVStream *st;

    st = av_new_stream(oc, 0);
    if (!st) {
        fprintf(stderr,"[video-net] Could not alloc stream\n");
        exit(1);
    }
    
    c = st->codec;
    c->codec_id = (CodecID) codec_id;
    c->codec_type = CODEC_TYPE_VIDEO;

    /* put sample parameters */
    c->bit_rate = 10000000;
    /* resolution must be a multiple of two */
    c->width = DEST_WIDTH;  
    c->height = DEST_HEIGHT;
    /* frames per second */
    c->time_base.den = 25;  
    c->time_base.num = 1;
    c->gop_size = 0; /* emit one intra frame every twelve frames at most */
    if (c->codec_id == CODEC_ID_MPEG2VIDEO) {
        /* just for testing, we also add B frames */
        c->max_b_frames = 0;
        c->me_method=ME_ZERO;
    }
    if (c->codec_id == CODEC_ID_MPEG1VIDEO){
        /* needed to avoid using macroblocks in which some coeffs overflow 
           this doesnt happen with normal video, it just happens here as the 
           motion of the chroma plane doesnt match the luma plane */
        c->mb_decision=2;
    }
    // some formats want stream headers to be seperate
    if(!strcmp(oc->oformat->name, "mp4") || !strcmp(oc->oformat->name, "mov") || !strcmp(oc->oformat->name, "3gp"))
        c->flags |= CODEC_FLAG_GLOBAL_HEADER;


    Xres=DEST_WIDTH;
    Yres=DEST_HEIGHT;
    Bpp = 16;

    line_len = DEST_WIDTH*2;
    
    return st;
}

AVFrame *cFBVideoOut::alloc_picture(int pix_fmt, int width, int height)
{
    AVFrame *picture;
    uint8_t *picture_buf;
    int size;
            
    picture = avcodec_alloc_frame();
    if (!picture)
       return NULL;
    size = avpicture_get_size(pix_fmt, width, height);
    picture_buf = (uint8_t *) malloc(size);
    if (!picture_buf) {
        av_free(picture);
        return NULL;
    }
    avpicture_fill((AVPicture *)picture, picture_buf,
                   pix_fmt, width, height);
    return picture;
}
   
void cFBVideoOut::open_video(AVFormatContext *oc, AVStream *st)
{
    AVCodec *codec;
    AVCodecContext *c;

    c = st->codec;

    /* find the video encoder */
    codec = avcodec_find_encoder(c->codec_id);
    if (!codec) {
        fprintf(stderr,"[video-net] codec not found\n");
        exit(1);
    }

    /* open the codec */
    if (avcodec_open(c, codec) < 0) {
        fprintf(stderr,"[video-net] could not open codec\n");
        exit(1);
    }

    video_outbuf = NULL;
    if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {
        /* allocate output buffer */
        /* XXX: API change will be done */
        video_outbuf_size = 200000;
        video_outbuf = (uint8_t*) malloc(video_outbuf_size);
    }

    picture= avcodec_alloc_frame(); 
    if (!picture) {
	fprintf(stderr,"[video-net] Cannot allocate picture.\n");
	exit(1);
    }
    tmp_picture = alloc_picture(PIX_FMT_RGB565,DEST_WIDTH,DEST_HEIGHT);
    if (!tmp_picture) {
	fprintf(stderr,"[video-net] Cannot allocate tmp_picture.\n");
	exit(1);
    }
    tmp2_picture =alloc_picture(PIX_FMT_YUV420P,DEST_WIDTH,DEST_HEIGHT);
    if (!tmp2_picture) {
	fprintf(stderr,"[video-net] Cannot allocate tmp2_picture.\n");
	exit(1);
    }
    empty_picture =alloc_picture(PIX_FMT_RGB565,DEST_WIDTH,DEST_HEIGHT);
    if (!empty_picture) {
	fprintf(stderr,"[video-net] Cannot allocate empty_picture.\n");
	exit(1);
    }

}
                                                                                       
/* prepare a dummy image */
void cFBVideoOut::fill_yuv_image(AVFrame *pict, int frame_index, int width, int height)
{
    int x, y, i;
    
    i = frame_index;
      
    /* Y */
    for(y=0;y<height;y++) {
       for(x=0;x<width;x++) {
          pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
       }
    }
                                                
    /* Cb and Cr */
    for(y=0;y<height/2;y++) {
       for(x=0;x<width/2;x++) {
           pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
           pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
       }
    }
}

void cFBVideoOut::write_video_frame(AVFormatContext *oc, AVStream *st, AVFrame *frame)
{
    int out_size, ret;
    AVCodecContext *c;
    AVFrame *picture_ptr;
    
    c = st->codec;
    
    picture_ptr = frame;
    
        /* encode the image */
        out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture_ptr);
        /* if zero size, it means the image was buffered */
        if (out_size != 0) {
    	    
            AVPacket pkt;
            av_init_packet(&pkt);
            
            pkt.pts= c->coded_frame->pts;
            if(c->coded_frame->key_frame)
                pkt.flags |= PKT_FLAG_KEY;
            pkt.stream_index= st->index;
            pkt.data= video_outbuf;
            pkt.size= out_size;
            
            /* write the compressed frame in the media file */
            ret = av_write_frame(oc, &pkt);
        } else {
            ret = 0;
        }
    
    if (ret != 0) {
        fprintf(stderr, "[video-net] Error while writing video frame.\n");
        exit(1);
    }
}

void cFBVideoOut::close_video(AVFormatContext *oc, AVStream *st)
{
    avcodec_close(st->codec);
    av_free(picture->data[0]);
    av_free(picture);
    if (tmp_picture) {
        av_free(tmp_picture->data[0]);
        av_free(tmp_picture);
    }
    av_free(video_outbuf);
}


                                                                                                    
static  pthread_mutex_t fb_mutex = PTHREAD_MUTEX_INITIALIZER;
// --- cFrameBuffer --------------------------------------------------------
cFBVideoOut::cFBVideoOut(char *fn)
{
    strcpy(filename, fn);

    fprintf(stderr,"[video-net] Initializing video mpeg encoder\n");
    av_register_all();

    fmt = guess_format(NULL, filename, NULL);
    if (!fmt) {
       fprintf(stderr,"[video-net] Could not deduce output format from file extension: using MPEG.\n");
       fmt = guess_format("mpeg", NULL, NULL);
    }
    if (!fmt) {
        fprintf(stderr,"[video-net] Could not find suitable output format.\n");
        exit(1);
    }

    /* allocate the output media context */
    oc = av_alloc_format_context();
    if (!oc) {
        fprintf(stderr,"[video-net] Could not allocate format context.\n");
        exit(1);
    }
    oc->oformat = fmt;
    snprintf(oc->filename, sizeof(oc->filename), "%s", filename);

    /* add the audio and video streams using the default format codecs
       and initialize the codecs */
    video_st = NULL;
    if (fmt->video_codec != CODEC_ID_NONE) {
        video_st = add_video_stream(oc, fmt->video_codec);
    }

    /* set the output parameters (must be done even if no
       parameters). */
    if (av_set_parameters(oc, NULL) < 0) {
        fprintf(stderr, "[video-net] Invalid output format parameters.\n");
        exit(1);
    }

    dump_format(oc, 0, filename, 1);

    /* now that all the parameters are set, we can open the audio and
       video codecs and allocate the necessary encode buffers */
    if (video_st)
        open_video(oc, video_st);

    /* open the output file, if needed */
    if (!(fmt->flags & AVFMT_NOFILE)) {
        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
            fprintf(stderr,"[video-net] Could not open '%s'\n", filename);
            exit(1);
        }
    }
    /* write the stream header, if any */
    av_write_header(oc);

    OSDpresent=false;

    printf("[video-net] init %d x %d (Size: %d Bytes LineLen %d) Bpp: %d\n",Xres,Yres, size, line_len, Bpp);
    
    current_osd=(cBitmap *) malloc(sizeof(cBitmap));
    
    if (!current_osd) {
	fprintf(stderr,"[video-net] Could not allocate memory for 'cBitmap *current_osd'.\n");
	exit(1);
    }

    current_osd= new cBitmap (720, 576, Bpp, 0,0);
    lastpic=getTimeMilis();
    Start(); //starte thread 
}

void cFBVideoOut::Pause(void) 
{
}


void cFBVideoOut::Action()
{
   uint64_t time;
      
   	//printf("[video-net] Neuer Thread gestartet. pid:%d\n",getpid());
	running=true;
	active=true;
	while(active) {
	  time= getTimeMilis();
          delay=(int)(time-lastpic);
	    if ((delay>240)) {       
               	Draw(current_osd,empty_picture->data[0],line_len);
                img_convert((AVPicture *)tmp2_picture, PIX_FMT_YUV420P,
	            (AVPicture *)empty_picture, PIX_FMT_RGB565,
	              DEST_WIDTH, DEST_HEIGHT);
		write_video_frame(oc, video_st, tmp2_picture);
                                
                if (!(framecount % 10) ) 
                  printf("[video-net] Encoding empty frame %3d \n", framecount);
                framecount++;
                usleep(100);			
	     } else usleep(1000);
	
	}
	running=false;
	//printf("[video-net] Thread beendet.\n");
}



void cFBVideoOut::Refresh(cBitmap *Bitmap)
{
  const tIndex  *adr;
  tColor        c;
   
  current_osd->SetSize(Bitmap->Width(),Bitmap->Height());
  
  /* save current OSD bitmap for further usage */
  
  for (int y = 0; y < Bitmap->Height(); y++)
  {
    for (int x = 0; x < Bitmap->Width(); x++)
    {
      adr = Bitmap->Data(x, y);
      c = Bitmap->Color(*adr);
      current_osd->DrawPixel(x,y, c);
    }
  }
}

void cFBVideoOut::YUV(uint8_t *Py, uint8_t *Pu, uint8_t *Pv, int Width, int Height, int Ystride, int UVstride)
{
  
/*
  picture->data[0] = Py;
  picture->data[1] = Pu;
  picture->data[2] = Pv;
  picture->linesize[0] = Ystride;
  picture->linesize[1] = UVstride;
  picture->linesize[2] = UVstride;
*/
 
  if (OSDpresent) {

    yuv_to_rgb (tmp_picture->data[0], Py, Pu, Pv, Width, Height, line_len,Ystride,UVstride,Xres,Yres,Bpp, NULL);

//    img_convert((AVPicture *)tmp_picture, PIX_FMT_RGB565,
//	          (AVPicture *)picture, PIX_FMT_YUV420P,
//    	          Width, Height);
    
    Draw(current_osd,tmp_picture->data[0],line_len);
    
    img_convert((AVPicture *)tmp2_picture, PIX_FMT_YUV420P,
	            (AVPicture *)tmp_picture, PIX_FMT_RGB565,
	              DEST_WIDTH, DEST_HEIGHT);

    /* encode the image (current frame and OSD mixed) */

    write_video_frame(oc, video_st, tmp2_picture);
    
  } else {
  

    yuv_to_rgb (tmp_picture->data[0], Py, Pu, Pv, Width, Height, line_len,Ystride,UVstride,Xres,Yres,Bpp, NULL);

    img_convert((AVPicture *)tmp2_picture, PIX_FMT_YUV420P,
	            (AVPicture *)tmp_picture, PIX_FMT_RGB565,
	              DEST_WIDTH, DEST_HEIGHT);

    /* encode the image (current frame only) */
    
    write_video_frame(oc, video_st, tmp2_picture);
  
  }
  
   lastpic=getTimeMilis();
  
  if (!(framecount % 10) ) 
    printf("[video-net] Encoding frame %3d - source resolution: %3dx%3d\n", framecount,Width,Height);
  framecount++;
}

cFBVideoOut::~cFBVideoOut()
{
  int i;
    active=false; //stop thread
    Cancel(3);

    /* close each codec */
    if (video_st)
        close_video(oc, video_st);

    /* write the trailer, if any */
    av_write_trailer(oc);
 
    /* free the streams */
    for(i = 0; i < oc->nb_streams; i++) {
        av_freep(&oc->streams[i]);
    }

    if (!(fmt->flags & AVFMT_NOFILE)) {
        /* close the output file */
        url_fclose(&oc->pb);
    }

    /* free the stream */
    av_free(oc);

    printf("\n");
}

