/*
 * PhotoCD Player plugin for VDR
 * pcd_mpeg.c: Generate MPEG still image
 *
 * See the README file for copyright information and how to reach the author.
 *
 * This code is distributed under the terms and conditions of the
 * GNU GENERAL PUBLIC LICENSE. See the file COPYING for details.
 *
 * $Id$
 */


#include <stdlib.h>
#include <string.h>
#include "pcd_mpeg.h"
#include "pcd_setup.h"

#define STARTCODE_SIZE    6
#define PTS_SIZE          5
#define PACKET_DATA_SIZE  0x2000
#define DEFAULT_FRAME_RATE_BASE 1001000


// --- cMpegFrame ------------------------------------------------------------

cMpegFrame::cMpegFrame(bool Pal)
{
  pal = Pal;
  width = pal ? PAL_WIDTH : NTSC_WIDTH;
  height = pal ? PAL_HEIGHT : NTSC_HEIGHT;

  avContext = NULL;
  buffer = NULL;
  bufferSize = 0;
  mpegSize = 0;

  avcodec_init();
  avcodec_register_all();

  if (!(avCodec = avcodec_find_encoder(CODEC_ID_MPEG1VIDEO))) {
     dsyslog("PCD: Codec not found");
     return;
     }

  avContext = avcodec_alloc_context();
  avFrame = avcodec_alloc_frame();

  avContext->bit_rate = 400000;
  avContext->width = width;
  avContext->height = height;
//  avContext->frame_rate = (pal ? 25 : 30) * DEFAULT_FRAME_RATE_BASE;
  avContext->gop_size = 1;
  avContext->flags |= CODEC_FLAG_QSCALE;

  if (avcodec_open(avContext, avCodec) < 0) {
     dsyslog("PCD: Can't open codec");
     return;
     }

  bufferSize = width * height;
  buffer = (unsigned char*)malloc(3 * bufferSize); // enough for an i-coded frame...

  avFrame->linesize[0] = width;
  avFrame->linesize[1] = width/2;
  avFrame->linesize[2] = width/2;
  avFrame->quality = PcdSetupData.Quality;
}

cMpegFrame::~cMpegFrame()
{
  avcodec_close(avContext);
  free(avContext);
  free(avFrame);
  free(buffer);
 
}

void cMpegFrame::Encode(unsigned char *Image)
{
  if (bufferSize<15) return;
  avFrame->data[0] = Image;
  avFrame->data[1] = avFrame->data[0] + bufferSize;
  avFrame->data[2] = avFrame->data[1] + bufferSize/4;
  mpegSize = avcodec_encode_video(avContext, buffer, bufferSize, avFrame);
}
