You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

729 lines
23KB

  1. /*
  2. * Copyright (c) 2012 Nicolas George
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public License
  8. * as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include "libavutil/avassert.h"
  21. #include "libavutil/avstring.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "libavutil/opt.h"
  24. #include "libavutil/parseutils.h"
  25. #include "libavutil/timestamp.h"
  26. #include "avformat.h"
  27. #include "internal.h"
  28. #include "url.h"
  29. typedef enum ConcatMatchMode {
  30. MATCH_ONE_TO_ONE,
  31. MATCH_EXACT_ID,
  32. } ConcatMatchMode;
  33. typedef struct ConcatStream {
  34. AVBitStreamFilterContext *bsf;
  35. int out_stream_index;
  36. } ConcatStream;
  37. typedef struct {
  38. char *url;
  39. int64_t start_time;
  40. int64_t file_start_time;
  41. int64_t file_inpoint;
  42. int64_t duration;
  43. ConcatStream *streams;
  44. int64_t inpoint;
  45. int64_t outpoint;
  46. AVDictionary *metadata;
  47. int nb_streams;
  48. } ConcatFile;
  49. typedef struct {
  50. AVClass *class;
  51. ConcatFile *files;
  52. ConcatFile *cur_file;
  53. unsigned nb_files;
  54. AVFormatContext *avf;
  55. int safe;
  56. int seekable;
  57. int eof;
  58. ConcatMatchMode stream_match_mode;
  59. unsigned auto_convert;
  60. } ConcatContext;
  61. static int concat_probe(AVProbeData *probe)
  62. {
  63. return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
  64. 0 : AVPROBE_SCORE_MAX;
  65. }
  66. static char *get_keyword(uint8_t **cursor)
  67. {
  68. char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
  69. *cursor += strcspn(*cursor, SPACE_CHARS);
  70. if (**cursor) {
  71. *((*cursor)++) = 0;
  72. *cursor += strspn(*cursor, SPACE_CHARS);
  73. }
  74. return ret;
  75. }
  76. static int safe_filename(const char *f)
  77. {
  78. const char *start = f;
  79. for (; *f; f++) {
  80. /* A-Za-z0-9_- */
  81. if (!((unsigned)((*f | 32) - 'a') < 26 ||
  82. (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
  83. if (f == start)
  84. return 0;
  85. else if (*f == '/')
  86. start = f + 1;
  87. else if (*f != '.')
  88. return 0;
  89. }
  90. }
  91. return 1;
  92. }
  93. #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
  94. static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
  95. unsigned *nb_files_alloc)
  96. {
  97. ConcatContext *cat = avf->priv_data;
  98. ConcatFile *file;
  99. char *url = NULL;
  100. const char *proto;
  101. size_t url_len, proto_len;
  102. int ret;
  103. if (cat->safe > 0 && !safe_filename(filename)) {
  104. av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
  105. FAIL(AVERROR(EPERM));
  106. }
  107. proto = avio_find_protocol_name(filename);
  108. proto_len = proto ? strlen(proto) : 0;
  109. if (!memcmp(filename, proto, proto_len) &&
  110. (filename[proto_len] == ':' || filename[proto_len] == ',')) {
  111. url = filename;
  112. filename = NULL;
  113. } else {
  114. url_len = strlen(avf->filename) + strlen(filename) + 16;
  115. if (!(url = av_malloc(url_len)))
  116. FAIL(AVERROR(ENOMEM));
  117. ff_make_absolute_url(url, url_len, avf->filename, filename);
  118. av_freep(&filename);
  119. }
  120. if (cat->nb_files >= *nb_files_alloc) {
  121. size_t n = FFMAX(*nb_files_alloc * 2, 16);
  122. ConcatFile *new_files;
  123. if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
  124. !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
  125. FAIL(AVERROR(ENOMEM));
  126. cat->files = new_files;
  127. *nb_files_alloc = n;
  128. }
  129. file = &cat->files[cat->nb_files++];
  130. memset(file, 0, sizeof(*file));
  131. *rfile = file;
  132. file->url = url;
  133. file->start_time = AV_NOPTS_VALUE;
  134. file->duration = AV_NOPTS_VALUE;
  135. file->inpoint = AV_NOPTS_VALUE;
  136. file->outpoint = AV_NOPTS_VALUE;
  137. return 0;
  138. fail:
  139. av_free(url);
  140. av_free(filename);
  141. return ret;
  142. }
  143. static int copy_stream_props(AVStream *st, AVStream *source_st)
  144. {
  145. int ret;
  146. if (st->codec->codec_id || !source_st->codec->codec_id) {
  147. if (st->codec->extradata_size < source_st->codec->extradata_size) {
  148. ret = ff_alloc_extradata(st->codec,
  149. source_st->codec->extradata_size);
  150. if (ret < 0)
  151. return ret;
  152. }
  153. memcpy(st->codec->extradata, source_st->codec->extradata,
  154. source_st->codec->extradata_size);
  155. return 0;
  156. }
  157. if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
  158. return ret;
  159. st->r_frame_rate = source_st->r_frame_rate;
  160. st->avg_frame_rate = source_st->avg_frame_rate;
  161. st->time_base = source_st->time_base;
  162. st->sample_aspect_ratio = source_st->sample_aspect_ratio;
  163. av_dict_copy(&st->metadata, source_st->metadata, 0);
  164. return 0;
  165. }
  166. static int detect_stream_specific(AVFormatContext *avf, int idx)
  167. {
  168. ConcatContext *cat = avf->priv_data;
  169. AVStream *st = cat->avf->streams[idx];
  170. ConcatStream *cs = &cat->cur_file->streams[idx];
  171. AVBitStreamFilterContext *bsf;
  172. if (cat->auto_convert && st->codec->codec_id == AV_CODEC_ID_H264 &&
  173. (st->codec->extradata_size < 4 || AV_RB32(st->codec->extradata) != 1)) {
  174. av_log(cat->avf, AV_LOG_INFO,
  175. "Auto-inserting h264_mp4toannexb bitstream filter\n");
  176. if (!(bsf = av_bitstream_filter_init("h264_mp4toannexb"))) {
  177. av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
  178. "required for H.264 streams\n");
  179. return AVERROR_BSF_NOT_FOUND;
  180. }
  181. cs->bsf = bsf;
  182. }
  183. return 0;
  184. }
  185. static int match_streams_one_to_one(AVFormatContext *avf)
  186. {
  187. ConcatContext *cat = avf->priv_data;
  188. AVStream *st;
  189. int i, ret;
  190. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
  191. if (i < avf->nb_streams) {
  192. st = avf->streams[i];
  193. } else {
  194. if (!(st = avformat_new_stream(avf, NULL)))
  195. return AVERROR(ENOMEM);
  196. }
  197. if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
  198. return ret;
  199. cat->cur_file->streams[i].out_stream_index = i;
  200. }
  201. return 0;
  202. }
  203. static int match_streams_exact_id(AVFormatContext *avf)
  204. {
  205. ConcatContext *cat = avf->priv_data;
  206. AVStream *st;
  207. int i, j, ret;
  208. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
  209. st = cat->avf->streams[i];
  210. for (j = 0; j < avf->nb_streams; j++) {
  211. if (avf->streams[j]->id == st->id) {
  212. av_log(avf, AV_LOG_VERBOSE,
  213. "Match slave stream #%d with stream #%d id 0x%x\n",
  214. i, j, st->id);
  215. if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
  216. return ret;
  217. cat->cur_file->streams[i].out_stream_index = j;
  218. }
  219. }
  220. }
  221. return 0;
  222. }
  223. static int match_streams(AVFormatContext *avf)
  224. {
  225. ConcatContext *cat = avf->priv_data;
  226. ConcatStream *map;
  227. int i, ret;
  228. if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
  229. return 0;
  230. map = av_realloc(cat->cur_file->streams,
  231. cat->avf->nb_streams * sizeof(*map));
  232. if (!map)
  233. return AVERROR(ENOMEM);
  234. cat->cur_file->streams = map;
  235. memset(map + cat->cur_file->nb_streams, 0,
  236. (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
  237. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
  238. map[i].out_stream_index = -1;
  239. switch (cat->stream_match_mode) {
  240. case MATCH_ONE_TO_ONE:
  241. ret = match_streams_one_to_one(avf);
  242. break;
  243. case MATCH_EXACT_ID:
  244. ret = match_streams_exact_id(avf);
  245. break;
  246. default:
  247. ret = AVERROR_BUG;
  248. }
  249. if (ret < 0)
  250. return ret;
  251. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
  252. if ((ret = detect_stream_specific(avf, i)) < 0)
  253. return ret;
  254. cat->cur_file->nb_streams = cat->avf->nb_streams;
  255. return 0;
  256. }
  257. static int open_file(AVFormatContext *avf, unsigned fileno)
  258. {
  259. ConcatContext *cat = avf->priv_data;
  260. ConcatFile *file = &cat->files[fileno];
  261. int ret;
  262. if (cat->avf)
  263. avformat_close_input(&cat->avf);
  264. cat->avf = avformat_alloc_context();
  265. if (!cat->avf)
  266. return AVERROR(ENOMEM);
  267. cat->avf->interrupt_callback = avf->interrupt_callback;
  268. if ((ret = ff_copy_whitelists(cat->avf, avf)) < 0)
  269. return ret;
  270. if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
  271. (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
  272. av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
  273. avformat_close_input(&cat->avf);
  274. return ret;
  275. }
  276. cat->cur_file = file;
  277. if (file->start_time == AV_NOPTS_VALUE)
  278. file->start_time = !fileno ? 0 :
  279. cat->files[fileno - 1].start_time +
  280. cat->files[fileno - 1].duration;
  281. file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
  282. file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
  283. if ((ret = match_streams(avf)) < 0)
  284. return ret;
  285. if (file->inpoint != AV_NOPTS_VALUE) {
  286. if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
  287. return ret;
  288. }
  289. return 0;
  290. }
  291. static int concat_read_close(AVFormatContext *avf)
  292. {
  293. ConcatContext *cat = avf->priv_data;
  294. unsigned i;
  295. if (cat->avf)
  296. avformat_close_input(&cat->avf);
  297. for (i = 0; i < cat->nb_files; i++) {
  298. av_freep(&cat->files[i].url);
  299. av_freep(&cat->files[i].streams);
  300. av_dict_free(&cat->files[i].metadata);
  301. }
  302. av_freep(&cat->files);
  303. return 0;
  304. }
  305. static int concat_read_header(AVFormatContext *avf)
  306. {
  307. ConcatContext *cat = avf->priv_data;
  308. uint8_t buf[4096];
  309. uint8_t *cursor, *keyword;
  310. int ret, line = 0, i;
  311. unsigned nb_files_alloc = 0;
  312. ConcatFile *file = NULL;
  313. int64_t time = 0;
  314. while (1) {
  315. if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
  316. break;
  317. line++;
  318. cursor = buf;
  319. keyword = get_keyword(&cursor);
  320. if (!*keyword || *keyword == '#')
  321. continue;
  322. if (!strcmp(keyword, "file")) {
  323. char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
  324. if (!filename) {
  325. av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
  326. FAIL(AVERROR_INVALIDDATA);
  327. }
  328. if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
  329. goto fail;
  330. } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
  331. char *dur_str = get_keyword(&cursor);
  332. int64_t dur;
  333. if (!file) {
  334. av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
  335. line, keyword);
  336. FAIL(AVERROR_INVALIDDATA);
  337. }
  338. if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
  339. av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
  340. line, keyword, dur_str);
  341. goto fail;
  342. }
  343. if (!strcmp(keyword, "duration"))
  344. file->duration = dur;
  345. else if (!strcmp(keyword, "inpoint"))
  346. file->inpoint = dur;
  347. else if (!strcmp(keyword, "outpoint"))
  348. file->outpoint = dur;
  349. } else if (!strcmp(keyword, "file_packet_metadata")) {
  350. char *metadata;
  351. if (!file) {
  352. av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
  353. line, keyword);
  354. FAIL(AVERROR_INVALIDDATA);
  355. }
  356. metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
  357. if (!metadata) {
  358. av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
  359. FAIL(AVERROR_INVALIDDATA);
  360. }
  361. if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
  362. av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
  363. av_freep(&metadata);
  364. FAIL(AVERROR_INVALIDDATA);
  365. }
  366. av_freep(&metadata);
  367. } else if (!strcmp(keyword, "stream")) {
  368. if (!avformat_new_stream(avf, NULL))
  369. FAIL(AVERROR(ENOMEM));
  370. } else if (!strcmp(keyword, "exact_stream_id")) {
  371. if (!avf->nb_streams) {
  372. av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
  373. line);
  374. FAIL(AVERROR_INVALIDDATA);
  375. }
  376. avf->streams[avf->nb_streams - 1]->id =
  377. strtol(get_keyword(&cursor), NULL, 0);
  378. } else if (!strcmp(keyword, "ffconcat")) {
  379. char *ver_kw = get_keyword(&cursor);
  380. char *ver_val = get_keyword(&cursor);
  381. if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
  382. av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
  383. FAIL(AVERROR_INVALIDDATA);
  384. }
  385. if (cat->safe < 0)
  386. cat->safe = 1;
  387. } else {
  388. av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
  389. line, keyword);
  390. FAIL(AVERROR_INVALIDDATA);
  391. }
  392. }
  393. if (ret < 0)
  394. goto fail;
  395. if (!cat->nb_files)
  396. FAIL(AVERROR_INVALIDDATA);
  397. for (i = 0; i < cat->nb_files; i++) {
  398. if (cat->files[i].start_time == AV_NOPTS_VALUE)
  399. cat->files[i].start_time = time;
  400. else
  401. time = cat->files[i].start_time;
  402. if (cat->files[i].duration == AV_NOPTS_VALUE) {
  403. if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
  404. break;
  405. cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
  406. }
  407. time += cat->files[i].duration;
  408. }
  409. if (i == cat->nb_files) {
  410. avf->duration = time;
  411. cat->seekable = 1;
  412. }
  413. cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
  414. MATCH_ONE_TO_ONE;
  415. if ((ret = open_file(avf, 0)) < 0)
  416. goto fail;
  417. return 0;
  418. fail:
  419. concat_read_close(avf);
  420. return ret;
  421. }
  422. static int open_next_file(AVFormatContext *avf)
  423. {
  424. ConcatContext *cat = avf->priv_data;
  425. unsigned fileno = cat->cur_file - cat->files;
  426. if (cat->cur_file->duration == AV_NOPTS_VALUE) {
  427. cat->cur_file->duration = cat->avf->duration;
  428. if (cat->cur_file->inpoint != AV_NOPTS_VALUE)
  429. cat->cur_file->duration -= (cat->cur_file->inpoint - cat->cur_file->file_start_time);
  430. if (cat->cur_file->outpoint != AV_NOPTS_VALUE)
  431. cat->cur_file->duration -= cat->avf->duration - (cat->cur_file->outpoint - cat->cur_file->file_start_time);
  432. }
  433. if (++fileno >= cat->nb_files) {
  434. cat->eof = 1;
  435. return AVERROR_EOF;
  436. }
  437. return open_file(avf, fileno);
  438. }
  439. static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
  440. {
  441. AVStream *st = avf->streams[cs->out_stream_index];
  442. AVBitStreamFilterContext *bsf;
  443. AVPacket pkt2;
  444. int ret;
  445. av_assert0(cs->out_stream_index >= 0);
  446. for (bsf = cs->bsf; bsf; bsf = bsf->next) {
  447. pkt2 = *pkt;
  448. ret = av_bitstream_filter_filter(bsf, st->codec, NULL,
  449. &pkt2.data, &pkt2.size,
  450. pkt->data, pkt->size,
  451. !!(pkt->flags & AV_PKT_FLAG_KEY));
  452. if (ret < 0) {
  453. av_packet_unref(pkt);
  454. return ret;
  455. }
  456. av_assert0(pkt2.buf);
  457. if (ret == 0 && pkt2.data != pkt->data) {
  458. if ((ret = av_copy_packet(&pkt2, pkt)) < 0) {
  459. av_free(pkt2.data);
  460. return ret;
  461. }
  462. ret = 1;
  463. }
  464. if (ret > 0) {
  465. av_packet_unref(pkt);
  466. pkt2.buf = av_buffer_create(pkt2.data, pkt2.size,
  467. av_buffer_default_free, NULL, 0);
  468. if (!pkt2.buf) {
  469. av_free(pkt2.data);
  470. return AVERROR(ENOMEM);
  471. }
  472. }
  473. *pkt = pkt2;
  474. }
  475. return 0;
  476. }
  477. /* Returns true if the packet dts is greater or equal to the specified outpoint. */
  478. static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
  479. {
  480. if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
  481. return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
  482. cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
  483. }
  484. return 0;
  485. }
  486. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  487. {
  488. ConcatContext *cat = avf->priv_data;
  489. int ret;
  490. int64_t delta;
  491. ConcatStream *cs;
  492. AVStream *st;
  493. if (cat->eof)
  494. return AVERROR_EOF;
  495. if (!cat->avf)
  496. return AVERROR(EIO);
  497. while (1) {
  498. ret = av_read_frame(cat->avf, pkt);
  499. if (ret == AVERROR_EOF || packet_after_outpoint(cat, pkt)) {
  500. if (ret == 0)
  501. av_packet_unref(pkt);
  502. if ((ret = open_next_file(avf)) < 0)
  503. return ret;
  504. continue;
  505. }
  506. if (ret < 0)
  507. return ret;
  508. if ((ret = match_streams(avf)) < 0) {
  509. av_packet_unref(pkt);
  510. return ret;
  511. }
  512. cs = &cat->cur_file->streams[pkt->stream_index];
  513. if (cs->out_stream_index < 0) {
  514. av_packet_unref(pkt);
  515. continue;
  516. }
  517. pkt->stream_index = cs->out_stream_index;
  518. break;
  519. }
  520. if ((ret = filter_packet(avf, cs, pkt)))
  521. return ret;
  522. st = cat->avf->streams[pkt->stream_index];
  523. av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
  524. (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
  525. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  526. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  527. delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
  528. AV_TIME_BASE_Q,
  529. cat->avf->streams[pkt->stream_index]->time_base);
  530. if (pkt->pts != AV_NOPTS_VALUE)
  531. pkt->pts += delta;
  532. if (pkt->dts != AV_NOPTS_VALUE)
  533. pkt->dts += delta;
  534. av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
  535. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  536. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  537. if (cat->cur_file->metadata) {
  538. uint8_t* metadata;
  539. int metadata_len;
  540. char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
  541. if (!packed_metadata)
  542. return AVERROR(ENOMEM);
  543. if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
  544. av_freep(&packed_metadata);
  545. return AVERROR(ENOMEM);
  546. }
  547. memcpy(metadata, packed_metadata, metadata_len);
  548. av_freep(&packed_metadata);
  549. }
  550. return ret;
  551. }
  552. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  553. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  554. {
  555. *ts = av_rescale_q (* ts, tb_in, tb_out);
  556. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  557. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  558. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  559. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  560. }
  561. static int try_seek(AVFormatContext *avf, int stream,
  562. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  563. {
  564. ConcatContext *cat = avf->priv_data;
  565. int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
  566. ts -= t0;
  567. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  568. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  569. if (stream >= 0) {
  570. if (stream >= cat->avf->nb_streams)
  571. return AVERROR(EIO);
  572. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  573. &min_ts, &ts, &max_ts);
  574. }
  575. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  576. }
  577. static int real_seek(AVFormatContext *avf, int stream,
  578. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  579. {
  580. ConcatContext *cat = avf->priv_data;
  581. int ret, left, right;
  582. if (stream >= 0) {
  583. if (stream >= avf->nb_streams)
  584. return AVERROR(EINVAL);
  585. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  586. &min_ts, &ts, &max_ts);
  587. }
  588. left = 0;
  589. right = cat->nb_files;
  590. while (right - left > 1) {
  591. int mid = (left + right) / 2;
  592. if (ts < cat->files[mid].start_time)
  593. right = mid;
  594. else
  595. left = mid;
  596. }
  597. if ((ret = open_file(avf, left)) < 0)
  598. return ret;
  599. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  600. if (ret < 0 &&
  601. left < cat->nb_files - 1 &&
  602. cat->files[left + 1].start_time < max_ts) {
  603. if ((ret = open_file(avf, left + 1)) < 0)
  604. return ret;
  605. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  606. }
  607. return ret;
  608. }
  609. static int concat_seek(AVFormatContext *avf, int stream,
  610. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  611. {
  612. ConcatContext *cat = avf->priv_data;
  613. ConcatFile *cur_file_saved = cat->cur_file;
  614. AVFormatContext *cur_avf_saved = cat->avf;
  615. int ret;
  616. if (!cat->seekable)
  617. return AVERROR(ESPIPE); /* XXX: can we use it? */
  618. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  619. return AVERROR(ENOSYS);
  620. cat->avf = NULL;
  621. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
  622. if (cat->avf)
  623. avformat_close_input(&cat->avf);
  624. cat->avf = cur_avf_saved;
  625. cat->cur_file = cur_file_saved;
  626. } else {
  627. avformat_close_input(&cur_avf_saved);
  628. cat->eof = 0;
  629. }
  630. return ret;
  631. }
  632. #define OFFSET(x) offsetof(ConcatContext, x)
  633. #define DEC AV_OPT_FLAG_DECODING_PARAM
  634. static const AVOption options[] = {
  635. { "safe", "enable safe mode",
  636. OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
  637. { "auto_convert", "automatically convert bitstream format",
  638. OFFSET(auto_convert), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
  639. { NULL }
  640. };
  641. static const AVClass concat_class = {
  642. .class_name = "concat demuxer",
  643. .item_name = av_default_item_name,
  644. .option = options,
  645. .version = LIBAVUTIL_VERSION_INT,
  646. };
  647. AVInputFormat ff_concat_demuxer = {
  648. .name = "concat",
  649. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  650. .priv_data_size = sizeof(ConcatContext),
  651. .read_probe = concat_probe,
  652. .read_header = concat_read_header,
  653. .read_packet = concat_read_packet,
  654. .read_close = concat_read_close,
  655. .read_seek2 = concat_seek,
  656. .priv_class = &concat_class,
  657. };