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.

796 lines
26KB

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