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.

784 lines
25KB

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