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.

731 lines
24KB

  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 (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)
  284. file->duration = file->outpoint - file->file_inpoint;
  285. if ((ret = match_streams(avf)) < 0)
  286. return ret;
  287. if (file->inpoint != AV_NOPTS_VALUE) {
  288. if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
  289. return ret;
  290. }
  291. return 0;
  292. }
  293. static int concat_read_close(AVFormatContext *avf)
  294. {
  295. ConcatContext *cat = avf->priv_data;
  296. unsigned i;
  297. if (cat->avf)
  298. avformat_close_input(&cat->avf);
  299. for (i = 0; i < cat->nb_files; i++) {
  300. av_freep(&cat->files[i].url);
  301. av_freep(&cat->files[i].streams);
  302. av_dict_free(&cat->files[i].metadata);
  303. }
  304. av_freep(&cat->files);
  305. return 0;
  306. }
  307. static int concat_read_header(AVFormatContext *avf)
  308. {
  309. ConcatContext *cat = avf->priv_data;
  310. uint8_t buf[4096];
  311. uint8_t *cursor, *keyword;
  312. int ret, line = 0, i;
  313. unsigned nb_files_alloc = 0;
  314. ConcatFile *file = NULL;
  315. int64_t time = 0;
  316. while (1) {
  317. if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
  318. break;
  319. line++;
  320. cursor = buf;
  321. keyword = get_keyword(&cursor);
  322. if (!*keyword || *keyword == '#')
  323. continue;
  324. if (!strcmp(keyword, "file")) {
  325. char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
  326. if (!filename) {
  327. av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
  328. FAIL(AVERROR_INVALIDDATA);
  329. }
  330. if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
  331. goto fail;
  332. } else if (!strcmp(keyword, "duration") || !strcmp(keyword, "inpoint") || !strcmp(keyword, "outpoint")) {
  333. char *dur_str = get_keyword(&cursor);
  334. int64_t dur;
  335. if (!file) {
  336. av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
  337. line, keyword);
  338. FAIL(AVERROR_INVALIDDATA);
  339. }
  340. if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
  341. av_log(avf, AV_LOG_ERROR, "Line %d: invalid %s '%s'\n",
  342. line, keyword, dur_str);
  343. goto fail;
  344. }
  345. if (!strcmp(keyword, "duration"))
  346. file->duration = dur;
  347. else if (!strcmp(keyword, "inpoint"))
  348. file->inpoint = dur;
  349. else if (!strcmp(keyword, "outpoint"))
  350. file->outpoint = dur;
  351. } else if (!strcmp(keyword, "file_packet_metadata")) {
  352. char *metadata;
  353. if (!file) {
  354. av_log(avf, AV_LOG_ERROR, "Line %d: %s without file\n",
  355. line, keyword);
  356. FAIL(AVERROR_INVALIDDATA);
  357. }
  358. metadata = av_get_token((const char **)&cursor, SPACE_CHARS);
  359. if (!metadata) {
  360. av_log(avf, AV_LOG_ERROR, "Line %d: packet metadata required\n", line);
  361. FAIL(AVERROR_INVALIDDATA);
  362. }
  363. if ((ret = av_dict_parse_string(&file->metadata, metadata, "=", "", 0)) < 0) {
  364. av_log(avf, AV_LOG_ERROR, "Line %d: failed to parse metadata string\n", line);
  365. av_freep(&metadata);
  366. FAIL(AVERROR_INVALIDDATA);
  367. }
  368. av_freep(&metadata);
  369. } else if (!strcmp(keyword, "stream")) {
  370. if (!avformat_new_stream(avf, NULL))
  371. FAIL(AVERROR(ENOMEM));
  372. } else if (!strcmp(keyword, "exact_stream_id")) {
  373. if (!avf->nb_streams) {
  374. av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
  375. line);
  376. FAIL(AVERROR_INVALIDDATA);
  377. }
  378. avf->streams[avf->nb_streams - 1]->id =
  379. strtol(get_keyword(&cursor), NULL, 0);
  380. } else if (!strcmp(keyword, "ffconcat")) {
  381. char *ver_kw = get_keyword(&cursor);
  382. char *ver_val = get_keyword(&cursor);
  383. if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
  384. av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
  385. FAIL(AVERROR_INVALIDDATA);
  386. }
  387. if (cat->safe < 0)
  388. cat->safe = 1;
  389. } else {
  390. av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
  391. line, keyword);
  392. FAIL(AVERROR_INVALIDDATA);
  393. }
  394. }
  395. if (ret < 0)
  396. goto fail;
  397. if (!cat->nb_files)
  398. FAIL(AVERROR_INVALIDDATA);
  399. for (i = 0; i < cat->nb_files; i++) {
  400. if (cat->files[i].start_time == AV_NOPTS_VALUE)
  401. cat->files[i].start_time = time;
  402. else
  403. time = cat->files[i].start_time;
  404. if (cat->files[i].duration == AV_NOPTS_VALUE) {
  405. if (cat->files[i].inpoint == AV_NOPTS_VALUE || cat->files[i].outpoint == AV_NOPTS_VALUE)
  406. break;
  407. cat->files[i].duration = cat->files[i].outpoint - cat->files[i].inpoint;
  408. }
  409. time += cat->files[i].duration;
  410. }
  411. if (i == cat->nb_files) {
  412. avf->duration = time;
  413. cat->seekable = 1;
  414. }
  415. cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
  416. MATCH_ONE_TO_ONE;
  417. if ((ret = open_file(avf, 0)) < 0)
  418. goto fail;
  419. return 0;
  420. fail:
  421. concat_read_close(avf);
  422. return ret;
  423. }
  424. static int open_next_file(AVFormatContext *avf)
  425. {
  426. ConcatContext *cat = avf->priv_data;
  427. unsigned fileno = cat->cur_file - cat->files;
  428. if (cat->cur_file->duration == AV_NOPTS_VALUE) {
  429. cat->cur_file->duration = cat->avf->duration;
  430. if (cat->cur_file->inpoint != AV_NOPTS_VALUE)
  431. cat->cur_file->duration -= (cat->cur_file->inpoint - cat->cur_file->file_start_time);
  432. if (cat->cur_file->outpoint != AV_NOPTS_VALUE)
  433. cat->cur_file->duration -= cat->avf->duration - (cat->cur_file->outpoint - cat->cur_file->file_start_time);
  434. }
  435. if (++fileno >= cat->nb_files) {
  436. cat->eof = 1;
  437. return AVERROR_EOF;
  438. }
  439. return open_file(avf, fileno);
  440. }
  441. static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
  442. {
  443. AVStream *st = avf->streams[cs->out_stream_index];
  444. AVBitStreamFilterContext *bsf;
  445. AVPacket pkt2;
  446. int ret;
  447. av_assert0(cs->out_stream_index >= 0);
  448. for (bsf = cs->bsf; bsf; bsf = bsf->next) {
  449. pkt2 = *pkt;
  450. ret = av_bitstream_filter_filter(bsf, st->codec, NULL,
  451. &pkt2.data, &pkt2.size,
  452. pkt->data, pkt->size,
  453. !!(pkt->flags & AV_PKT_FLAG_KEY));
  454. if (ret < 0) {
  455. av_packet_unref(pkt);
  456. return ret;
  457. }
  458. av_assert0(pkt2.buf);
  459. if (ret == 0 && pkt2.data != pkt->data) {
  460. if ((ret = av_copy_packet(&pkt2, pkt)) < 0) {
  461. av_free(pkt2.data);
  462. return ret;
  463. }
  464. ret = 1;
  465. }
  466. if (ret > 0) {
  467. av_packet_unref(pkt);
  468. pkt2.buf = av_buffer_create(pkt2.data, pkt2.size,
  469. av_buffer_default_free, NULL, 0);
  470. if (!pkt2.buf) {
  471. av_free(pkt2.data);
  472. return AVERROR(ENOMEM);
  473. }
  474. }
  475. *pkt = pkt2;
  476. }
  477. return 0;
  478. }
  479. /* Returns true if the packet dts is greater or equal to the specified outpoint. */
  480. static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
  481. {
  482. if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
  483. return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
  484. cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
  485. }
  486. return 0;
  487. }
  488. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  489. {
  490. ConcatContext *cat = avf->priv_data;
  491. int ret;
  492. int64_t delta;
  493. ConcatStream *cs;
  494. AVStream *st;
  495. if (cat->eof)
  496. return AVERROR_EOF;
  497. if (!cat->avf)
  498. return AVERROR(EIO);
  499. while (1) {
  500. ret = av_read_frame(cat->avf, pkt);
  501. if (ret == AVERROR_EOF || packet_after_outpoint(cat, pkt)) {
  502. if (ret == 0)
  503. av_packet_unref(pkt);
  504. if ((ret = open_next_file(avf)) < 0)
  505. return ret;
  506. continue;
  507. }
  508. if (ret < 0)
  509. return ret;
  510. if ((ret = match_streams(avf)) < 0) {
  511. av_packet_unref(pkt);
  512. return ret;
  513. }
  514. cs = &cat->cur_file->streams[pkt->stream_index];
  515. if (cs->out_stream_index < 0) {
  516. av_packet_unref(pkt);
  517. continue;
  518. }
  519. pkt->stream_index = cs->out_stream_index;
  520. break;
  521. }
  522. if ((ret = filter_packet(avf, cs, pkt)))
  523. return ret;
  524. st = cat->avf->streams[pkt->stream_index];
  525. av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
  526. (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
  527. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  528. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  529. delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
  530. AV_TIME_BASE_Q,
  531. cat->avf->streams[pkt->stream_index]->time_base);
  532. if (pkt->pts != AV_NOPTS_VALUE)
  533. pkt->pts += delta;
  534. if (pkt->dts != AV_NOPTS_VALUE)
  535. pkt->dts += delta;
  536. av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
  537. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  538. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  539. if (cat->cur_file->metadata) {
  540. uint8_t* metadata;
  541. int metadata_len;
  542. char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
  543. if (!packed_metadata)
  544. return AVERROR(ENOMEM);
  545. if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
  546. av_freep(&packed_metadata);
  547. return AVERROR(ENOMEM);
  548. }
  549. memcpy(metadata, packed_metadata, metadata_len);
  550. av_freep(&packed_metadata);
  551. }
  552. return ret;
  553. }
  554. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  555. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  556. {
  557. *ts = av_rescale_q (* ts, tb_in, tb_out);
  558. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  559. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  560. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  561. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  562. }
  563. static int try_seek(AVFormatContext *avf, int stream,
  564. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  565. {
  566. ConcatContext *cat = avf->priv_data;
  567. int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
  568. ts -= t0;
  569. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  570. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  571. if (stream >= 0) {
  572. if (stream >= cat->avf->nb_streams)
  573. return AVERROR(EIO);
  574. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  575. &min_ts, &ts, &max_ts);
  576. }
  577. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  578. }
  579. static int real_seek(AVFormatContext *avf, int stream,
  580. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  581. {
  582. ConcatContext *cat = avf->priv_data;
  583. int ret, left, right;
  584. if (stream >= 0) {
  585. if (stream >= avf->nb_streams)
  586. return AVERROR(EINVAL);
  587. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  588. &min_ts, &ts, &max_ts);
  589. }
  590. left = 0;
  591. right = cat->nb_files;
  592. while (right - left > 1) {
  593. int mid = (left + right) / 2;
  594. if (ts < cat->files[mid].start_time)
  595. right = mid;
  596. else
  597. left = mid;
  598. }
  599. if ((ret = open_file(avf, left)) < 0)
  600. return ret;
  601. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  602. if (ret < 0 &&
  603. left < cat->nb_files - 1 &&
  604. cat->files[left + 1].start_time < max_ts) {
  605. if ((ret = open_file(avf, left + 1)) < 0)
  606. return ret;
  607. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  608. }
  609. return ret;
  610. }
  611. static int concat_seek(AVFormatContext *avf, int stream,
  612. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  613. {
  614. ConcatContext *cat = avf->priv_data;
  615. ConcatFile *cur_file_saved = cat->cur_file;
  616. AVFormatContext *cur_avf_saved = cat->avf;
  617. int ret;
  618. if (!cat->seekable)
  619. return AVERROR(ESPIPE); /* XXX: can we use it? */
  620. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  621. return AVERROR(ENOSYS);
  622. cat->avf = NULL;
  623. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
  624. if (cat->avf)
  625. avformat_close_input(&cat->avf);
  626. cat->avf = cur_avf_saved;
  627. cat->cur_file = cur_file_saved;
  628. } else {
  629. avformat_close_input(&cur_avf_saved);
  630. cat->eof = 0;
  631. }
  632. return ret;
  633. }
  634. #define OFFSET(x) offsetof(ConcatContext, x)
  635. #define DEC AV_OPT_FLAG_DECODING_PARAM
  636. static const AVOption options[] = {
  637. { "safe", "enable safe mode",
  638. OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
  639. { "auto_convert", "automatically convert bitstream format",
  640. OFFSET(auto_convert), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, DEC },
  641. { NULL }
  642. };
  643. static const AVClass concat_class = {
  644. .class_name = "concat demuxer",
  645. .item_name = av_default_item_name,
  646. .option = options,
  647. .version = LIBAVUTIL_VERSION_INT,
  648. };
  649. AVInputFormat ff_concat_demuxer = {
  650. .name = "concat",
  651. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  652. .priv_data_size = sizeof(ConcatContext),
  653. .read_probe = concat_probe,
  654. .read_header = concat_read_header,
  655. .read_packet = concat_read_packet,
  656. .read_close = concat_read_close,
  657. .read_seek2 = concat_seek,
  658. .priv_class = &concat_class,
  659. };