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.

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