1/*
2 * Copyright (c) 2015 Ludmila Glinskih
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23/**
24 * Seek test.
25 */
26
27#include "libavutil/adler32.h"
28#include "libavcodec/avcodec.h"
29#include "libavformat/avformat.h"
30#include "libavutil/imgutils.h"
31
32int64_t *pts_array;
33uint32_t *crc_array;
34int size_of_array;
35int number_of_elements;
36
37static int add_crc_to_array(uint32_t crc, int64_t pts)
38{
39    if (size_of_array <= number_of_elements) {
40        if (size_of_array == 0)
41            size_of_array = 10;
42        size_of_array *= 2;
43        crc_array = av_realloc_f(crc_array, size_of_array, sizeof(uint32_t));
44        pts_array = av_realloc_f(pts_array, size_of_array, sizeof(int64_t));
45        if ((crc_array == NULL) || (pts_array == NULL)) {
46            av_log(NULL, AV_LOG_ERROR, "Can't allocate array to store crcs\n");
47            return AVERROR(ENOMEM);
48        }
49    }
50    crc_array[number_of_elements] = crc;
51    pts_array[number_of_elements] = pts;
52    number_of_elements++;
53    return 0;
54}
55
56static int compare_crc_in_array(uint32_t crc, int64_t pts)
57{
58    int i;
59    for (i = 0; i < number_of_elements; i++) {
60        if (pts_array[i] == pts) {
61            if (crc_array[i] == crc) {
62                printf("Comparing 0x%08"PRIx32" %"PRId64" %d is OK\n", crc, pts, i);
63                return 0;
64            }
65            else {
66                av_log(NULL, AV_LOG_ERROR, "Incorrect crc of a frame after seeking\n");
67                return -1;
68            }
69        }
70    }
71    av_log(NULL, AV_LOG_ERROR, "Incorrect pts of a frame after seeking\n");
72    return -1;
73}
74
75static int compute_crc_of_packets(AVFormatContext *fmt_ctx, int video_stream,
76                                AVCodecContext *ctx, AVPacket *pkt, AVFrame *fr,
77                                uint64_t ts_start, uint64_t ts_end, int no_seeking)
78{
79    int number_of_written_bytes;
80    int result;
81    int byte_buffer_size;
82    uint8_t *byte_buffer;
83    uint32_t crc;
84
85    byte_buffer_size = av_image_get_buffer_size(ctx->pix_fmt, ctx->width, ctx->height, 16);
86    byte_buffer = av_malloc(byte_buffer_size);
87    if (!byte_buffer) {
88        av_log(NULL, AV_LOG_ERROR, "Can't allocate buffer\n");
89        return AVERROR(ENOMEM);
90    }
91
92    if (!no_seeking) {
93        result = av_seek_frame(fmt_ctx, video_stream, ts_start, AVSEEK_FLAG_ANY);
94        printf("Seeking to %"PRId64", computing crc for frames with pts < %"PRId64"\n", ts_start, ts_end);
95        if (result < 0) {
96            av_log(NULL, AV_LOG_ERROR, "Error in seeking\n");
97            return result;
98        }
99        avcodec_flush_buffers(ctx);
100    }
101
102    do {
103        result = av_read_frame(fmt_ctx, pkt);
104        if (result >= 0 && pkt->stream_index != video_stream) {
105            av_packet_unref(pkt);
106            continue;
107        }
108
109        if (result < 0)
110            result = avcodec_send_packet(ctx, NULL);
111        else {
112            if (pkt->pts == AV_NOPTS_VALUE) {
113                av_log(NULL, AV_LOG_ERROR, "Error: frames doesn't have pts values\n");
114                return -1;
115            }
116            result = avcodec_send_packet(ctx, pkt);
117        }
118
119        av_packet_unref(pkt);
120
121        if (result < 0) {
122            av_log(NULL, AV_LOG_ERROR, "Error submitting a packet for decoding\n");
123            return result;
124        }
125
126        while (result >= 0) {
127            result = avcodec_receive_frame(ctx, fr);
128            if (result == AVERROR_EOF)
129                goto finish;
130            else if (result == AVERROR(EAGAIN)) {
131                result = 0;
132                break;
133            } else if (result < 0) {
134                av_log(NULL, AV_LOG_ERROR, "Error decoding frame\n");
135                return result;
136            }
137
138            number_of_written_bytes = av_image_copy_to_buffer(byte_buffer, byte_buffer_size,
139                                    (const uint8_t* const *)fr->data, (const int*) fr->linesize,
140                                    ctx->pix_fmt, ctx->width, ctx->height, 1);
141            if (number_of_written_bytes < 0) {
142                av_log(NULL, AV_LOG_ERROR, "Can't copy image to buffer\n");
143                return number_of_written_bytes;
144            }
145            if ((!no_seeking) && (fr->pts > ts_end))
146                break;
147            crc = av_adler32_update(0, (const uint8_t*)byte_buffer, number_of_written_bytes);
148            printf("%10"PRId64", 0x%08"PRIx32"\n", fr->pts, crc);
149            if (no_seeking) {
150                if (add_crc_to_array(crc, fr->pts) < 0)
151                    return -1;
152            }
153            else {
154                if (compare_crc_in_array(crc, fr->pts) < 0)
155                    return -1;
156            }
157            av_frame_unref(fr);
158        }
159    } while (result >= 0 && (no_seeking || (fr->pts + fr->pkt_duration <= ts_end)));
160
161finish:
162    av_freep(&byte_buffer);
163
164    return 0;
165}
166
167static long int read_seek_range(const char *string_with_number)
168{
169    long int number;
170    char *end_of_string = NULL;
171    number = strtol(string_with_number, &end_of_string, 10);
172    if ((strlen(string_with_number) != end_of_string - string_with_number)  || (number < 0)) {
173        av_log(NULL, AV_LOG_ERROR, "Incorrect input ranges of seeking\n");
174        return -1;
175    }
176    else if ((number == LONG_MAX) || (number == LONG_MIN)) {
177        if (errno == ERANGE) {
178            av_log(NULL, AV_LOG_ERROR, "Incorrect input ranges of seeking\n");
179            return -1;
180        }
181    }
182    return number;
183}
184
185static int seek_test(const char *input_filename, const char *start, const char *end)
186{
187    const AVCodec *codec = NULL;
188    AVCodecContext *ctx= NULL;
189    AVCodecParameters *origin_par = NULL;
190    AVPacket *pkt = NULL;
191    AVFrame *fr = NULL;
192    AVFormatContext *fmt_ctx = NULL;
193    int video_stream;
194    int result;
195    int i, j;
196    long int start_ts, end_ts;
197
198    size_of_array = 0;
199    number_of_elements = 0;
200    crc_array = NULL;
201    pts_array = NULL;
202
203    result = avformat_open_input(&fmt_ctx, input_filename, NULL, NULL);
204    if (result < 0) {
205        av_log(NULL, AV_LOG_ERROR, "Can't open file\n");
206        return result;
207    }
208
209    result = avformat_find_stream_info(fmt_ctx, NULL);
210    if (result < 0) {
211        av_log(NULL, AV_LOG_ERROR, "Can't get stream info\n");
212        goto end;
213    }
214
215    start_ts = read_seek_range(start);
216    end_ts = read_seek_range(end);
217    if ((start_ts < 0) || (end_ts < 0)) {
218        result = -1;
219        goto end;
220    }
221
222    //TODO: add ability to work with audio format
223    video_stream = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
224    if (video_stream < 0) {
225      av_log(NULL, AV_LOG_ERROR, "Can't find video stream in input file\n");
226      result = video_stream;
227      goto end;
228    }
229
230    origin_par = fmt_ctx->streams[video_stream]->codecpar;
231
232    codec = avcodec_find_decoder(origin_par->codec_id);
233    if (!codec) {
234        av_log(NULL, AV_LOG_ERROR, "Can't find decoder\n");
235        result = AVERROR_DECODER_NOT_FOUND;
236        goto end;
237    }
238
239    ctx = avcodec_alloc_context3(codec);
240    if (!ctx) {
241        av_log(NULL, AV_LOG_ERROR, "Can't allocate decoder context\n");
242        result = AVERROR(ENOMEM);
243        goto end;
244    }
245
246    result = avcodec_parameters_to_context(ctx, origin_par);
247    if (result) {
248        av_log(NULL, AV_LOG_ERROR, "Can't copy decoder context\n");
249        goto end;
250    }
251
252    result = avcodec_open2(ctx, codec, NULL);
253    if (result < 0) {
254        av_log(ctx, AV_LOG_ERROR, "Can't open decoder\n");
255        goto end;
256    }
257
258    fr = av_frame_alloc();
259    if (!fr) {
260        av_log(NULL, AV_LOG_ERROR, "Can't allocate frame\n");
261        result = AVERROR(ENOMEM);
262        goto end;
263    }
264
265    pkt = av_packet_alloc();
266    if (!pkt) {
267        av_log(NULL, AV_LOG_ERROR, "Cannot allocate packet\n");
268        result = AVERROR(ENOMEM);
269        goto end;
270    }
271
272    result = compute_crc_of_packets(fmt_ctx, video_stream, ctx, pkt, fr, 0, 0, 1);
273    if (result != 0)
274        goto end;
275
276    for (i = start_ts; i < end_ts; i += 100) {
277        for (j = i + 100; j < end_ts; j += 100) {
278            result = compute_crc_of_packets(fmt_ctx, video_stream, ctx, pkt, fr, i, j, 0);
279            if (result != 0)
280                break;
281        }
282    }
283
284end:
285    av_freep(&crc_array);
286    av_freep(&pts_array);
287    av_packet_free(&pkt);
288    av_frame_free(&fr);
289    avformat_close_input(&fmt_ctx);
290    avcodec_free_context(&ctx);
291    return result;
292}
293
294int main(int argc, char **argv)
295{
296    if (argc < 4) {
297        av_log(NULL, AV_LOG_ERROR, "Incorrect input\n");
298        return 1;
299    }
300
301    if (seek_test(argv[1], argv[2], argv[3]) != 0)
302        return 1;
303
304    return 0;
305}
306