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.

798 lines
26KB

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