Class: Hive::FFmpeg

Inherits:
Object
  • Object
show all
Defined in:
ext/hive_ffmpeg/hive_ffmpeg.c

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeObject


710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 710

static VALUE rb_ff_init(VALUE self, VALUE file_arg) {
  char *path;
  ff_state *state;

  Check_Type(file_arg, T_STRING);

  Data_Get_Struct(self, ff_state, state);

  path = StringValueCStr(file_arg);

  if (avformat_open_input(&state->ctx, path, NULL, NULL) != 0) {
    state->ctx = NULL;
    rb_raise(rb_eRuntimeError, "FFmpeg - can't open file");
  }

  if (avformat_find_stream_info(state->ctx, NULL) < 0) {
    avformat_close_input(&state->ctx);
    state->ctx = NULL;
    rb_raise(rb_eRuntimeError, "FFmpeg - couldn't get stream info");
  }

  state->path = (char*)malloc(strlen(path) + 1);
  strcpy(state->path, path);

  return Qnil;
}

Class Method Details

.openObject


763
764
765
766
767
768
769
770
771
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 763

static VALUE rb_ff_open(int argc, VALUE *argv, VALUE klass) {
  VALUE ff = rb_class_new_instance(argc, argv, klass);

  if (rb_block_given_p()) {
    return rb_ensure(rb_yield, ff, rb_ff_close, ff);
  }

  return ff;
}

Instance Method Details

#closeObject


737
738
739
740
741
742
743
744
745
746
747
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 737

static VALUE rb_ff_close(VALUE self) {
  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  if (!state->closed) {
    avformat_close_input(&state->ctx);
    state->closed = 1;
  }

  return Qnil;
}

#closed?Boolean

Returns:

  • (Boolean)

749
750
751
752
753
754
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 749

static VALUE rb_ff_is_closed(VALUE self) {
  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  return state->closed ? Qtrue : Qfalse;
}

#durationObject


326
327
328
329
330
331
332
333
334
335
336
337
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 326

static VALUE rb_ff_duration(VALUE self) {
  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  ff_check_closed(state);

  if (state->ctx->duration == AV_NOPTS_VALUE) {
    return Qnil;
  }

  return rb_float_new(state->ctx->duration / (double)AV_TIME_BASE);
}

#formatObject


317
318
319
320
321
322
323
324
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 317

static VALUE rb_ff_format(VALUE self) {
  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  ff_check_closed(state);

  return rb_str_new2(state->ctx->iformat->name);
}

#nb_streamsObject


308
309
310
311
312
313
314
315
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 308

static VALUE rb_ff_nb_streams(VALUE self) {
  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  ff_check_closed(state);

  return INT2FIX(state->ctx->nb_streams);
}

#packetObject


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
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 264

static VALUE rb_ff_packet(VALUE self, VALUE sec_arg) {
  int64_t ts;
  VALUE hash;
  AVPacket packet;
  
  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  ff_check_closed(state);  
  
  Check_Type(sec_arg, T_FLOAT);
  
  ts = (int64_t)(NUM2DBL(sec_arg) * AV_TIME_BASE);
  
  if (avformat_seek_file(state->ctx, -1, INT64_MIN, ts, INT64_MAX, 0) < 0) {
    return Qnil;
  }
  
  if (av_read_frame(state->ctx, &packet) < 0) {
    return Qnil;
  }
  
  hash = rb_hash_new();
  
  rb_hash_aset(hash,
    STR2SYM("stream_index"),
    INT2FIX(packet.stream_index)
  );
  
  rb_hash_aset(hash,
    STR2SYM("pos"),
    LL2NUM(packet.pos)
  );
  
  rb_hash_aset(hash,
    STR2SYM("size"),
    INT2FIX(packet.size)
  );
  
  av_free_packet(&packet);
  
  return hash;
}

#pathObject


756
757
758
759
760
761
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 756

static VALUE rb_ff_path(VALUE self) {
  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  return rb_enc_str_new(state->path, strlen(state->path), rb_utf8_encoding());
}

#save_frameObject


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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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
629
630
631
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
687
688
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 390

static VALUE rb_ff_save_frame(int argc, VALUE *argv, VALUE self) {
  VALUE opts, arg;

  ID format_arg_id;

  char *out_path = NULL;

  unsigned int i,
    max_size = 0,
    out_quality = HIVE_JPEG_QUALITY,
    out_format = 0,
    out_offset = 0,
    out_width = 0,
    out_height = 0;

  int ret = 0, got_frame = 0, stream_index;

  int64_t timestamp = 0;

  float ratio;
  AVRational sar;

  ff_state *state;

  AVFormatContext *ctx;
  AVStream *stream;
  AVCodec *codec;
  AVPacket packet;

  AVCodecContext *codec_ctx = NULL;
  struct SwsContext *sws_ctx = NULL;
  AVFrame *frame = NULL;
  AVFrame *frame_rgb = NULL;

  const char *error = NULL;

  if (argc < 1) {
    rb_raise(rb_eArgError, "FFmpeg - wrong number of arguments");
  }

  arg = argv[0];
  Check_Type(arg, T_STRING);
  out_path = StringValueCStr(arg);

  if (argc == 2) {
    opts = argv[1];

    Check_Type(opts, T_HASH);

    arg = rb_hash_lookup(opts, STR2SYM("max_size"));

    if (arg != Qnil) {
      Check_Type(arg, T_FIXNUM);
      max_size = FIX2INT(arg);
    }

    arg = rb_hash_lookup(opts, STR2SYM("offset"));

    if (arg != Qnil) {
      Check_Type(arg, T_FIXNUM);
      out_offset = FIX2INT(arg);

      if (out_offset > 100) {
        rb_raise(rb_eArgError, "FFmpeg - offset must be between 0 and 100");
      }
    }

    arg = rb_hash_lookup(opts, STR2SYM("format"));

    if (arg != Qnil) {
      Check_Type(arg, T_SYMBOL);
      format_arg_id = SYM2ID(arg);

      if (format_arg_id == rb_intern("png")) {
        out_format = HIVE_FMT_PNG;
      }
      else if (format_arg_id == rb_intern("jpg") ||
        format_arg_id == rb_intern("jpeg")) {

        out_format = HIVE_FMT_JPEG;

        arg = rb_hash_lookup(opts, STR2SYM("quality"));

        if (arg != Qnil) {
          Check_Type(arg, T_FIXNUM);
          out_quality = FIX2INT(arg);

          if (out_quality > 100) {
            rb_raise(rb_eArgError, "FFmpeg - quality must be between 0 and 100");
          }
        }
      }
      else {
        rb_raise(rb_eArgError, "FFmpeg - invalid output format");
      }
    }
  }

  if (!out_format) {
    out_format = ff_fmt_from_path(out_path);

    if (!out_format) {
      rb_raise(rb_eArgError, "FFmpeg - invalid output format");
    }
  }

  Data_Get_Struct(self, ff_state, state);

  ff_check_closed(state);

  ctx = state->ctx;

  stream = NULL;

  for (i = 0; i < ctx->nb_streams; ++i) {
    if (ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
      stream_index = i;
      stream = ctx->streams[i];
      break;
    }
  }

  if (stream == NULL) {
    rb_raise(rb_eRuntimeError, "FFmpeg - no video stream");
  }

  codec_ctx = stream->codec;
  codec = avcodec_find_decoder(codec_ctx->codec_id);

  if (codec == NULL) {
    error = "FFmpeg - no suitable decoder";
    goto cleanup;
  }

  if (avcodec_open2(codec_ctx, codec, NULL) < 0) {
    error = "FFmpeg - failed to initialize the decoder";
    goto cleanup;
  }

  out_width = codec_ctx->width;
  out_height = codec_ctx->height;

  if (!out_width || !out_height || codec_ctx->pix_fmt == AV_PIX_FMT_NONE) {
    error = "FFmpeg - invalid input file";
    goto cleanup;
  }

  sar = stream->sample_aspect_ratio;

  if (sar.num != sar.den && sar.num > 0 && sar.den > 0) {
    if (sar.num > sar.den) {
      out_width = (unsigned int)(out_width * (sar.num / (double)sar.den));
    }
    else {
      out_height = (unsigned int)(out_height * (sar.den / (double)sar.num));
    }
  }

  if (max_size > 0 && (max_size < out_width || max_size < out_height)) {
    if (out_width > out_height) {
      ratio = (float)out_height / (float)out_width;

      out_width = max_size;
      out_height = (int)(max_size * ratio);

      if (out_height == 0) {
        out_height = 1;
      }
    }
    else if (out_height > out_width) {
      ratio = (float)out_width / (float)out_height;

      out_height = max_size;
      out_width = (int)(max_size * ratio);

      if (out_width == 0) {
        out_width = 1;
      }
    }
    else {
      out_width = out_height = max_size;
    }
  }

  frame = av_frame_alloc();
  frame_rgb = av_frame_alloc();

  if (frame == NULL || frame_rgb == NULL) {
    error = "FFmpeg - av_frame_alloc failed";
    goto cleanup;
  }

  frame_rgb->format = PIX_FMT_RGB24;
  frame->width = out_width;
  frame->height = out_height;

  if (av_image_alloc(
    frame_rgb->data,
    frame_rgb->linesize,
    out_width,
    out_height,
    PIX_FMT_RGB24,
    16
  ) < 0) {
    error = "FFmpeg - av_image_alloc failed";
    goto cleanup;
  }

  sws_ctx = sws_getContext(
    codec_ctx->width,
    codec_ctx->height,
    codec_ctx->pix_fmt,
    out_width,
    out_height,
    PIX_FMT_RGB24,
    SWS_BILINEAR,
    NULL,
    NULL,
    NULL
  );

  if (sws_ctx == NULL) {
    error = "FFmpeg - scaler failed to initialize";
    goto cleanup;
  }

  if (out_offset) {
    timestamp = (int64_t)(av_rescale(
      (int64_t)((double)(ctx->duration / AV_TIME_BASE) * (out_offset / 100.0)),
      stream->time_base.den,
      stream->time_base.num
    ));
  }

  avformat_seek_file(ctx, stream_index, INT64_MIN, timestamp, INT64_MAX, 0);

  while (av_read_frame(ctx, &packet) >= 0) {
    if (packet.stream_index == stream_index) {
      avcodec_decode_video2(codec_ctx, frame, &got_frame, &packet);

      if (got_frame) {
        sws_scale(
          sws_ctx,
          (uint8_t const * const *)frame->data,
          frame->linesize,
          0,
          codec_ctx->height,
          frame_rgb->data,
          frame_rgb->linesize
        );

        av_free_packet(&packet);

	      break;
      }
    }

    av_free_packet(&packet);
  }

  if (out_format == HIVE_FMT_JPEG) {
#ifdef HAVE_JPEGLIB_H
    ret = ff_save_jpeg(frame_rgb, out_width, out_height, out_path, out_quality);
#else
    error = "FFmpeg - JPEG support is disabled";
#endif
  }
  else if (out_format == HIVE_FMT_PNG) {
#ifdef HAVE_PNG_H
    ret = ff_save_png(frame_rgb, out_width, out_height, out_path);
#else
    error = "FFmpeg - PNG support is disabled";
#endif
  }

  if (ret > 0) {
    if (ret == HIVE_ERR_IO) {
      error = "FFmpeg - couldn't open file for writing";
    }
    else if (ret == HIVE_ERR_OUT) {
      error = "FFmpeg - couldn't compress output image";
    }
  }

  cleanup:
    sws_freeContext(sws_ctx);
    if (frame_rgb->data != NULL) {
      av_freep(&frame_rgb->data[0]);
    }
    av_frame_free(&frame_rgb);
    av_frame_free(&frame);
    avcodec_close(codec_ctx);

  if (error != NULL) {
    rb_raise(rb_eRuntimeError, "%s", error);
  }

  return rb_ary_new3(2, UINT2NUM(out_width), UINT2NUM(out_height));
}

#streamsObject


339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'ext/hive_ffmpeg/hive_ffmpeg.c', line 339

static VALUE rb_ff_streams(VALUE self) {
  VALUE ary;

  unsigned int i;

  ff_state *state;
  Data_Get_Struct(self, ff_state, state);

  ff_check_closed(state);

  ary = rb_ary_new();

  for (i = 0; i < state->ctx->nb_streams; ++i) {
    rb_ary_push(ary, ff_get_stream_info(state->ctx->streams[i]));
  }

  return ary;
}