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.

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