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.

781 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. AVBSFContext *bsf;
  35. int out_stream_index;
  36. } ConcatStream;
  37. typedef struct {
  38. char *url;
  39. int64_t start_time;
  40. int64_t file_start_time;
  41. int64_t file_inpoint;
  42. int64_t duration;
  43. int64_t next_dts;
  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 (proto && !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->next_dts = AV_NOPTS_VALUE;
  138. file->inpoint = AV_NOPTS_VALUE;
  139. file->outpoint = AV_NOPTS_VALUE;
  140. return 0;
  141. fail:
  142. av_free(url);
  143. av_free(filename);
  144. return ret;
  145. }
  146. static int copy_stream_props(AVStream *st, AVStream *source_st)
  147. {
  148. int ret;
  149. if (st->codecpar->codec_id || !source_st->codecpar->codec_id) {
  150. if (st->codecpar->extradata_size < source_st->codecpar->extradata_size) {
  151. if (st->codecpar->extradata) {
  152. av_freep(&st->codecpar->extradata);
  153. st->codecpar->extradata_size = 0;
  154. }
  155. ret = ff_alloc_extradata(st->codecpar,
  156. source_st->codecpar->extradata_size);
  157. if (ret < 0)
  158. return ret;
  159. }
  160. memcpy(st->codecpar->extradata, source_st->codecpar->extradata,
  161. source_st->codecpar->extradata_size);
  162. return 0;
  163. }
  164. if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)
  165. return ret;
  166. st->r_frame_rate = source_st->r_frame_rate;
  167. st->avg_frame_rate = source_st->avg_frame_rate;
  168. st->sample_aspect_ratio = source_st->sample_aspect_ratio;
  169. avpriv_set_pts_info(st, 64, source_st->time_base.num, source_st->time_base.den);
  170. av_dict_copy(&st->metadata, source_st->metadata, 0);
  171. return 0;
  172. }
  173. static int detect_stream_specific(AVFormatContext *avf, int idx)
  174. {
  175. ConcatContext *cat = avf->priv_data;
  176. AVStream *st = cat->avf->streams[idx];
  177. ConcatStream *cs = &cat->cur_file->streams[idx];
  178. const AVBitStreamFilter *filter;
  179. AVBSFContext *bsf;
  180. int ret;
  181. if (cat->auto_convert && st->codecpar->codec_id == AV_CODEC_ID_H264) {
  182. if (!st->codecpar->extradata_size ||
  183. (st->codecpar->extradata_size >= 3 && AV_RB24(st->codecpar->extradata) == 1) ||
  184. (st->codecpar->extradata_size >= 4 && AV_RB32(st->codecpar->extradata) == 1))
  185. return 0;
  186. av_log(cat->avf, AV_LOG_INFO,
  187. "Auto-inserting h264_mp4toannexb bitstream filter\n");
  188. filter = av_bsf_get_by_name("h264_mp4toannexb");
  189. if (!filter) {
  190. av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb bitstream filter "
  191. "required for H.264 streams\n");
  192. return AVERROR_BSF_NOT_FOUND;
  193. }
  194. ret = av_bsf_alloc(filter, &bsf);
  195. if (ret < 0)
  196. return ret;
  197. cs->bsf = bsf;
  198. ret = avcodec_parameters_copy(bsf->par_in, st->codecpar);
  199. if (ret < 0)
  200. return ret;
  201. ret = av_bsf_init(bsf);
  202. if (ret < 0)
  203. return ret;
  204. ret = avcodec_parameters_copy(st->codecpar, bsf->par_out);
  205. if (ret < 0)
  206. return ret;
  207. }
  208. return 0;
  209. }
  210. static int match_streams_one_to_one(AVFormatContext *avf)
  211. {
  212. ConcatContext *cat = avf->priv_data;
  213. AVStream *st;
  214. int i, ret;
  215. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
  216. if (i < avf->nb_streams) {
  217. st = avf->streams[i];
  218. } else {
  219. if (!(st = avformat_new_stream(avf, NULL)))
  220. return AVERROR(ENOMEM);
  221. }
  222. if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
  223. return ret;
  224. cat->cur_file->streams[i].out_stream_index = i;
  225. }
  226. return 0;
  227. }
  228. static int match_streams_exact_id(AVFormatContext *avf)
  229. {
  230. ConcatContext *cat = avf->priv_data;
  231. AVStream *st;
  232. int i, j, ret;
  233. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
  234. st = cat->avf->streams[i];
  235. for (j = 0; j < avf->nb_streams; j++) {
  236. if (avf->streams[j]->id == st->id) {
  237. av_log(avf, AV_LOG_VERBOSE,
  238. "Match slave stream #%d with stream #%d id 0x%x\n",
  239. i, j, st->id);
  240. if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
  241. return ret;
  242. cat->cur_file->streams[i].out_stream_index = j;
  243. }
  244. }
  245. }
  246. return 0;
  247. }
  248. static int match_streams(AVFormatContext *avf)
  249. {
  250. ConcatContext *cat = avf->priv_data;
  251. ConcatStream *map;
  252. int i, ret;
  253. if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
  254. return 0;
  255. map = av_realloc(cat->cur_file->streams,
  256. cat->avf->nb_streams * sizeof(*map));
  257. if (!map)
  258. return AVERROR(ENOMEM);
  259. cat->cur_file->streams = map;
  260. memset(map + cat->cur_file->nb_streams, 0,
  261. (cat->avf->nb_streams - cat->cur_file->nb_streams) * sizeof(*map));
  262. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
  263. map[i].out_stream_index = -1;
  264. if ((ret = detect_stream_specific(avf, i)) < 0)
  265. return ret;
  266. }
  267. switch (cat->stream_match_mode) {
  268. case MATCH_ONE_TO_ONE:
  269. ret = match_streams_one_to_one(avf);
  270. break;
  271. case MATCH_EXACT_ID:
  272. ret = match_streams_exact_id(avf);
  273. break;
  274. default:
  275. ret = AVERROR_BUG;
  276. }
  277. if (ret < 0)
  278. return ret;
  279. cat->cur_file->nb_streams = cat->avf->nb_streams;
  280. return 0;
  281. }
  282. static int open_file(AVFormatContext *avf, unsigned fileno)
  283. {
  284. ConcatContext *cat = avf->priv_data;
  285. ConcatFile *file = &cat->files[fileno];
  286. int ret;
  287. if (cat->avf)
  288. avformat_close_input(&cat->avf);
  289. cat->avf = avformat_alloc_context();
  290. if (!cat->avf)
  291. return AVERROR(ENOMEM);
  292. cat->avf->flags |= avf->flags & ~AVFMT_FLAG_CUSTOM_IO;
  293. cat->avf->interrupt_callback = avf->interrupt_callback;
  294. if ((ret = ff_copy_whiteblacklists(cat->avf, avf)) < 0)
  295. return ret;
  296. if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
  297. (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
  298. av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
  299. avformat_close_input(&cat->avf);
  300. return ret;
  301. }
  302. cat->cur_file = file;
  303. if (file->start_time == AV_NOPTS_VALUE)
  304. file->start_time = !fileno ? 0 :
  305. cat->files[fileno - 1].start_time +
  306. cat->files[fileno - 1].duration;
  307. file->file_start_time = (cat->avf->start_time == AV_NOPTS_VALUE) ? 0 : cat->avf->start_time;
  308. file->file_inpoint = (file->inpoint == AV_NOPTS_VALUE) ? file->file_start_time : file->inpoint;
  309. if (file->duration == AV_NOPTS_VALUE && file->outpoint != AV_NOPTS_VALUE)
  310. file->duration = file->outpoint - file->file_inpoint;
  311. if (cat->segment_time_metadata) {
  312. av_dict_set_int(&file->metadata, "lavf.concatdec.start_time", file->start_time, 0);
  313. if (file->duration != AV_NOPTS_VALUE)
  314. av_dict_set_int(&file->metadata, "lavf.concatdec.duration", file->duration, 0);
  315. }
  316. if ((ret = match_streams(avf)) < 0)
  317. return ret;
  318. if (file->inpoint != AV_NOPTS_VALUE) {
  319. if ((ret = avformat_seek_file(cat->avf, -1, INT64_MIN, file->inpoint, file->inpoint, 0)) < 0)
  320. return ret;
  321. }
  322. return 0;
  323. }
  324. static int concat_read_close(AVFormatContext *avf)
  325. {
  326. ConcatContext *cat = avf->priv_data;
  327. unsigned i, j;
  328. for (i = 0; i < cat->nb_files; i++) {
  329. av_freep(&cat->files[i].url);
  330. for (j = 0; j < cat->files[i].nb_streams; j++) {
  331. if (cat->files[i].streams[j].bsf)
  332. av_bsf_free(&cat->files[i].streams[j].bsf);
  333. }
  334. av_freep(&cat->files[i].streams);
  335. av_dict_free(&cat->files[i].metadata);
  336. }
  337. if (cat->avf)
  338. avformat_close_input(&cat->avf);
  339. av_freep(&cat->files);
  340. return 0;
  341. }
  342. static int concat_read_header(AVFormatContext *avf)
  343. {
  344. ConcatContext *cat = avf->priv_data;
  345. uint8_t buf[4096];
  346. uint8_t *cursor, *keyword;
  347. int ret, line = 0, i;
  348. unsigned nb_files_alloc = 0;
  349. ConcatFile *file = NULL;
  350. int64_t time = 0;
  351. while (1) {
  352. if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
  353. break;
  354. line++;
  355. cursor = buf;
  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 < 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. return 0;
  455. fail:
  456. concat_read_close(avf);
  457. return ret;
  458. }
  459. static int open_next_file(AVFormatContext *avf)
  460. {
  461. ConcatContext *cat = avf->priv_data;
  462. unsigned fileno = cat->cur_file - cat->files;
  463. if (cat->cur_file->duration == AV_NOPTS_VALUE) {
  464. if (cat->avf->duration > 0 || cat->cur_file->next_dts == AV_NOPTS_VALUE) {
  465. cat->cur_file->duration = cat->avf->duration;
  466. } else {
  467. cat->cur_file->duration = cat->cur_file->next_dts;
  468. }
  469. cat->cur_file->duration -= (cat->cur_file->file_inpoint - cat->cur_file->file_start_time);
  470. }
  471. if (++fileno >= cat->nb_files) {
  472. cat->eof = 1;
  473. return AVERROR_EOF;
  474. }
  475. return open_file(avf, fileno);
  476. }
  477. static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
  478. {
  479. int ret;
  480. if (cs->bsf) {
  481. ret = av_bsf_send_packet(cs->bsf, pkt);
  482. if (ret < 0) {
  483. av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
  484. "failed to send input packet\n");
  485. av_packet_unref(pkt);
  486. return ret;
  487. }
  488. while (!ret)
  489. ret = av_bsf_receive_packet(cs->bsf, pkt);
  490. if (ret < 0 && (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)) {
  491. av_log(avf, AV_LOG_ERROR, "h264_mp4toannexb filter "
  492. "failed to receive output packet\n");
  493. return ret;
  494. }
  495. }
  496. return 0;
  497. }
  498. /* Returns true if the packet dts is greater or equal to the specified outpoint. */
  499. static int packet_after_outpoint(ConcatContext *cat, AVPacket *pkt)
  500. {
  501. if (cat->cur_file->outpoint != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE) {
  502. return av_compare_ts(pkt->dts, cat->avf->streams[pkt->stream_index]->time_base,
  503. cat->cur_file->outpoint, AV_TIME_BASE_Q) >= 0;
  504. }
  505. return 0;
  506. }
  507. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  508. {
  509. ConcatContext *cat = avf->priv_data;
  510. int ret;
  511. int64_t delta;
  512. ConcatStream *cs;
  513. AVStream *st;
  514. if (cat->eof)
  515. return AVERROR_EOF;
  516. if (!cat->avf)
  517. return AVERROR(EIO);
  518. while (1) {
  519. ret = av_read_frame(cat->avf, pkt);
  520. if (ret == AVERROR_EOF) {
  521. if ((ret = open_next_file(avf)) < 0)
  522. return ret;
  523. continue;
  524. }
  525. if (ret < 0)
  526. return ret;
  527. if ((ret = match_streams(avf)) < 0) {
  528. av_packet_unref(pkt);
  529. return ret;
  530. }
  531. if (packet_after_outpoint(cat, pkt)) {
  532. av_packet_unref(pkt);
  533. if ((ret = open_next_file(avf)) < 0)
  534. return ret;
  535. continue;
  536. }
  537. cs = &cat->cur_file->streams[pkt->stream_index];
  538. if (cs->out_stream_index < 0) {
  539. av_packet_unref(pkt);
  540. continue;
  541. }
  542. pkt->stream_index = cs->out_stream_index;
  543. break;
  544. }
  545. if ((ret = filter_packet(avf, cs, pkt)))
  546. return ret;
  547. st = cat->avf->streams[pkt->stream_index];
  548. av_log(avf, AV_LOG_DEBUG, "file:%d stream:%d pts:%s pts_time:%s dts:%s dts_time:%s",
  549. (unsigned)(cat->cur_file - cat->files), pkt->stream_index,
  550. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  551. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  552. delta = av_rescale_q(cat->cur_file->start_time - cat->cur_file->file_inpoint,
  553. AV_TIME_BASE_Q,
  554. cat->avf->streams[pkt->stream_index]->time_base);
  555. if (pkt->pts != AV_NOPTS_VALUE)
  556. pkt->pts += delta;
  557. if (pkt->dts != AV_NOPTS_VALUE)
  558. pkt->dts += delta;
  559. av_log(avf, AV_LOG_DEBUG, " -> pts:%s pts_time:%s dts:%s dts_time:%s\n",
  560. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &st->time_base),
  561. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &st->time_base));
  562. if (cat->cur_file->metadata) {
  563. uint8_t* metadata;
  564. int metadata_len;
  565. char* packed_metadata = av_packet_pack_dictionary(cat->cur_file->metadata, &metadata_len);
  566. if (!packed_metadata)
  567. return AVERROR(ENOMEM);
  568. if (!(metadata = av_packet_new_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, metadata_len))) {
  569. av_freep(&packed_metadata);
  570. return AVERROR(ENOMEM);
  571. }
  572. memcpy(metadata, packed_metadata, metadata_len);
  573. av_freep(&packed_metadata);
  574. }
  575. if (cat->cur_file->duration == AV_NOPTS_VALUE && st->cur_dts != AV_NOPTS_VALUE) {
  576. int64_t next_dts = av_rescale_q(st->cur_dts, st->time_base, AV_TIME_BASE_Q);
  577. if (cat->cur_file->next_dts == AV_NOPTS_VALUE || next_dts > cat->cur_file->next_dts) {
  578. cat->cur_file->next_dts = next_dts;
  579. }
  580. }
  581. return ret;
  582. }
  583. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  584. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  585. {
  586. *ts = av_rescale_q (* ts, tb_in, tb_out);
  587. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  588. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  589. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  590. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  591. }
  592. static int try_seek(AVFormatContext *avf, int stream,
  593. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  594. {
  595. ConcatContext *cat = avf->priv_data;
  596. int64_t t0 = cat->cur_file->start_time - cat->cur_file->file_inpoint;
  597. ts -= t0;
  598. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  599. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  600. if (stream >= 0) {
  601. if (stream >= cat->avf->nb_streams)
  602. return AVERROR(EIO);
  603. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  604. &min_ts, &ts, &max_ts);
  605. }
  606. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  607. }
  608. static int real_seek(AVFormatContext *avf, int stream,
  609. int64_t min_ts, int64_t ts, int64_t max_ts, int flags, AVFormatContext *cur_avf)
  610. {
  611. ConcatContext *cat = avf->priv_data;
  612. int ret, left, right;
  613. if (stream >= 0) {
  614. if (stream >= avf->nb_streams)
  615. return AVERROR(EINVAL);
  616. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  617. &min_ts, &ts, &max_ts);
  618. }
  619. left = 0;
  620. right = cat->nb_files;
  621. while (right - left > 1) {
  622. int mid = (left + right) / 2;
  623. if (ts < cat->files[mid].start_time)
  624. right = mid;
  625. else
  626. left = mid;
  627. }
  628. if (cat->cur_file != &cat->files[left]) {
  629. if ((ret = open_file(avf, left)) < 0)
  630. return ret;
  631. } else {
  632. cat->avf = cur_avf;
  633. }
  634. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  635. if (ret < 0 &&
  636. left < cat->nb_files - 1 &&
  637. cat->files[left + 1].start_time < max_ts) {
  638. if (cat->cur_file == &cat->files[left])
  639. cat->avf = NULL;
  640. if ((ret = open_file(avf, left + 1)) < 0)
  641. return ret;
  642. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  643. }
  644. return ret;
  645. }
  646. static int concat_seek(AVFormatContext *avf, int stream,
  647. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  648. {
  649. ConcatContext *cat = avf->priv_data;
  650. ConcatFile *cur_file_saved = cat->cur_file;
  651. AVFormatContext *cur_avf_saved = cat->avf;
  652. int ret;
  653. if (!cat->seekable)
  654. return AVERROR(ESPIPE); /* XXX: can we use it? */
  655. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  656. return AVERROR(ENOSYS);
  657. cat->avf = NULL;
  658. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags, cur_avf_saved)) < 0) {
  659. if (cat->cur_file != cur_file_saved) {
  660. if (cat->avf)
  661. avformat_close_input(&cat->avf);
  662. }
  663. cat->avf = cur_avf_saved;
  664. cat->cur_file = cur_file_saved;
  665. } else {
  666. if (cat->cur_file != cur_file_saved) {
  667. avformat_close_input(&cur_avf_saved);
  668. }
  669. cat->eof = 0;
  670. }
  671. return ret;
  672. }
  673. #define OFFSET(x) offsetof(ConcatContext, x)
  674. #define DEC AV_OPT_FLAG_DECODING_PARAM
  675. static const AVOption options[] = {
  676. { "safe", "enable safe mode",
  677. OFFSET(safe), AV_OPT_TYPE_BOOL, {.i64 = 1}, -1, 1, DEC },
  678. { "auto_convert", "automatically convert bitstream format",
  679. OFFSET(auto_convert), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, DEC },
  680. { "segment_time_metadata", "output file segment start time and duration as packet metadata",
  681. OFFSET(segment_time_metadata), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
  682. { NULL }
  683. };
  684. static const AVClass concat_class = {
  685. .class_name = "concat demuxer",
  686. .item_name = av_default_item_name,
  687. .option = options,
  688. .version = LIBAVUTIL_VERSION_INT,
  689. };
  690. AVInputFormat ff_concat_demuxer = {
  691. .name = "concat",
  692. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  693. .priv_data_size = sizeof(ConcatContext),
  694. .read_probe = concat_probe,
  695. .read_header = concat_read_header,
  696. .read_packet = concat_read_packet,
  697. .read_close = concat_read_close,
  698. .read_seek2 = concat_seek,
  699. .priv_class = &concat_class,
  700. };