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 #include <string.h>
13 
14 #include "./ivfdec.h"
15 #include "./video_reader.h"
16 
17 #include "vpx_ports/mem_ops.h"
18 
19 static const char *const kIVFSignature = "DKIF";
20 
21 struct VpxVideoReaderStruct {
22   VpxVideoInfo info;
23   FILE *file;
24   uint8_t *buffer;
25   size_t buffer_size;
26   size_t frame_size;
27 };
28 
vpx_video_reader_open(const char * filename)29 VpxVideoReader *vpx_video_reader_open(const char *filename) {
30   char header[32];
31   VpxVideoReader *reader = NULL;
32   FILE *const file = fopen(filename, "rb");
33   if (!file)
34     return NULL;  // Can't open file
35 
36   if (fread(header, 1, 32, file) != 32)
37     return NULL;  // Can't read file header
38 
39   if (memcmp(kIVFSignature, header, 4) != 0)
40     return NULL;  // Wrong IVF signature
41 
42   if (mem_get_le16(header + 4) != 0)
43     return NULL;  // Wrong IVF version
44 
45   reader = calloc(1, sizeof(*reader));
46   if (!reader)
47     return NULL;  // Can't allocate VpxVideoReader
48 
49   reader->file = file;
50   reader->info.codec_fourcc = mem_get_le32(header + 8);
51   reader->info.frame_width = mem_get_le16(header + 12);
52   reader->info.frame_height = mem_get_le16(header + 14);
53   reader->info.time_base.numerator = mem_get_le32(header + 16);
54   reader->info.time_base.denominator = mem_get_le32(header + 20);
55 
56   return reader;
57 }
58 
vpx_video_reader_close(VpxVideoReader * reader)59 void vpx_video_reader_close(VpxVideoReader *reader) {
60   if (reader) {
61     fclose(reader->file);
62     free(reader->buffer);
63     free(reader);
64   }
65 }
66 
vpx_video_reader_read_frame(VpxVideoReader * reader)67 int vpx_video_reader_read_frame(VpxVideoReader *reader) {
68   return !ivf_read_frame(reader->file, &reader->buffer, &reader->frame_size,
69                          &reader->buffer_size);
70 }
71 
vpx_video_reader_get_frame(VpxVideoReader * reader,size_t * size)72 const uint8_t *vpx_video_reader_get_frame(VpxVideoReader *reader,
73                                           size_t *size) {
74   if (size)
75     *size = reader->frame_size;
76 
77   return reader->buffer;
78 }
79 
vpx_video_reader_get_info(VpxVideoReader * reader)80 const VpxVideoInfo *vpx_video_reader_get_info(VpxVideoReader *reader) {
81   return &reader->info;
82 }
83 
84