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
11 #include <stdlib.h>
12
13 #include "./ivfenc.h"
14 #include "./video_writer.h"
15 #include "vpx/vpx_encoder.h"
16
17 struct VpxVideoWriterStruct {
18 VpxVideoInfo info;
19 FILE *file;
20 int frame_count;
21 };
22
write_header(FILE * file,const VpxVideoInfo * info,int frame_count)23 static void write_header(FILE *file, const VpxVideoInfo *info,
24 int frame_count) {
25 struct vpx_codec_enc_cfg cfg;
26 cfg.g_w = info->frame_width;
27 cfg.g_h = info->frame_height;
28 cfg.g_timebase.num = info->time_base.numerator;
29 cfg.g_timebase.den = info->time_base.denominator;
30
31 ivf_write_file_header(file, &cfg, info->codec_fourcc, frame_count);
32 }
33
vpx_video_writer_open(const char * filename,VpxContainer container,const VpxVideoInfo * info)34 VpxVideoWriter *vpx_video_writer_open(const char *filename,
35 VpxContainer container,
36 const VpxVideoInfo *info) {
37 if (container == kContainerIVF) {
38 VpxVideoWriter *writer = NULL;
39 FILE *const file = fopen(filename, "wb");
40 if (!file) {
41 fprintf(stderr, "%s can't be written to.\n", filename);
42 return NULL;
43 }
44 writer = malloc(sizeof(*writer));
45 if (!writer) {
46 fprintf(stderr, "Can't allocate VpxVideoWriter.\n");
47 return NULL;
48 }
49 writer->frame_count = 0;
50 writer->info = *info;
51 writer->file = file;
52
53 write_header(writer->file, info, 0);
54
55 return writer;
56 }
57 fprintf(stderr, "VpxVideoWriter supports only IVF.\n");
58 return NULL;
59 }
60
vpx_video_writer_close(VpxVideoWriter * writer)61 void vpx_video_writer_close(VpxVideoWriter *writer) {
62 if (writer) {
63 // Rewriting frame header with real frame count
64 rewind(writer->file);
65 write_header(writer->file, &writer->info, writer->frame_count);
66
67 fclose(writer->file);
68 free(writer);
69 }
70 }
71
vpx_video_writer_write_frame(VpxVideoWriter * writer,const uint8_t * buffer,size_t size,int64_t pts)72 int vpx_video_writer_write_frame(VpxVideoWriter *writer, const uint8_t *buffer,
73 size_t size, int64_t pts) {
74 ivf_write_frame_header(writer->file, pts, size);
75 if (fwrite(buffer, 1, size, writer->file) != size) return 0;
76
77 ++writer->frame_count;
78
79 return 1;
80 }
81