/*
 *  Copyright 1994-2022 Olivier Girondel
 *
 *  This file is part of lebiniou.
 *
 *  lebiniou 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.
 *
 *  lebiniou 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 lebiniou. If not, see <http://www.gnu.org/licenses/>.
 */

#include "context.h"

uint32_t options = BO_NONE;
uint32_t version = 0;
char desc[] = "RTMP streaming";


#define FFMPEG_CHECK     "ffmpeg -h >/dev/null 2>&1"
#define FFMPEG           "ffmpeg"
#define RTMP_FFMPEG_ARGS "-loglevel quiet -re -vcodec ppm -f image2pipe -i pipe: -c:v libx264 -b:v 5M -pix_fmt yuv420p -c:a:0 libfdk_aac -b:a:0 480k -f flv"
#define RTMP_URL         "rtmp://localhost/live/stream"

static FILE *rtmp = NULL;


static int8_t
open_rtmp(void)
{
  char cmd[MAXLEN+1];
  char *args = NULL, *url = NULL;

  memset(&cmd, '\0', MAXLEN+1);
  if (NULL == (args = getenv("LEBINIOU_RTMP_FFMPEG_ARGS"))) {
    args = RTMP_FFMPEG_ARGS;
  }
  if (NULL == (url = getenv("LEBINIOU_RTMP_URL"))) {
    url = RTMP_URL;
  }

  g_snprintf(cmd, MAXLEN, "%s %s %s", FFMPEG, args, url);
  if (NULL == (rtmp = popen(cmd, "w"))) {
    xperror("popen");
  } else {
    VERBOSE(printf("[i] %s: opened stream to %s\n", __FILE__, url));
    VERBOSE(printf("[i] %s: ffmpeg args: '%s'\n", __FILE__, args));
  }

  return 1;
}


int8_t
create(Context_t *ctx)
{
  if (check_command(FFMPEG_CHECK) == -1) {
    printf("[!] %s: ffmpeg binary not found, plugin disabled\n", __FILE__);
    return 0;
  } else {
    return open_rtmp();
  }
}


void
destroy(Context_t *ctx)
{
  if (NULL != rtmp)
    if (-1 == pclose(rtmp)) {
      xperror("pclose");
    }
}


void
run(Context_t *ctx)
{
  uint8_t *data;
  char buff[MAXLEN+1];
  size_t res;

  /* get picture */
  data = export_RGB_active_buffer(ctx, 1);

  memset(&buff, '\0', MAXLEN+1);
  g_snprintf(buff, MAXLEN, "P6  %d %d 255\n", WIDTH, HEIGHT);

  /* PPM header */
  res = fwrite((const void *)&buff, sizeof(char), strlen(buff), rtmp);
  if (res != strlen(buff)) {
    fprintf(stderr, "[!] %s:write_header: short write (%zu of %d)\n", __FILE__, res, (int)strlen(buff));
    exit(1);
  }

  /* PPM data */
  res = fwrite((const void *)data, sizeof(Pixel_t), RGB_BUFFSIZE, rtmp);
  xfree(data);
  if (res != RGB_BUFFSIZE) {
    fprintf(stderr, "[!] %s:write_image: short write (%zu of %li)\n", __FILE__, res, RGB_BUFFSIZE);
    exit(1);
  }

  fflush(rtmp);
}
