summaryrefslogtreecommitdiff
path: root/ext/divx/gstdivxenc.c
blob: cbd3159ef8a64baf03bc30322ff8f3609c51087c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
/* GStreamer divx encoder plugin
 * Copyright (C) 2003 Ronald Bultje <rbultje@ronald.bitfreak.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "config.h"
#endif

#include <string.h>
#include "gstdivxenc.h"
#include <gst/video/video.h>
#include <encore2.h>

/* elementfactory information */
GstElementDetails gst_divxenc_details = {
  "Divx encoder",
  "Codec/Video/Encoder",
  "Commercial",
  "Divx encoder based on divxencore",
  VERSION,
  "Ronald Bultje <rbultje@ronald.bitfreak.net>",
  "(C) 2003",
};

GST_PAD_TEMPLATE_FACTORY(sink_template,
  "sink",
  GST_PAD_SINK,
  GST_PAD_ALWAYS,
  gst_caps_new(
    "divxdec_src",
    "video/x-raw-yuv",
      GST_VIDEO_YUV_PAD_TEMPLATE_PROPS(
        GST_PROPS_LIST(
          GST_PROPS_FOURCC(GST_MAKE_FOURCC('R','G','B',' ')),
          GST_PROPS_FOURCC(GST_MAKE_FOURCC('I','4','2','0')),
          GST_PROPS_FOURCC(GST_MAKE_FOURCC('Y','U','Y','2')),
          GST_PROPS_FOURCC(GST_MAKE_FOURCC('Y','V','1','2')),
          GST_PROPS_FOURCC(GST_MAKE_FOURCC('U','Y','V','Y'))
        )
      )
  ),
  gst_caps_new(
    "divxdec_src_rgb1",
    "video/x-raw-rgb",
      GST_VIDEO_RGB_PAD_TEMPLATE_PROPS_24_32
  ),
  gst_caps_new(
    "divxdec_src_rgb2",
    "video/x-raw-rgb",
      GST_VIDEO_RGB_PAD_TEMPLATE_PROPS_15_16
  )
)

GST_PAD_TEMPLATE_FACTORY(src_template,
  "src",
  GST_PAD_SRC,
  GST_PAD_ALWAYS,
  GST_CAPS_NEW(
    "divxenc_sink",
    "video/x-divx",
      "divxversion", GST_PROPS_INT(5),
      "width",       GST_PROPS_INT_RANGE(0, G_MAXINT),
      "height",      GST_PROPS_INT_RANGE(0, G_MAXINT),
      "framerate",   GST_PROPS_FLOAT_RANGE(0, G_MAXFLOAT)
  )
)


/* DivxEnc signals and args */
enum {
  FRAME_ENCODED,
  LAST_SIGNAL
};

enum {
  ARG_0,
  ARG_BITRATE,
  ARG_MAXKEYINTERVAL,
  ARG_BUFSIZE,
  ARG_QUALITY
};


static void             gst_divxenc_class_init   (GstDivxEncClass *klass);
static void             gst_divxenc_init         (GstDivxEnc      *divxenc);
static void             gst_divxenc_dispose      (GObject         *object);
static void             gst_divxenc_chain        (GstPad          *pad,
                                                  GstBuffer       *buf);
static GstPadLinkReturn gst_divxenc_connect      (GstPad          *pad,
                                                  GstCaps         *vscapslist);

/* properties */
static void             gst_divxenc_set_property (GObject         *object,
                                                  guint            prop_id,
                                                  const GValue    *value,
                                                  GParamSpec      *pspec);
static void             gst_divxenc_get_property (GObject         *object,
                                                  guint            prop_id,
                                                  GValue          *value,
                                                  GParamSpec      *pspec);

static GstElementClass *parent_class = NULL;
static guint gst_divxenc_signals[LAST_SIGNAL] = { 0 };


static gchar *
gst_divxenc_error (int errorcode)
{
  gchar *error;

  switch (errorcode) {
    case ENC_BUFFER:
      error = "Invalid buffer";
      break;
    case ENC_FAIL:
      error = "Operation failed";
      break;
    case ENC_OK:
      error = "No error";
      break;
    case ENC_MEMORY:
      error = "Bad memory location";
      break;
    case ENC_BAD_FORMAT:
      error = "Invalid format";
      break;
    case ENC_INTERNAL:
      error = "Internal error";
      break;
    default:
      error = "Unknown error";
      break;
  }

  return error;
}


GType
gst_divxenc_get_type(void)
{
  static GType divxenc_type = 0;

  if (!divxenc_type)
  {
    static const GTypeInfo divxenc_info = {
      sizeof(GstDivxEncClass),
      NULL,
      NULL,
      (GClassInitFunc) gst_divxenc_class_init,
      NULL,
      NULL,
      sizeof(GstDivxEnc),
      0,
      (GInstanceInitFunc) gst_divxenc_init,
    };
    divxenc_type = g_type_register_static(GST_TYPE_ELEMENT,
                                          "GstDivxEnc",
                                          &divxenc_info, 0);
  }
  return divxenc_type;
}


static void
gst_divxenc_class_init (GstDivxEncClass *klass)
{
  GstElementClass *gstelement_class;
  GObjectClass *gobject_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;

  parent_class = g_type_class_ref(GST_TYPE_ELEMENT);

  g_object_class_install_property(G_OBJECT_CLASS(klass), ARG_BITRATE,
    g_param_spec_ulong("bitrate","Bitrate",
                       "Target video bitrate",
                       0,G_MAXULONG,0,G_PARAM_READWRITE));

  g_object_class_install_property(G_OBJECT_CLASS(klass), ARG_MAXKEYINTERVAL,
    g_param_spec_int("max_key_interval","Max. Key Interval",
                     "Maximum number of frames between two keyframes",
                     0,G_MAXINT,0,G_PARAM_READWRITE));

  g_object_class_install_property(G_OBJECT_CLASS(klass), ARG_BUFSIZE,
    g_param_spec_ulong("buffer_size", "Buffer Size",
                       "Size of the video buffers",
                       0,G_MAXULONG,0,G_PARAM_READABLE));

  g_object_class_install_property(G_OBJECT_CLASS(klass), ARG_QUALITY,
    g_param_spec_int("quality", "Quality",
                     "Amount of Motion Estimation",
                     1,5,3,G_PARAM_READWRITE));

  gobject_class->set_property = gst_divxenc_set_property;
  gobject_class->get_property = gst_divxenc_get_property;

  gobject_class->dispose = gst_divxenc_dispose;

  gst_divxenc_signals[FRAME_ENCODED] =
    g_signal_new ("frame_encoded", G_TYPE_FROM_CLASS(klass),
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (GstDivxEncClass, frame_encoded),
                  NULL, NULL,
                  g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
}


static void
gst_divxenc_init (GstDivxEnc *divxenc)
{
  /* create the sink pad */
  divxenc->sinkpad = gst_pad_new_from_template(
                       GST_PAD_TEMPLATE_GET(sink_template),
                       "sink");
  gst_element_add_pad(GST_ELEMENT(divxenc), divxenc->sinkpad);

  gst_pad_set_chain_function(divxenc->sinkpad, gst_divxenc_chain);
  gst_pad_set_link_function(divxenc->sinkpad, gst_divxenc_connect);

  /* create the src pad */
  divxenc->srcpad = gst_pad_new_from_template(
                      GST_PAD_TEMPLATE_GET(src_template),
                      "src");
  gst_element_add_pad(GST_ELEMENT(divxenc), divxenc->srcpad);

  /* bitrate, etc. */
  divxenc->width = divxenc->height = divxenc->csp = divxenc->bitcnt = -1;
  divxenc->bitrate = 512 * 1024;
  divxenc->max_key_interval = -1; /* default - 2*fps */
  divxenc->buffer_size = 512 * 1024;
  divxenc->quality = 3;

  /* set divx handle to NULL */
  divxenc->handle = NULL;
}


static gboolean
gst_divxenc_setup (GstDivxEnc *divxenc)
{
  void *handle = NULL;
  SETTINGS output;
  DivXBitmapInfoHeader input;
  int ret;

  /* set it up */
  memset(&input, 0, sizeof(DivXBitmapInfoHeader));
  input.biSize = sizeof(DivXBitmapInfoHeader);
  input.biWidth = divxenc->width;
  input.biHeight = divxenc->height;
  input.biBitCount = divxenc->bitcnt;
  input.biCompression = divxenc->csp;

  memset(&output, 0, sizeof(SETTINGS));
  output.vbr_mode = 0;
  output.bitrate = divxenc->bitrate;
  output.quantizer = 0;
  output.use_bidirect = 0;
  output.input_clock = 0;
  output.input_frame_period = 1000000;
  output.internal_timescale = divxenc->fps * 1000000;
  output.max_key_interval = (divxenc->max_key_interval == -1) ?
                              (2 * divxenc->fps) :
                              divxenc->max_key_interval;
  output.key_frame_threshold = 0;
  output.vbv_bitrate = 0;
  output.vbv_size = 0;
  output.vbv_occupancy = 0;
  output.complexity_modulation = 0;
  output.deinterlace = 0;
  output.quality = divxenc->quality;
  output.data_partitioning = 0;
  output.quarter_pel = 0;
  output.use_gmc = 0; 
  output.psychovisual = 0;
  output.pv_strength_frame = 0;
  output.pv_strength_MB = 0;
  output.interlace_mode = 0;
  output.enable_crop = 0;
  output.enable_resize = 0;
  output.temporal_enable = 0;
  output.spatial_passes = 0;

  if ((ret = encore(&handle, ENC_OPT_INIT, &input, &output))) {
    gst_element_gerror(GST_ELEMENT(divxenc), GST_ERROR_UNKNOWN,
      g_strdup ("unconverted error, file a bug"),
      g_strdup_printf("Error setting up divx encoder: %s (%d)",
                      gst_divxenc_error(ret), ret));
    return FALSE;
  }

  divxenc->handle = handle;

  /* set buffer size to theoretical limit (see docs on divx.com) */
  divxenc->buffer_size = 6 * divxenc->width * divxenc->height;

  return TRUE;
}


static void
gst_divxenc_unset (GstDivxEnc *divxenc)
{
  if (divxenc->handle) {
    encore(divxenc->handle, ENC_OPT_RELEASE, NULL, NULL);
    divxenc->handle = NULL;
  }
}


static void
gst_divxenc_dispose (GObject *object)
{
  GstDivxEnc *divxenc = GST_DIVXENC(object);

  gst_divxenc_unset(divxenc);
}


static void
gst_divxenc_chain (GstPad    *pad,
                   GstBuffer *buf)
{
  GstDivxEnc *divxenc;
  GstBuffer *outbuf;
  ENC_FRAME xframe;
  ENC_RESULT xres;
  int ret;

  g_return_if_fail(pad != NULL);
  g_return_if_fail(GST_IS_PAD(pad));
  g_return_if_fail(buf != NULL);

  divxenc = GST_DIVXENC(GST_OBJECT_PARENT(pad));

  outbuf = gst_buffer_new_and_alloc(divxenc->buffer_size);
  GST_BUFFER_TIMESTAMP(outbuf) = GST_BUFFER_TIMESTAMP(buf);

  /* encode and so ... */
  xframe.image = GST_BUFFER_DATA(buf);
  xframe.bitstream = (void *) GST_BUFFER_DATA(outbuf);
  xframe.length = GST_BUFFER_MAXSIZE(outbuf);
  xframe.produce_empty_frame = 0;

  if ((ret = encore(divxenc->handle, ENC_OPT_ENCODE,
                    &xframe, &xres))) {
    gst_element_gerror(GST_ELEMENT(divxenc), GST_ERROR_UNKNOWN,
      g_strdup ("unconverted error, file a bug"),
      g_strdup_printf("Error encoding divx frame: %s (%d)",
                      gst_divxenc_error(ret), ret));
    gst_buffer_unref(buf);
    return;
  }

  GST_BUFFER_SIZE(outbuf) = xframe.length;
  if (xres.cType == 'I')
    GST_BUFFER_FLAG_SET(outbuf, GST_BUFFER_KEY_UNIT);

  /* go out, multiply! */
  gst_pad_push(divxenc->srcpad, outbuf);

  /* proclaim destiny */
  g_signal_emit(G_OBJECT(divxenc),gst_divxenc_signals[FRAME_ENCODED], 0);

  /* until the final judgement */
  gst_buffer_unref(buf);
}


static GstPadLinkReturn
gst_divxenc_connect (GstPad  *pad,
                     GstCaps *vscaps)
{
  GstDivxEnc *divxenc;
  GstCaps *caps;

  divxenc = GST_DIVXENC(gst_pad_get_parent (pad));

  /* if there's something old around, remove it */
  gst_divxenc_unset(divxenc);

  /* we are not going to act on variable caps */
  if (!GST_CAPS_IS_FIXED(vscaps))
    return GST_PAD_LINK_DELAYED;

  for (caps = vscaps; caps != NULL; caps = caps->next) {
    gint w,h,d;
    gfloat fps;
    guint32 fourcc;
    guint32 divx_cs;
    gint bitcnt = 0;
    gst_caps_get_int(caps, "width", &w);
    gst_caps_get_int(caps, "height", &h);
    gst_caps_get_float(caps, "framerate", &fps);
    gst_caps_get_fourcc_int(caps, "format", &fourcc);

    switch (fourcc) {
      case GST_MAKE_FOURCC('I','4','2','0'):
        divx_cs = GST_MAKE_FOURCC('I','4','2','0');
        break;
      case GST_MAKE_FOURCC('Y','U','Y','2'):
        divx_cs = GST_MAKE_FOURCC('Y','U','Y','2');
        break;
      case GST_MAKE_FOURCC('Y','V','1','2'):
        divx_cs = GST_MAKE_FOURCC('Y','V','1','2');
        break;
      case GST_MAKE_FOURCC('Y','V','Y','U'):
        divx_cs = GST_MAKE_FOURCC('Y','V','Y','U');
        break;
      case GST_MAKE_FOURCC('U','Y','V','Y'):
        divx_cs = GST_MAKE_FOURCC('U','Y','V','Y');
        break;
      case GST_MAKE_FOURCC('R','G','B',' '):
        gst_caps_get_int(caps, "depth", &d);
        switch (d) {
          case 24:
            divx_cs = 0;
            bitcnt = 24;
            break;
          case 32:
            divx_cs = 0;
            bitcnt = 32;
            break;
          default:
            goto trynext;
        }
        break;
      default:
        goto trynext;
    }

    divxenc->csp = divx_cs;
    divxenc->bitcnt = bitcnt;
    divxenc->width = w;
    divxenc->height = h;
    divxenc->fps = fps;

    /* try it */
    if (gst_divxenc_setup(divxenc)) {
      GstPadLinkReturn ret;
      GstCaps *new_caps;

      new_caps = GST_CAPS_NEW("divxenc_src_caps",
                              "video/x-divx",
			        "divxversion", GST_PROPS_INT(5),
                                "width",       GST_PROPS_INT(w),
                                "height",      GST_PROPS_INT(h),
                                "framerate",   GST_PROPS_FLOAT(fps));

      ret = gst_pad_try_set_caps(divxenc->srcpad, new_caps);

      if (ret <= 0) {
        gst_divxenc_unset(divxenc);
      }

      return ret;
    }

trynext:
    continue;
  }

  /* if we got here - it's not good */
  return GST_PAD_LINK_REFUSED;
}


static void
gst_divxenc_set_property (GObject      *object,
                          guint         prop_id,
                          const GValue *value,
                          GParamSpec   *pspec)
{
  GstDivxEnc *divxenc;

  /* it's not null if we got it, but it might not be ours */
  g_return_if_fail (GST_IS_DIVXENC (object));
  divxenc = GST_DIVXENC(object);

  switch (prop_id) {
    case ARG_BITRATE:
      divxenc->bitrate = g_value_get_ulong(value);
      break;
    case ARG_MAXKEYINTERVAL:
      divxenc->max_key_interval = g_value_get_int(value);
      break;
    case ARG_QUALITY:
      divxenc->quality = g_value_get_int(value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}


static void
gst_divxenc_get_property (GObject    *object,
                          guint       prop_id,
                          GValue     *value,
                          GParamSpec *pspec)
{
  GstDivxEnc *divxenc;

  /* it's not null if we got it, but it might not be ours */
  g_return_if_fail (GST_IS_DIVXENC (object));
  divxenc = GST_DIVXENC(object);

  switch (prop_id) {
    case ARG_BITRATE:
      g_value_set_ulong(value, divxenc->bitrate);
      break;
    case ARG_BUFSIZE:
      g_value_set_ulong(value, divxenc->buffer_size);
      break;
    case ARG_MAXKEYINTERVAL:
      g_value_set_int(value, divxenc->max_key_interval);
      break;
    case ARG_QUALITY:
      g_value_set_int(value, divxenc->quality);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}


static gboolean
plugin_init (GModule   *module,
             GstPlugin *plugin)
{
  GstElementFactory *factory;
  int lib_version;

  lib_version = encore(NULL, ENC_OPT_VERSION, 0, 0);
  if (lib_version != ENCORE_VERSION) {
    g_warning("Version mismatch! This plugin was compiled for "
              "DivX version %d, while your library has version %d!",
              ENCORE_VERSION, lib_version);
  }

  if (!gst_library_load("gstvideo"))
    return FALSE;

  /* create an elementfactory for the element */
  factory = gst_element_factory_new("divxenc", GST_TYPE_DIVXENC,
                                    &gst_divxenc_details);
  g_return_val_if_fail(factory != NULL, FALSE);

  /* add pad templates */
  gst_element_factory_add_pad_template(factory,
    GST_PAD_TEMPLATE_GET(sink_template));
  gst_element_factory_add_pad_template(factory,
    GST_PAD_TEMPLATE_GET(src_template));

  gst_plugin_add_feature (plugin, GST_PLUGIN_FEATURE (factory));

  return TRUE;
}


GstPluginDesc plugin_desc = {
  GST_VERSION_MAJOR,
  GST_VERSION_MINOR,
  "divxenc",
  plugin_init
};