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