/*
 * mpeg.c: Generate MPEG still image
 *
 * PhotoCD Player plugin for VDR (the Video Disk Recorder)
 * Copyright (C) 2002  Thomas Heiligenmann  <thomas@heiligenmann.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA
 *
 */


#include <stdlib.h>
#include <string.h>
#include "mpeg.h"
#include "setup.h"

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


// --- 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_MPEG2VIDEO))) {
     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->time_base = (AVRational){1, pal ? 25 : 30};
  avContext->gop_size = 1;
  avContext->flags |= CODEC_FLAG_QSCALE;
  avContext->pix_fmt = PIX_FMT_YUV420P;

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

  bufferSize = 3 * width * height;
  buffer = (unsigned char*)malloc(bufferSize);

  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;

  int imgsize = width * height;
  avFrame->data[0] = Image;
  avFrame->data[1] = Image + imgsize;
  avFrame->data[2] = Image + imgsize + imgsize/4;

  mpegSize = avcodec_encode_video(avContext, buffer, bufferSize, avFrame);
}
