ff-save.c 24.6 KB
Newer Older
1 2 3 4 5
/* This file is an image processing operation for GEGL
 *
 * GEGL is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
6
 * version 3 of the License, or (at your option) any later version.
7 8 9 10 11 12 13
 *
 * GEGL 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
14
 * License along with GEGL; if not, see <http://www.gnu.org/licenses/>.
15 16 17
 *
 * Copyright 2003,2004,2007 Øyvind Kolås <pippin@gimp.org>
 */
18 19

#include "config.h"
Martin Nordholts's avatar
Martin Nordholts committed
20 21 22

#include <stdlib.h>

23 24
#include <glib/gi18n-lib.h>

25
#ifdef GEGL_PROPERTIES
26

27
property_string (path, _("File"), "/tmp/fnord.ogv")
28
    description (_("Target path and filename, use '-' for stdout."))
29
property_string (video_codec,   _("Audio codec"),   "auto")
30
property_int (video_bit_rate, _("video bitrate"), 810000)
31
    value_range (0.0, 500000000.0)
32 33 34 35 36 37 38 39 40 41
#if 0
property_double (video_bit_rate_tolerance, _("video bitrate"), 1000.0)
property_int    (video_global_quality, _("global quality"), 255)
property_int    (compression_level,    _("compression level"), 255)
property_int    (noise_reduction,      _("noise reduction strength"), 0)
property_int    (gop_size,             _("the number of frames in a group of pictures, 0 for keyframe only"), 16)
property_int    (key_int_min,          _("the minimum number of frames in a group of pictures, 0 for keyframe only"), 1)
property_int    (max_b_frames,         _("maximum number of consequetive b frames"), 3)
#endif
property_double (frame_rate, _("Frames/second"), 25.0)
42
    value_range (0.0, 100.0)
43

44
property_string (audio_codec, _("Audio codec"), "auto")
45 46
property_int (audio_sample_rate, _("Audio sample rate"), 48000)
property_int (audio_bit_rate, _("Audio bitrate"), 810000)
47

48 49
property_audio (audio, _("audio"), 0)

50 51
#else

52
#define GEGL_OP_SINK
53
#define GEGL_OP_C_SOURCE ff-save.c
54

55
/* bitrot cruft */
56 57 58
#define FF_API_OLD_ENCODE_AUDIO 1
#define FF_API_DUMP_FORMAT  1

59
#include "gegl-op.h"
60

61
#include <libavformat/avformat.h>
62 63 64 65
#include <libavcodec/avcodec.h>
#include <libavutil/avutil.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
66

67 68 69 70 71 72 73 74 75 76 77 78
#define MAX_AUDIO_CHANNELS  6
#define MAX_AUDIO_SAMPLES   2048

typedef struct AudioFrame {
  //int64_t          pts;
  float            data[MAX_AUDIO_CHANNELS][MAX_AUDIO_SAMPLES];
  int              channels;
  int              sample_rate;
  int              len;
  long             pos;
} AudioFrame;

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
typedef struct
{
  gdouble    frame;
  gdouble    frames;
  gdouble    width;
  gdouble    height;
  GeglBuffer *input;

  AVOutputFormat *fmt;
  AVFormatContext *oc;
  AVStream *video_st;

  AVFrame  *picture, *tmp_picture;
  uint8_t  *video_outbuf;
  int       frame_count, video_outbuf_size;

95 96 97 98
    /** the rest is for audio handling within oxide, note that the interface
     * used passes all used functions in the oxide api through the reg_sym api
     * of gggl, this means that the ops should be usable by other applications
     * using gggl directly,. without needing to link with the oxide library
99 100 101
     */
  AVStream *audio_st;

Kevin Cozens's avatar
Kevin Cozens committed
102
  void     *oxide_audio_instance;
103
  /*< non NULL audio_query,. means audio present */
104

105 106 107 108 109 110
  int32_t (*oxide_audio_query) (void *audio_instance,
                                uint32_t * sample_rate,
                                uint32_t * bits,
                                uint32_t * channels,
                                uint32_t * fragment_samples,
                                uint32_t * fragment_size);
111

112 113 114
  /* get audio samples for the current video frame, this should provide all
   * audiosamples associated with the frame, frame centering on audio stream is
   * undefined (FIXME:<<)
115 116
   */

117
  int32_t (*oxide_audio_get_fragment) (void *audio_instance, uint8_t * buf);
118 119 120 121 122 123 124 125 126 127 128 129

  uint32_t  sample_rate;
  uint32_t  bits;
  uint32_t  channels;
  uint32_t  fragment_samples;
  uint32_t  fragment_size;

  uint8_t  *fragment;

  int       buffer_size;
  int       buffer_read_pos;
  int       buffer_write_pos;
130 131
  uint8_t  *buffer; 
                   
132 133 134 135
  int       audio_outbuf_size;
  int       audio_input_frame_size;
  int16_t  *samples;
  uint8_t  *audio_outbuf;
136 137 138 139

  GList *audio_track;
  long   audio_pos;
  long   audio_read_pos;
140 141
} Priv;

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
static void
clear_audio_track (GeglProperties *o)
{
  Priv *p = (Priv*)o->user_data;
  while (p->audio_track)
    {
      g_free (p->audio_track->data);
      p->audio_track = g_list_remove (p->audio_track, p->audio_track->data);
    }
}

static void get_sample_data (Priv *p, long sample_no, float *left, float *right)
{
  int to_remove = 0;
  GList *l;
  l = p->audio_track;
  if (sample_no < 0)
    return;
  for (; l; l = l->next)
  {
    AudioFrame *af = l->data;
    if (sample_no > af->pos + af->len)
    {
      to_remove ++;
    }

    if (af->pos <= sample_no &&
        sample_no < af->pos + af->len)
      {
        int i = sample_no - af->pos;
        *left  = af->data[0][i];
        if (af->channels == 1)
          *right = af->data[0][i];
        else
          *right = af->data[1][i];

	if (to_remove)  /* consuming audiotrack */
        {
          again:
          for (l = p->audio_track; l; l = l->next)
          {
            AudioFrame *af = l->data;
            if (sample_no > af->pos + af->len)
            {
              p->audio_track = g_list_remove (p->audio_track, af);
              goto again;
            }
          }
        }
        return;
      }
  }
  //fprintf (stderr, "didn't find audio sample\n");
  *left  = 0;
  *right = 0;
}
198

199
#if 0
200 201
static void
buffer_open (GeglProperties *o, int size);
202
#endif
203

Kevin Cozens's avatar
Kevin Cozens committed
204
static void
205
init (GeglProperties *o)
206
{
Kevin Cozens's avatar
Kevin Cozens committed
207
  static gint inited = 0; /*< this is actually meant to be static, only to be done once */
208
  Priv       *p = (Priv*)o->user_data;
Kevin Cozens's avatar
Kevin Cozens committed
209 210

  if (p == NULL)
211
    {
Kevin Cozens's avatar
Kevin Cozens committed
212
      p = g_new0 (Priv, 1);
213
      o->user_data = (void*) p;
214 215 216 217 218 219 220 221 222
    }

  if (!inited)
    {
      av_register_all ();
      avcodec_register_all ();
      inited = 1;
    }

223 224 225 226
  clear_audio_track (o);
  p->audio_pos = 0;
  p->audio_read_pos = 0;

227
#ifndef DISABLE_AUDIO
228 229 230 231
  //p->oxide_audio_instance = gggl_op_sym (op, "oxide_audio_instance");
  //p->oxide_audio_query = gggl_op_sym (op, "oxide_audio_query()");
  //p->oxide_audio_get_fragment =
    //gggl_op_sym (op, "oxide_audio_get_fragment()");
232 233 234 235 236 237 238 239 240 241 242 243 244

  if (p->oxide_audio_instance && p->oxide_audio_query)
    {
      p->oxide_audio_query (p->oxide_audio_instance,
                            &p->sample_rate,
                            &p->bits,
                            &p->channels,
                            &p->fragment_samples, &p->fragment_size);

      /* FIXME: for now, the buffer is set to a size double that of a oxide
       * provided fragment,. should be enough no matter how things are handled,
       * but it should also be more than needed,. find out exact amount needed later
       */
245
#if 0
246 247
      if (!p->buffer)
        {
Kevin Cozens's avatar
Kevin Cozens committed
248
          int size =
249 250
            (p->sample_rate / o->frame_rate) * p->channels * (p->bits / 8) * 2;
          buffer_open (o, size);
251
        }
252
#endif
253
      if (!p->fragment)
254
        p->fragment = calloc (1, p->fragment_size);
255 256 257 258
    }
#endif
}

Kevin Cozens's avatar
Kevin Cozens committed
259 260 261 262 263 264
static void close_video       (Priv            *p,
                               AVFormatContext *oc,
                               AVStream        *st);
void        close_audio       (Priv            *p,
                               AVFormatContext *oc,
                               AVStream        *st);
265 266
static int  tfile             (GeglProperties  *o);
static void write_video_frame (GeglProperties  *o,
Kevin Cozens's avatar
Kevin Cozens committed
267 268
                               AVFormatContext *oc,
                               AVStream        *st);
269
static void write_audio_frame (GeglProperties      *o,
Kevin Cozens's avatar
Kevin Cozens committed
270 271
                               AVFormatContext *oc,
                               AVStream        *st);
272 273 274

#define STREAM_FRAME_RATE 25    /* 25 images/s */

275
#ifndef DISABLE_AUDIO
276 277
/* add an audio output stream */
static AVStream *
278
add_audio_stream (GeglProperties *o, AVFormatContext * oc, int codec_id)
279
{
280
  //Priv     *p = (Priv*)o->user_data;
281 282 283
  AVCodecContext *c;
  AVStream *st;

284 285
  //p = NULL;
  st = avformat_new_stream (oc, NULL);
286 287 288 289 290 291 292 293
  if (!st)
    {
      fprintf (stderr, "Could not alloc stream\n");
      exit (1);
    }

  c = st->codec;
  c->codec_id = codec_id;
294
  c->codec_type = AVMEDIA_TYPE_AUDIO;
295 296 297 298 299 300

  c->bit_rate = 64000;
  c->sample_rate = 44100;
  c->channels = 2;
  return st;
}
301
#endif
302 303 304 305 306 307

static void
open_audio (Priv * p, AVFormatContext * oc, AVStream * st)
{
  AVCodecContext *c;
  AVCodec  *codec;
308
  int i;
309 310 311 312 313 314 315 316 317 318

  c = st->codec;

  /* find the audio encoder */
  codec = avcodec_find_encoder (c->codec_id);
  if (!codec)
    {
      fprintf (stderr, "codec not found\n");
      exit (1);
    }
319 320 321
  c->bit_rate = 64000;
  c->sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
  if(1)if (codec->sample_fmts) {
    int i;
    for (i = 0; codec->sample_fmts[i]; i++)
    {
      if (codec->sample_fmts[i] == AV_SAMPLE_FMT_FLT)
        fprintf (stderr, "supports interleaved float!\n");
      if (codec->sample_fmts[i] == AV_SAMPLE_FMT_S16)
        fprintf (stderr, "supports interleaved s16!\n");
      if (codec->sample_fmts[i] == AV_SAMPLE_FMT_S16P)
        fprintf (stderr, "supports planar s16!\n");
      if (codec->sample_fmts[i] == AV_SAMPLE_FMT_FLTP)
        fprintf (stderr, "supports planar float!\n");
    }
  }

337 338 339 340
  c->sample_rate = 44100;
  c->channel_layout = AV_CH_LAYOUT_STEREO;
  c->channels = 2;

341

342 343 344 345 346 347 348 349 350 351
  if (codec->supported_samplerates)
  {
    c->sample_rate = codec->supported_samplerates[0];
    for (i = 0; codec->supported_samplerates[i]; i++)
      if (codec->supported_samplerates[i] == 44100)
         c->sample_rate = 44100;
  }
  st->time_base = (AVRational){1, c->sample_rate};

  c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; // ffmpeg AAC is not quite stable yet
352 353

  /* open it */
354
  if (avcodec_open2 (c, codec, NULL) < 0)
355 356 357 358 359 360 361 362 363 364 365
    {
      fprintf (stderr, "could not open codec\n");
      exit (1);
    }

  p->audio_outbuf_size = 10000;
  p->audio_outbuf = malloc (p->audio_outbuf_size);

  p->samples = malloc (p->audio_input_frame_size * 2 * c->channels);
}

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

/* XXX: rewrite  */
static AVFrame *alloc_audio_frame(enum AVSampleFormat sample_fmt,
                                  uint64_t channel_layout,
                                  int sample_rate, int nb_samples)
{
  AVFrame *frame = av_frame_alloc();
  int ret;

  if (!frame) {
      fprintf(stderr, "Error allocating an audio frame\n");
      exit(1);
  }

  frame->format         = sample_fmt;
  frame->channel_layout = channel_layout;
  frame->sample_rate    = sample_rate;
  frame->nb_samples     = nb_samples;

  if (nb_samples) {
      ret = av_frame_get_buffer(frame, 0);
      if (ret < 0) {
          fprintf(stderr, "Error allocating an audio buffer\n");
          exit(1);
      }
  }
  return frame;
}

395
void
396
write_audio_frame (GeglProperties *o, AVFormatContext * oc, AVStream * st)
397
{
398
  Priv *p = (Priv*)o->user_data;
399 400 401 402 403

  AVCodecContext *c;
  AVPacket  pkt;
  av_init_packet (&pkt);

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  /* first we add incoming frames audio samples */
  {
    int i;
    AudioFrame *af = g_malloc0 (sizeof (AudioFrame));
    af->channels = 2; //o->audio->channels;
    af->len = o->audio->samples;
    for (i = 0; i < af->len; i++)
      {
        af->data[0][i] = o->audio->left[i];
        af->data[1][i] = o->audio->right[i];
      }
    af->pos = p->audio_pos;
    p->audio_pos += af->len;
    p->audio_track = g_list_append (p->audio_track, af);
  }

  /* then we encode as much as we can in a loop using the codec frame size */
421
  c = st->codec;
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  
  fprintf (stderr, "%li %i %i\n",
           p->audio_pos, p->audio_read_pos, c->frame_size);
  while (p->audio_pos - p->audio_read_pos > c->frame_size)
  {
    long i;
    AVFrame *frame = alloc_audio_frame (c->sample_fmt, c->channel_layout,
                                        c->sample_rate, c->frame_size);

    for (i = 0; i < c->frame_size; i++)
    {
      float left = 0, right = 0;
      get_sample_data (p, i + p->audio_read_pos, &left, &right);
//    fprintf (stderr, "[%f %f]\n", left, right);
    }

    av_frame_free (&frame);
    p->audio_read_pos += c->frame_size;
  }
441

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
#if 0
  if(1)switch (c->sample_fmt)
  {
    case AV_SAMPLE_FMT_FLT:
      fprintf (stderr, "f\n");
      break;
    case AV_SAMPLE_FMT_FLTP:
      fprintf (stderr, "fp\n");
      break;
    case AV_SAMPLE_FMT_S16:
      fprintf (stderr, "s16\n");
      break;
    case AV_SAMPLE_FMT_S16P:
      fprintf (stderr, "s16p\n");
      break;
    case AV_SAMPLE_FMT_S32:
    case AV_SAMPLE_FMT_S32P:
      fprintf (stderr, "s32\n");
      break;
  }
#endif
  //fprintf (stderr, "asdfasdfadf\n");

  fprintf (stderr, "audio codec wants: %i samples\n", c->frame_size);

  p->audio_input_frame_size = c->frame_size;
  //fprintf (stderr, "going to grab %i %i\n", p->fragment_size, o->audio->samples);
469
#if 0
470 471 472 473 474
  if (p->oxide_audio_get_fragment (p->oxide_audio_instance,
                                   p->fragment) == (signed) p->fragment_size)
    {
      buffer_write (p, p->fragment, p->fragment_size);
    }
475
#endif
476

477
#if 0
478 479 480 481 482 483 484 485 486
  while (buffer_used (p) >= p->audio_input_frame_size * 2 * c->channels)
    {
      buffer_read (p, (uint8_t *) p->samples,
                   p->audio_input_frame_size * 2 * c->channels);

      pkt.size = avcodec_encode_audio (c, p->audio_outbuf,
                                       p->audio_outbuf_size, p->samples);

      pkt.pts = c->coded_frame->pts;
487
      pkt.flags |= AV_PKT_FLAG_KEY;
488 489 490 491 492 493 494 495 496
      pkt.stream_index = st->index;
      pkt.data = p->audio_outbuf;

      if (av_write_frame (oc, &pkt) != 0)
        {
          fprintf (stderr, "Error while writing audio frame\n");
          exit (1);
        }
    }
497
#endif
498 499
}

500
/*p->audio_get_frame (samples, audio_input_frame_size, c->channels);*/
501 502 503 504 505 506 507 508 509 510 511 512

void
close_audio (Priv * p, AVFormatContext * oc, AVStream * st)
{
  avcodec_close (st->codec);

  av_free (p->samples);
  av_free (p->audio_outbuf);
}

/* add a video output stream */
static AVStream *
513
add_video_stream (GeglProperties *o, AVFormatContext * oc, int codec_id)
514
{
515
  Priv *p = (Priv*)o->user_data;
516 517 518 519

  AVCodecContext *c;
  AVStream *st;

520
  st = avformat_new_stream (oc, NULL);
521 522
  if (!st)
    {
523
      fprintf (stderr, "Could not alloc stream %p %p %i\n", o, oc, codec_id);
524 525 526 527 528
      exit (1);
    }

  c = st->codec;
  c->codec_id = codec_id;
529
  c->codec_type = AVMEDIA_TYPE_VIDEO;
530 531

  /* put sample propeters */
532
  c->bit_rate = o->video_bit_rate;
533 534 535 536
  /* resolution must be a multiple of two */
  c->width = p->width;
  c->height = p->height;
  /* frames per second */
537
  st->time_base =(AVRational){1, o->frame_rate};
538 539
  c->time_base = st->time_base;
  c->pix_fmt = AV_PIX_FMT_YUV420P;
540

541
  c->gop_size = 12;             /* emit one intra frame every twelve frames at most */
542
  if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO)
543
    {
544
      c->max_b_frames = 2;
545
    }
546 547
  if (c->codec_id == AV_CODEC_ID_H264)
   {
548 549 550 551 552 553 554
#if 1
     c->qcompress = 0.6;  // qcomp=0.6
     c->me_range = 16;    // me_range=16
     c->gop_size = 250;   // g=250

     c->max_b_frames = 3; // bf=3
#if 0
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
     c->coder_type = 1;  // coder = 1
     c->flags|=CODEC_FLAG_LOOP_FILTER;   // flags=+loop
     c->me_cmp|= 1;  // cmp=+chroma, where CHROMA = 1
     //c->partitions|=X264_PART_I8X8+X264_PART_I4X4+X264_PART_P8X8+X264_PART_B8X8; // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
     c->me_subpel_quality = 7;   // subq=7
     c->keyint_min = 25; // keyint_min=25
     c->scenechange_threshold = 40;  // sc_threshold=40
     c->i_quant_factor = 0.71; // i_qfactor=0.71
     c->b_frame_strategy = 1;  // b_strategy=1
     c->qmin = 10;   // qmin=10
     c->qmax = 51;   // qmax=51
     c->max_qdiff = 4;   // qdiff=4
     c->refs = 3;    // refs=3
     //c->directpred = 1;  // directpred=1
     c->flags |= CODEC_FLAG_GLOBAL_HEADER;
     c->trellis = 1; // trellis=1
     //c->flags2|=AV_CODEC_FLAG2_BPYRAMID|AV_CODEC_FLAG2_MIXED_REFS|AV_CODEC_FLAG2_WPRED+CODEC_FLAG2_8X8DCT+CODEC_FLAG2_FASTPSKIP;  // flags2=+bpyramid+mixed_refs+wpred+dct8x8+fastpskip
     //c->weighted_p_pred = 2; // wpredp=2

// libx264-main.ffpreset preset
     //c->flags2|=CODEC_FLAG2_8X8DCT;c->flags2^=CODEC_FLAG2_8X8DCT;
576 577
#endif
#endif
578 579
   }

580 581 582
   if (oc->oformat->flags & AVFMT_GLOBALHEADER)
     c->flags |= CODEC_FLAG_GLOBAL_HEADER;

583

584 585
/*    if (!strcmp (oc->oformat->name, "mp4") ||
          !strcmp (oc->oformat->name, "3gp"))
586
    c->flags |= CODEC_FLAG_GLOBAL_HEADER;
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    */
  return st;
}


static AVFrame *
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;
602
  size = avpicture_get_size (pix_fmt, width, height + 1);
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
  picture_buf = malloc (size);
  if (!picture_buf)
    {
      av_free (picture);
      return NULL;
    }
  avpicture_fill ((AVPicture *) picture, picture_buf, pix_fmt, width, height);
  return picture;
}

static void
open_video (Priv * p, 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, "codec not found\n");
      exit (1);
    }

629

630
  /* open the codec */
631
  if (avcodec_open2 (c, codec, NULL) < 0)
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    {
      fprintf (stderr, "could not open codec\n");
      exit (1);
    }

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

  /* allocate the encoded raw picture */
  p->picture = alloc_picture (c->pix_fmt, c->width, c->height);
  if (!p->picture)
    {
      fprintf (stderr, "Could not allocate picture\n");
      exit (1);
    }

  /* if the output format is not YUV420P, then a temporary YUV420P
     picture is needed too. It is then converted to the required
     output format */
  p->tmp_picture = NULL;
  if (c->pix_fmt != PIX_FMT_RGB24)
    {
      p->tmp_picture = alloc_picture (PIX_FMT_RGB24, c->width, c->height);
      if (!p->tmp_picture)
        {
          fprintf (stderr, "Could not allocate temporary picture\n");
          exit (1);
        }
    }
}

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

#include "string.h"

/* prepare a dummy image */
static void
687
fill_rgb_image (GeglProperties *o,
Kevin Cozens's avatar
Kevin Cozens committed
688
                AVFrame *pict, int frame_index, int width, int height)
689
{
690
  Priv     *p = (Priv*)o->user_data;
691
  GeglRectangle rect={0,0,width,height};
692
  gegl_buffer_get (p->input, &rect, 1.0, babl_format ("R'G'B' u8"), pict->data[0], GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
693 694 695
}

static void
696
write_video_frame (GeglProperties *o,
Kevin Cozens's avatar
Kevin Cozens committed
697
                   AVFormatContext *oc, AVStream *st)
698
{
699
  Priv     *p = (Priv*)o->user_data;
700 701 702 703 704 705 706 707
  int       out_size, ret;
  AVCodecContext *c;
  AVFrame  *picture_ptr;

  c = st->codec;

  if (c->pix_fmt != PIX_FMT_RGB24)
    {
708
      struct SwsContext *img_convert_ctx;
709
      fill_rgb_image (o, p->tmp_picture, p->frame_count, c->width,
710
                      c->height);
711

712 713
      img_convert_ctx = sws_getContext(c->width, c->height, PIX_FMT_RGB24,
                                       c->width, c->height, c->pix_fmt,
714 715 716 717 718 719 720 721 722
                                       SWS_BICUBIC, NULL, NULL, NULL);

      if (img_convert_ctx == NULL)
        {
          fprintf(stderr, "ff_save: Cannot initialize conversion context.");
        }
      else
        {
          sws_scale(img_convert_ctx,
723
                    (void*)p->tmp_picture->data,
724 725 726 727 728
                    p->tmp_picture->linesize,
                    0,
                    c->height,
                    p->picture->data,
                    p->picture->linesize);
729 730 731
         p->picture->format = c->pix_fmt;
         p->picture->width = c->width;
         p->picture->height = c->height;
732
        }
733 734 735
    }
  else
    {
736
      fill_rgb_image (o, p->picture, p->frame_count, c->width, c->height);
737
    }
738

739
  picture_ptr = p->picture;
740
  picture_ptr->pts = p->frame_count;
741 742 743 744 745 746 747 748

  if (oc->oformat->flags & AVFMT_RAWPICTURE)
    {
      /* raw video case. The API will change slightly in the near
         future for that */
      AVPacket  pkt;
      av_init_packet (&pkt);

749
      pkt.flags |= AV_PKT_FLAG_KEY;
750 751 752
      pkt.stream_index = st->index;
      pkt.data = (uint8_t *) picture_ptr;
      pkt.size = sizeof (AVPicture);
753 754
      pkt.pts = picture_ptr->pts;
      av_packet_rescale_ts (&pkt, c->time_base, st->time_base);
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771

      ret = av_write_frame (oc, &pkt);
    }
  else
    {
      /* encode the image */
      out_size =
        avcodec_encode_video (c,
                              p->video_outbuf,
                              p->video_outbuf_size, picture_ptr);

      /* if zero size, it means the image was buffered */
      if (out_size != 0)
        {
          AVPacket  pkt;
          av_init_packet (&pkt);
          if (c->coded_frame->key_frame)
772
            pkt.flags |= AV_PKT_FLAG_KEY;
773 774 775
          pkt.stream_index = st->index;
          pkt.data = p->video_outbuf;
          pkt.size = out_size;
776 777
          pkt.pts = picture_ptr->pts;
          av_packet_rescale_ts (&pkt, c->time_base, st->time_base);
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
          /* write the compressed frame in the media file */
          ret = av_write_frame (oc, &pkt);
        }
      else
        {
          ret = 0;
        }
    }
  if (ret != 0)
    {
      fprintf (stderr, "Error while writing video frame\n");
      exit (1);
    }
  p->frame_count++;
}

static int
795
tfile (GeglProperties *o)
796
{
797
  Priv *p = (Priv*)o->user_data;
798

799
  p->fmt = av_guess_format (NULL, o->path, NULL);
800 801 802 803 804
  if (!p->fmt)
    {
      fprintf (stderr,
               "ff_save couldn't deduce outputformat from file extension: using MPEG.\n%s",
               "");
805
      p->fmt = av_guess_format ("mpeg", NULL, NULL);
806
    }
807
  p->oc = avformat_alloc_context ();
808 809 810 811 812 813 814 815
  if (!p->oc)
    {
      fprintf (stderr, "memory error\n%s", "");
      return -1;
    }

  p->oc->oformat = p->fmt;

816
  snprintf (p->oc->filename, sizeof (p->oc->filename), "%s", o->path);
817 818 819 820 821 822

  p->video_st = NULL;
  p->audio_st = NULL;

  if (p->fmt->video_codec != CODEC_ID_NONE)
    {
823
      p->video_st = add_video_stream (o, p->oc, p->fmt->video_codec);
824
    }
825
  if (p->fmt->audio_codec != CODEC_ID_NONE)
826
    {
827
     p->audio_st = add_audio_stream (o, p->oc, p->fmt->audio_codec);
828 829
    }

830
  av_dump_format (p->oc, 0, o->path, 1);
831 832 833 834 835 836

  if (p->video_st)
    open_video (p, p->oc, p->video_st);
  if (p->audio_st)
    open_audio (p, p->oc, p->audio_st);

837
  if (avio_open (&p->oc->pb, o->path, AVIO_FLAG_WRITE) < 0)
838
    {
839
      fprintf (stderr, "couldn't open '%s'\n", o->path);
840 841 842
      return -1;
    }

843
  avformat_write_header (p->oc, NULL);
844 845 846
  return 0;
}

847
#if 0
848
static int
849
filechanged (GeglOpOperation *op, const char *att)
850 851 852 853
{
  init (op);
  return 0;
}
854
#endif
855

Kevin Cozens's avatar
Kevin Cozens committed
856 857 858
static gboolean
process (GeglOperation       *operation,
         GeglBuffer          *input,
859 860
         const GeglRectangle *result,
         gint                 level)
Kevin Cozens's avatar
Kevin Cozens committed
861 862
{
  static gint inited = 0;
863 864
  GeglProperties *o = GEGL_PROPERTIES (operation);
  Priv       *p = (Priv*)o->user_data;
Kevin Cozens's avatar
Kevin Cozens committed
865 866 867 868 869

  g_assert (input);

  if (p == NULL)
    init (o);
870
  p = (Priv*)o->user_data;
Kevin Cozens's avatar
Kevin Cozens committed
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891

  p->width = result->width;
  p->height = result->height;
  p->input = input;

  if (!inited)
    {
      tfile (o);
      inited = 1;
    }

  write_video_frame (o, p->oc, p->video_st);
  if (p->audio_st)
    write_audio_frame (o, p->oc, p->audio_st);

  return  TRUE;
}

static void
finalize (GObject *object)
{
892 893
  GeglProperties *o = GEGL_PROPERTIES (object);
  if (o->user_data)
Kevin Cozens's avatar
Kevin Cozens committed
894
    {
895
      Priv *p = (Priv*)o->user_data;
896
#if 0
897
    buffer_close (o);
898
#endif
899

Kevin Cozens's avatar
Kevin Cozens committed
900 901 902 903 904 905 906 907
    if (p->oc)
      {
        if (p->video_st)
          close_video (p, p->oc, p->video_st);
        if (p->audio_st)
          close_audio (p, p->oc, p->audio_st);

        av_write_trailer (p->oc);
908
#if 0
909 910
{
        //gint i;
Kevin Cozens's avatar
Kevin Cozens committed
911 912 913 914
        for (i = 0; i < p->oc->nb_streams; i++)
          {
            av_freep (&p->oc->streams[i]);
          }
915
}
916
#endif
Kevin Cozens's avatar
Kevin Cozens committed
917

918 919
        avio_closep (&p->oc->pb);
        avformat_free_context (p->oc);
Kevin Cozens's avatar
Kevin Cozens committed
920
      }
921

922 923
      g_free (o->user_data);
      o->user_data = NULL;
Kevin Cozens's avatar
Kevin Cozens committed
924 925 926 927 928 929 930
    }

  G_OBJECT_CLASS (g_type_class_peek_parent (G_OBJECT_GET_CLASS (object)))->finalize (object);
}


static void
931
gegl_op_class_init (GeglOpClass *klass)
Kevin Cozens's avatar
Kevin Cozens committed
932 933 934 935 936 937 938 939 940 941 942 943
{
  GeglOperationClass     *operation_class;
  GeglOperationSinkClass *sink_class;

  G_OBJECT_CLASS (klass)->finalize = finalize;

  operation_class = GEGL_OPERATION_CLASS (klass);
  sink_class      = GEGL_OPERATION_SINK_CLASS (klass);

  sink_class->process = process;
  sink_class->needs_full = TRUE;

944 945 946 947 948
  gegl_operation_class_set_keys (operation_class,
    "name"        , "gegl:ff-save",
    "categories"  , "output:video",
    "description" , _("FFmpeg video output sink"),
    NULL);
Kevin Cozens's avatar
Kevin Cozens committed
949 950
}

951
#endif