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.

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