video_writer.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2014 The WebM project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include <stdlib.h>
  11. #include "./ivfenc.h"
  12. #include "./video_writer.h"
  13. #include "vpx/vpx_encoder.h"
  14. struct VpxVideoWriterStruct {
  15. VpxVideoInfo info;
  16. FILE *file;
  17. int frame_count;
  18. };
  19. static void write_header(FILE *file, const VpxVideoInfo *info,
  20. int frame_count) {
  21. struct vpx_codec_enc_cfg cfg;
  22. cfg.g_w = info->frame_width;
  23. cfg.g_h = info->frame_height;
  24. cfg.g_timebase.num = info->time_base.numerator;
  25. cfg.g_timebase.den = info->time_base.denominator;
  26. ivf_write_file_header(file, &cfg, info->codec_fourcc, frame_count);
  27. }
  28. VpxVideoWriter *vpx_video_writer_open(const char *filename,
  29. VpxContainer container,
  30. const VpxVideoInfo *info) {
  31. if (container == kContainerIVF) {
  32. VpxVideoWriter *writer = NULL;
  33. FILE *const file = fopen(filename, "wb");
  34. if (!file) {
  35. fprintf(stderr, "%s can't be written to.\n", filename);
  36. return NULL;
  37. }
  38. writer = malloc(sizeof(*writer));
  39. if (!writer) {
  40. fprintf(stderr, "Can't allocate VpxVideoWriter.\n");
  41. return NULL;
  42. }
  43. writer->frame_count = 0;
  44. writer->info = *info;
  45. writer->file = file;
  46. write_header(writer->file, info, 0);
  47. return writer;
  48. }
  49. fprintf(stderr, "VpxVideoWriter supports only IVF.\n");
  50. return NULL;
  51. }
  52. void vpx_video_writer_close(VpxVideoWriter *writer) {
  53. if (writer) {
  54. // Rewriting frame header with real frame count
  55. rewind(writer->file);
  56. write_header(writer->file, &writer->info, writer->frame_count);
  57. fclose(writer->file);
  58. free(writer);
  59. }
  60. }
  61. int vpx_video_writer_write_frame(VpxVideoWriter *writer, const uint8_t *buffer,
  62. size_t size, int64_t pts) {
  63. ivf_write_frame_header(writer->file, pts, size);
  64. if (fwrite(buffer, 1, size, writer->file) != size) return 0;
  65. ++writer->frame_count;
  66. return 1;
  67. }