seek.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. * seek utility functions for use within format handlers
  3. *
  4. * Copyright (c) 2009 Ivan Schreter
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "seek.h"
  23. #include "libavutil/mem.h"
  24. #include "internal.h"
  25. // NOTE: implementation should be moved here in another patch, to keep patches
  26. // separated.
  27. /**
  28. * helper structure describing keyframe search state of one stream
  29. */
  30. typedef struct {
  31. int64_t pos_lo; ///< position of the frame with low timestamp in file or INT64_MAX if not found (yet)
  32. int64_t ts_lo; ///< frame presentation timestamp or same as pos_lo for byte seeking
  33. int64_t pos_hi; ///< position of the frame with high timestamp in file or INT64_MAX if not found (yet)
  34. int64_t ts_hi; ///< frame presentation timestamp or same as pos_hi for byte seeking
  35. int64_t last_pos; ///< last known position of a frame, for multi-frame packets
  36. int64_t term_ts; ///< termination timestamp (which TS we already read)
  37. AVRational term_ts_tb; ///< timebase for term_ts
  38. int64_t first_ts; ///< first packet timestamp in this iteration (to fill term_ts later)
  39. AVRational first_ts_tb; ///< timebase for first_ts
  40. int terminated; ///< termination flag for the current iteration
  41. } AVSyncPoint;
  42. /**
  43. * Compute a distance between timestamps.
  44. *
  45. * Distances are only comparable, if same time bases are used for computing
  46. * distances.
  47. *
  48. * @param ts_hi high timestamp
  49. * @param tb_hi high timestamp time base
  50. * @param ts_lo low timestamp
  51. * @param tb_lo low timestamp time base
  52. * @return representation of distance between high and low timestamps
  53. */
  54. static int64_t ts_distance(int64_t ts_hi,
  55. AVRational tb_hi,
  56. int64_t ts_lo,
  57. AVRational tb_lo)
  58. {
  59. int64_t hi, lo;
  60. hi = ts_hi * tb_hi.num * tb_lo.den;
  61. lo = ts_lo * tb_lo.num * tb_hi.den;
  62. return hi - lo;
  63. }
  64. /**
  65. * Partial search for keyframes in multiple streams.
  66. *
  67. * This routine searches in each stream for the next lower and the next higher
  68. * timestamp compared to the given target timestamp. The search starts at the current
  69. * file position and ends at the file position, where all streams have already been
  70. * examined (or when all higher key frames are found in the first iteration).
  71. *
  72. * This routine is called iteratively with an exponential backoff to find the lower
  73. * timestamp.
  74. *
  75. * @param s format context
  76. * @param timestamp target timestamp (or position, if AVSEEK_FLAG_BYTE)
  77. * @param timebase time base for timestamps
  78. * @param flags seeking flags
  79. * @param sync array with information per stream
  80. * @param keyframes_to_find count of keyframes to find in total
  81. * @param found_lo ptr to the count of already found low timestamp keyframes
  82. * @param found_hi ptr to the count of already found high timestamp keyframes
  83. * @param first_iter flag for first iteration
  84. */
  85. static void search_hi_lo_keyframes(AVFormatContext *s,
  86. int64_t timestamp,
  87. AVRational timebase,
  88. int flags,
  89. AVSyncPoint *sync,
  90. int keyframes_to_find,
  91. int *found_lo,
  92. int *found_hi,
  93. int first_iter)
  94. {
  95. AVPacket pkt;
  96. AVSyncPoint *sp;
  97. AVStream *st;
  98. int idx;
  99. int flg;
  100. int terminated_count = 0;
  101. int64_t pos;
  102. int64_t pts, dts; // PTS/DTS from stream
  103. int64_t ts; // PTS in stream-local time base or position for byte seeking
  104. AVRational ts_tb; // Time base of the stream or 1:1 for byte seeking
  105. for (;;) {
  106. if (av_read_frame(s, &pkt) < 0) {
  107. // EOF or error, make sure high flags are set
  108. for (idx = 0; idx < s->nb_streams; ++idx) {
  109. if (s->streams[idx]->discard < AVDISCARD_ALL) {
  110. sp = &sync[idx];
  111. if (sp->pos_hi == INT64_MAX) {
  112. // no high frame exists for this stream
  113. (*found_hi)++;
  114. sp->ts_hi = INT64_MAX;
  115. sp->pos_hi = INT64_MAX - 1;
  116. }
  117. }
  118. }
  119. break;
  120. }
  121. idx = pkt.stream_index;
  122. st = s->streams[idx];
  123. if (st->discard >= AVDISCARD_ALL)
  124. // this stream is not active, skip packet
  125. continue;
  126. sp = &sync[idx];
  127. flg = pkt.flags;
  128. pos = pkt.pos;
  129. pts = pkt.pts;
  130. dts = pkt.dts;
  131. if (pts == AV_NOPTS_VALUE)
  132. // some formats don't provide PTS, only DTS
  133. pts = dts;
  134. av_free_packet(&pkt);
  135. // Multi-frame packets only return position for the very first frame.
  136. // Other frames are read with position == -1. Therefore, we note down
  137. // last known position of a frame and use it if a frame without
  138. // position arrives. In this way, it's possible to seek to proper
  139. // position. Additionally, for parsers not providing position at all,
  140. // an approximation will be used (starting position of this iteration).
  141. if (pos < 0)
  142. pos = sp->last_pos;
  143. else
  144. sp->last_pos = pos;
  145. // Evaluate key frames with known TS (or any frames, if AVSEEK_FLAG_ANY set).
  146. if (pts != AV_NOPTS_VALUE &&
  147. ((flg & AV_PKT_FLAG_KEY) || (flags & AVSEEK_FLAG_ANY))) {
  148. if (flags & AVSEEK_FLAG_BYTE) {
  149. // for byte seeking, use position as timestamp
  150. ts = pos;
  151. ts_tb.num = 1;
  152. ts_tb.den = 1;
  153. } else {
  154. // otherwise, get stream time_base
  155. ts = pts;
  156. ts_tb = st->time_base;
  157. }
  158. if (sp->first_ts == AV_NOPTS_VALUE) {
  159. // Note down termination timestamp for the next iteration - when
  160. // we encounter a packet with the same timestamp, we will ignore
  161. // any further packets for this stream in next iteration (as they
  162. // are already evaluated).
  163. sp->first_ts = ts;
  164. sp->first_ts_tb = ts_tb;
  165. }
  166. if (sp->term_ts != AV_NOPTS_VALUE &&
  167. av_compare_ts(ts, ts_tb, sp->term_ts, sp->term_ts_tb) > 0) {
  168. // past the end position from last iteration, ignore packet
  169. if (!sp->terminated) {
  170. sp->terminated = 1;
  171. ++terminated_count;
  172. if (sp->pos_hi == INT64_MAX) {
  173. // no high frame exists for this stream
  174. (*found_hi)++;
  175. sp->ts_hi = INT64_MAX;
  176. sp->pos_hi = INT64_MAX - 1;
  177. }
  178. if (terminated_count == keyframes_to_find)
  179. break; // all terminated, iteration done
  180. }
  181. continue;
  182. }
  183. if (av_compare_ts(ts, ts_tb, timestamp, timebase) <= 0) {
  184. // keyframe found before target timestamp
  185. if (sp->pos_lo == INT64_MAX) {
  186. // found first keyframe lower than target timestamp
  187. (*found_lo)++;
  188. sp->ts_lo = ts;
  189. sp->pos_lo = pos;
  190. } else if (sp->ts_lo < ts) {
  191. // found a better match (closer to target timestamp)
  192. sp->ts_lo = ts;
  193. sp->pos_lo = pos;
  194. }
  195. }
  196. if (av_compare_ts(ts, ts_tb, timestamp, timebase) >= 0) {
  197. // keyframe found after target timestamp
  198. if (sp->pos_hi == INT64_MAX) {
  199. // found first keyframe higher than target timestamp
  200. (*found_hi)++;
  201. sp->ts_hi = ts;
  202. sp->pos_hi = pos;
  203. if (*found_hi >= keyframes_to_find && first_iter) {
  204. // We found high frame for all. They may get updated
  205. // to TS closer to target TS in later iterations (which
  206. // will stop at start position of previous iteration).
  207. break;
  208. }
  209. } else if (sp->ts_hi > ts) {
  210. // found a better match (actually, shouldn't happen)
  211. sp->ts_hi = ts;
  212. sp->pos_hi = pos;
  213. }
  214. }
  215. }
  216. }
  217. // Clean up the parser.
  218. ff_read_frame_flush(s);
  219. }
  220. int64_t ff_gen_syncpoint_search(AVFormatContext *s,
  221. int stream_index,
  222. int64_t pos,
  223. int64_t ts_min,
  224. int64_t ts,
  225. int64_t ts_max,
  226. int flags)
  227. {
  228. AVSyncPoint *sync, *sp;
  229. AVStream *st;
  230. int i;
  231. int keyframes_to_find = 0;
  232. int64_t curpos;
  233. int64_t step;
  234. int found_lo = 0, found_hi = 0;
  235. int64_t min_distance, distance;
  236. int64_t min_pos = 0;
  237. int first_iter = 1;
  238. AVRational time_base;
  239. if (flags & AVSEEK_FLAG_BYTE) {
  240. // for byte seeking, we have exact 1:1 "timestamps" - positions
  241. time_base.num = 1;
  242. time_base.den = 1;
  243. } else {
  244. if (stream_index >= 0) {
  245. // we have a reference stream, which time base we use
  246. st = s->streams[stream_index];
  247. time_base = st->time_base;
  248. } else {
  249. // no reference stream, use AV_TIME_BASE as reference time base
  250. time_base.num = 1;
  251. time_base.den = AV_TIME_BASE;
  252. }
  253. }
  254. // Initialize syncpoint structures for each stream.
  255. sync = av_malloc(s->nb_streams * sizeof(AVSyncPoint));
  256. if (!sync)
  257. // cannot allocate helper structure
  258. return -1;
  259. for (i = 0; i < s->nb_streams; ++i) {
  260. st = s->streams[i];
  261. sp = &sync[i];
  262. sp->pos_lo = INT64_MAX;
  263. sp->ts_lo = INT64_MAX;
  264. sp->pos_hi = INT64_MAX;
  265. sp->ts_hi = INT64_MAX;
  266. sp->terminated = 0;
  267. sp->first_ts = AV_NOPTS_VALUE;
  268. sp->term_ts = ts_max;
  269. sp->term_ts_tb = time_base;
  270. sp->last_pos = pos;
  271. st->cur_dts = AV_NOPTS_VALUE;
  272. if (st->discard < AVDISCARD_ALL)
  273. ++keyframes_to_find;
  274. }
  275. if (!keyframes_to_find) {
  276. // no stream active, error
  277. av_free(sync);
  278. return -1;
  279. }
  280. // Find keyframes in all active streams with timestamp/position just before
  281. // and just after requested timestamp/position.
  282. step = s->pb->buffer_size;
  283. curpos = FFMAX(pos - step / 2, 0);
  284. for (;;) {
  285. url_fseek(s->pb, curpos, SEEK_SET);
  286. search_hi_lo_keyframes(s,
  287. ts, time_base,
  288. flags,
  289. sync,
  290. keyframes_to_find,
  291. &found_lo, &found_hi,
  292. first_iter);
  293. if (found_lo == keyframes_to_find && found_hi == keyframes_to_find)
  294. break; // have all keyframes we wanted
  295. if (!curpos)
  296. break; // cannot go back anymore
  297. curpos = pos - step;
  298. if (curpos < 0)
  299. curpos = 0;
  300. step *= 2;
  301. // switch termination positions
  302. for (i = 0; i < s->nb_streams; ++i) {
  303. st = s->streams[i];
  304. st->cur_dts = AV_NOPTS_VALUE;
  305. sp = &sync[i];
  306. if (sp->first_ts != AV_NOPTS_VALUE) {
  307. sp->term_ts = sp->first_ts;
  308. sp->term_ts_tb = sp->first_ts_tb;
  309. sp->first_ts = AV_NOPTS_VALUE;
  310. }
  311. sp->terminated = 0;
  312. sp->last_pos = curpos;
  313. }
  314. first_iter = 0;
  315. }
  316. // Find actual position to start decoding so that decoder synchronizes
  317. // closest to ts and between ts_min and ts_max.
  318. pos = INT64_MAX;
  319. for (i = 0; i < s->nb_streams; ++i) {
  320. st = s->streams[i];
  321. if (st->discard < AVDISCARD_ALL) {
  322. sp = &sync[i];
  323. min_distance = INT64_MAX;
  324. // Find timestamp closest to requested timestamp within min/max limits.
  325. if (sp->pos_lo != INT64_MAX
  326. && av_compare_ts(ts_min, time_base, sp->ts_lo, st->time_base) <= 0
  327. && av_compare_ts(sp->ts_lo, st->time_base, ts_max, time_base) <= 0) {
  328. // low timestamp is in range
  329. min_distance = ts_distance(ts, time_base, sp->ts_lo, st->time_base);
  330. min_pos = sp->pos_lo;
  331. }
  332. if (sp->pos_hi != INT64_MAX
  333. && av_compare_ts(ts_min, time_base, sp->ts_hi, st->time_base) <= 0
  334. && av_compare_ts(sp->ts_hi, st->time_base, ts_max, time_base) <= 0) {
  335. // high timestamp is in range, check distance
  336. distance = ts_distance(sp->ts_hi, st->time_base, ts, time_base);
  337. if (distance < min_distance) {
  338. min_distance = distance;
  339. min_pos = sp->pos_hi;
  340. }
  341. }
  342. if (min_distance == INT64_MAX) {
  343. // no timestamp is in range, cannot seek
  344. av_free(sync);
  345. return -1;
  346. }
  347. if (min_pos < pos)
  348. pos = min_pos;
  349. }
  350. }
  351. url_fseek(s->pb, pos, SEEK_SET);
  352. av_free(sync);
  353. return pos;
  354. }
  355. AVParserState *ff_store_parser_state(AVFormatContext *s)
  356. {
  357. int i;
  358. AVStream *st;
  359. AVParserStreamState *ss;
  360. AVParserState *state = av_malloc(sizeof(AVParserState));
  361. if (!state)
  362. return NULL;
  363. state->stream_states = av_malloc(sizeof(AVParserStreamState) * s->nb_streams);
  364. if (!state->stream_states) {
  365. av_free(state);
  366. return NULL;
  367. }
  368. state->fpos = url_ftell(s->pb);
  369. // copy context structures
  370. state->cur_st = s->cur_st;
  371. state->packet_buffer = s->packet_buffer;
  372. state->raw_packet_buffer = s->raw_packet_buffer;
  373. state->raw_packet_buffer_remaining_size = s->raw_packet_buffer_remaining_size;
  374. s->cur_st = NULL;
  375. s->packet_buffer = NULL;
  376. s->raw_packet_buffer = NULL;
  377. s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;
  378. // copy stream structures
  379. state->nb_streams = s->nb_streams;
  380. for (i = 0; i < s->nb_streams; i++) {
  381. st = s->streams[i];
  382. ss = &state->stream_states[i];
  383. ss->parser = st->parser;
  384. ss->last_IP_pts = st->last_IP_pts;
  385. ss->cur_dts = st->cur_dts;
  386. ss->reference_dts = st->reference_dts;
  387. ss->cur_ptr = st->cur_ptr;
  388. ss->cur_len = st->cur_len;
  389. ss->probe_packets = st->probe_packets;
  390. ss->cur_pkt = st->cur_pkt;
  391. st->parser = NULL;
  392. st->last_IP_pts = AV_NOPTS_VALUE;
  393. st->cur_dts = AV_NOPTS_VALUE;
  394. st->reference_dts = AV_NOPTS_VALUE;
  395. st->cur_ptr = NULL;
  396. st->cur_len = 0;
  397. st->probe_packets = MAX_PROBE_PACKETS;
  398. av_init_packet(&st->cur_pkt);
  399. }
  400. return state;
  401. }
  402. void ff_restore_parser_state(AVFormatContext *s, AVParserState *state)
  403. {
  404. int i;
  405. AVStream *st;
  406. AVParserStreamState *ss;
  407. ff_read_frame_flush(s);
  408. if (!state)
  409. return;
  410. url_fseek(s->pb, state->fpos, SEEK_SET);
  411. // copy context structures
  412. s->cur_st = state->cur_st;
  413. s->packet_buffer = state->packet_buffer;
  414. s->raw_packet_buffer = state->raw_packet_buffer;
  415. s->raw_packet_buffer_remaining_size = state->raw_packet_buffer_remaining_size;
  416. // copy stream structures
  417. for (i = 0; i < state->nb_streams; i++) {
  418. st = s->streams[i];
  419. ss = &state->stream_states[i];
  420. st->parser = ss->parser;
  421. st->last_IP_pts = ss->last_IP_pts;
  422. st->cur_dts = ss->cur_dts;
  423. st->reference_dts = ss->reference_dts;
  424. st->cur_ptr = ss->cur_ptr;
  425. st->cur_len = ss->cur_len;
  426. st->probe_packets = ss->probe_packets;
  427. st->cur_pkt = ss->cur_pkt;
  428. }
  429. av_free(state->stream_states);
  430. av_free(state);
  431. }
  432. static void free_packet_list(AVPacketList *pktl)
  433. {
  434. AVPacketList *cur;
  435. while (pktl) {
  436. cur = pktl;
  437. pktl = cur->next;
  438. av_free_packet(&cur->pkt);
  439. av_free(cur);
  440. }
  441. }
  442. void ff_free_parser_state(AVFormatContext *s, AVParserState *state)
  443. {
  444. int i;
  445. AVParserStreamState *ss;
  446. if (!state)
  447. return;
  448. for (i = 0; i < state->nb_streams; i++) {
  449. ss = &state->stream_states[i];
  450. if (ss->parser)
  451. av_parser_close(ss->parser);
  452. av_free_packet(&ss->cur_pkt);
  453. }
  454. free_packet_list(state->packet_buffer);
  455. free_packet_list(state->raw_packet_buffer);
  456. av_free(state->stream_states);
  457. av_free(state);
  458. }