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.

412 lines
12KB

  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/avstring.h"
  21. #include "libavutil/opt.h"
  22. #include "libavutil/parseutils.h"
  23. #include "avformat.h"
  24. #include "internal.h"
  25. #include "url.h"
  26. typedef struct {
  27. char *url;
  28. int64_t start_time;
  29. int64_t duration;
  30. } ConcatFile;
  31. typedef struct {
  32. AVClass *class;
  33. ConcatFile *files;
  34. ConcatFile *cur_file;
  35. unsigned nb_files;
  36. AVFormatContext *avf;
  37. int safe;
  38. int seekable;
  39. } ConcatContext;
  40. static int concat_probe(AVProbeData *probe)
  41. {
  42. return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
  43. 0 : AVPROBE_SCORE_MAX;
  44. }
  45. static char *get_keyword(uint8_t **cursor)
  46. {
  47. char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
  48. *cursor += strcspn(*cursor, SPACE_CHARS);
  49. if (**cursor) {
  50. *((*cursor)++) = 0;
  51. *cursor += strspn(*cursor, SPACE_CHARS);
  52. }
  53. return ret;
  54. }
  55. static int safe_filename(const char *f)
  56. {
  57. const char *start = f;
  58. for (; *f; f++) {
  59. /* A-Za-z0-9_- */
  60. if (!((unsigned)((*f | 32) - 'a') < 26 ||
  61. (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
  62. if (f == start)
  63. return 0;
  64. else if (*f == '/')
  65. start = f + 1;
  66. else if (*f != '.')
  67. return 0;
  68. }
  69. }
  70. return 1;
  71. }
  72. #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
  73. static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
  74. unsigned *nb_files_alloc)
  75. {
  76. ConcatContext *cat = avf->priv_data;
  77. ConcatFile *file;
  78. char *url = NULL;
  79. size_t url_len;
  80. int ret;
  81. if (cat->safe > 0 && !safe_filename(filename)) {
  82. av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
  83. FAIL(AVERROR(EPERM));
  84. }
  85. url_len = strlen(avf->filename) + strlen(filename) + 16;
  86. if (!(url = av_malloc(url_len)))
  87. FAIL(AVERROR(ENOMEM));
  88. ff_make_absolute_url(url, url_len, avf->filename, filename);
  89. av_freep(&filename);
  90. if (cat->nb_files >= *nb_files_alloc) {
  91. size_t n = FFMAX(*nb_files_alloc * 2, 16);
  92. ConcatFile *new_files;
  93. if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
  94. !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
  95. FAIL(AVERROR(ENOMEM));
  96. cat->files = new_files;
  97. *nb_files_alloc = n;
  98. }
  99. file = &cat->files[cat->nb_files++];
  100. memset(file, 0, sizeof(*file));
  101. *rfile = file;
  102. file->url = url;
  103. file->start_time = AV_NOPTS_VALUE;
  104. file->duration = AV_NOPTS_VALUE;
  105. return 0;
  106. fail:
  107. av_free(url);
  108. av_free(filename);
  109. return ret;
  110. }
  111. static int open_file(AVFormatContext *avf, unsigned fileno)
  112. {
  113. ConcatContext *cat = avf->priv_data;
  114. ConcatFile *file = &cat->files[fileno];
  115. int ret;
  116. if (cat->avf)
  117. avformat_close_input(&cat->avf);
  118. if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
  119. (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
  120. av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
  121. return ret;
  122. }
  123. cat->cur_file = file;
  124. if (file->start_time == AV_NOPTS_VALUE)
  125. file->start_time = !fileno ? 0 :
  126. cat->files[fileno - 1].start_time +
  127. cat->files[fileno - 1].duration;
  128. return 0;
  129. }
  130. static int concat_read_close(AVFormatContext *avf)
  131. {
  132. ConcatContext *cat = avf->priv_data;
  133. unsigned i;
  134. if (cat->avf)
  135. avformat_close_input(&cat->avf);
  136. for (i = 0; i < cat->nb_files; i++)
  137. av_freep(&cat->files[i].url);
  138. av_freep(&cat->files);
  139. return 0;
  140. }
  141. static int concat_read_header(AVFormatContext *avf)
  142. {
  143. ConcatContext *cat = avf->priv_data;
  144. uint8_t buf[4096];
  145. uint8_t *cursor, *keyword;
  146. int ret, line = 0, i;
  147. unsigned nb_files_alloc = 0;
  148. ConcatFile *file = NULL;
  149. AVStream *st, *source_st;
  150. int64_t time = 0;
  151. while (1) {
  152. if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
  153. break;
  154. line++;
  155. cursor = buf;
  156. keyword = get_keyword(&cursor);
  157. if (!*keyword || *keyword == '#')
  158. continue;
  159. if (!strcmp(keyword, "file")) {
  160. char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
  161. if (!filename) {
  162. av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
  163. FAIL(AVERROR_INVALIDDATA);
  164. }
  165. if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
  166. FAIL(ret);
  167. } else if (!strcmp(keyword, "duration")) {
  168. char *dur_str = get_keyword(&cursor);
  169. int64_t dur;
  170. if (!file) {
  171. av_log(avf, AV_LOG_ERROR, "Line %d: duration without file\n",
  172. line);
  173. FAIL(AVERROR_INVALIDDATA);
  174. }
  175. if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
  176. av_log(avf, AV_LOG_ERROR, "Line %d: invalid duration '%s'\n",
  177. line, dur_str);
  178. FAIL(ret);
  179. }
  180. file->duration = dur;
  181. } else if (!strcmp(keyword, "ffconcat")) {
  182. char *ver_kw = get_keyword(&cursor);
  183. char *ver_val = get_keyword(&cursor);
  184. if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
  185. av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
  186. FAIL(AVERROR_INVALIDDATA);
  187. }
  188. if (cat->safe < 0)
  189. cat->safe = 1;
  190. } else {
  191. av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
  192. line, keyword);
  193. FAIL(AVERROR_INVALIDDATA);
  194. }
  195. }
  196. if (ret < 0)
  197. FAIL(ret);
  198. if (!cat->nb_files)
  199. FAIL(AVERROR_INVALIDDATA);
  200. for (i = 0; i < cat->nb_files; i++) {
  201. if (cat->files[i].start_time == AV_NOPTS_VALUE)
  202. cat->files[i].start_time = time;
  203. else
  204. time = cat->files[i].start_time;
  205. if (cat->files[i].duration == AV_NOPTS_VALUE)
  206. break;
  207. time += cat->files[i].duration;
  208. }
  209. if (i == cat->nb_files) {
  210. avf->duration = time;
  211. cat->seekable = 1;
  212. }
  213. if ((ret = open_file(avf, 0)) < 0)
  214. FAIL(ret);
  215. for (i = 0; i < cat->avf->nb_streams; i++) {
  216. if (!(st = avformat_new_stream(avf, NULL)))
  217. FAIL(AVERROR(ENOMEM));
  218. source_st = cat->avf->streams[i];
  219. if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
  220. FAIL(ret);
  221. st->r_frame_rate = source_st->r_frame_rate;
  222. st->avg_frame_rate = source_st->avg_frame_rate;
  223. st->time_base = source_st->time_base;
  224. st->sample_aspect_ratio = source_st->sample_aspect_ratio;
  225. }
  226. return 0;
  227. fail:
  228. concat_read_close(avf);
  229. return ret;
  230. }
  231. static int open_next_file(AVFormatContext *avf)
  232. {
  233. ConcatContext *cat = avf->priv_data;
  234. unsigned fileno = cat->cur_file - cat->files;
  235. if (cat->cur_file->duration == AV_NOPTS_VALUE)
  236. cat->cur_file->duration = cat->avf->duration;
  237. if (++fileno >= cat->nb_files)
  238. return AVERROR_EOF;
  239. return open_file(avf, fileno);
  240. }
  241. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  242. {
  243. ConcatContext *cat = avf->priv_data;
  244. int ret;
  245. int64_t delta;
  246. while (1) {
  247. if ((ret = av_read_frame(cat->avf, pkt)) != AVERROR_EOF ||
  248. (ret = open_next_file(avf)) < 0)
  249. break;
  250. }
  251. if (ret < 0)
  252. return ret;
  253. delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
  254. AV_TIME_BASE_Q,
  255. cat->avf->streams[pkt->stream_index]->time_base);
  256. if (pkt->pts != AV_NOPTS_VALUE)
  257. pkt->pts += delta;
  258. if (pkt->dts != AV_NOPTS_VALUE)
  259. pkt->dts += delta;
  260. return ret;
  261. }
  262. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  263. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  264. {
  265. *ts = av_rescale_q (* ts, tb_in, tb_out);
  266. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  267. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  268. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  269. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  270. }
  271. static int try_seek(AVFormatContext *avf, int stream,
  272. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  273. {
  274. ConcatContext *cat = avf->priv_data;
  275. int64_t t0 = cat->cur_file->start_time - cat->avf->start_time;
  276. ts -= t0;
  277. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  278. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  279. if (stream >= 0) {
  280. if (stream >= cat->avf->nb_streams)
  281. return AVERROR(EIO);
  282. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  283. &min_ts, &ts, &max_ts);
  284. }
  285. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  286. }
  287. static int real_seek(AVFormatContext *avf, int stream,
  288. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  289. {
  290. ConcatContext *cat = avf->priv_data;
  291. int ret, left, right;
  292. if (stream >= 0) {
  293. if (stream >= avf->nb_streams)
  294. return AVERROR(EINVAL);
  295. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  296. &min_ts, &ts, &max_ts);
  297. }
  298. left = 0;
  299. right = cat->nb_files;
  300. while (right - left > 1) {
  301. int mid = (left + right) / 2;
  302. if (ts < cat->files[mid].start_time)
  303. right = mid;
  304. else
  305. left = mid;
  306. }
  307. if ((ret = open_file(avf, left)) < 0)
  308. return ret;
  309. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  310. if (ret < 0 &&
  311. left < cat->nb_files - 1 &&
  312. cat->files[left + 1].start_time < max_ts) {
  313. if ((ret = open_file(avf, left + 1)) < 0)
  314. return ret;
  315. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  316. }
  317. return ret;
  318. }
  319. static int concat_seek(AVFormatContext *avf, int stream,
  320. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  321. {
  322. ConcatContext *cat = avf->priv_data;
  323. ConcatFile *cur_file_saved = cat->cur_file;
  324. AVFormatContext *cur_avf_saved = cat->avf;
  325. int ret;
  326. if (!cat->seekable)
  327. return AVERROR(ESPIPE); /* XXX: can we use it? */
  328. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  329. return AVERROR(ENOSYS);
  330. cat->avf = NULL;
  331. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
  332. if (cat->avf)
  333. avformat_close_input(&cat->avf);
  334. cat->avf = cur_avf_saved;
  335. cat->cur_file = cur_file_saved;
  336. } else {
  337. avformat_close_input(&cur_avf_saved);
  338. }
  339. return ret;
  340. }
  341. #define OFFSET(x) offsetof(ConcatContext, x)
  342. #define DEC AV_OPT_FLAG_DECODING_PARAM
  343. static const AVOption options[] = {
  344. { "safe", "enable safe mode",
  345. OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
  346. { NULL }
  347. };
  348. static const AVClass concat_class = {
  349. .class_name = "concat demuxer",
  350. .item_name = av_default_item_name,
  351. .option = options,
  352. .version = LIBAVUTIL_VERSION_INT,
  353. };
  354. AVInputFormat ff_concat_demuxer = {
  355. .name = "concat",
  356. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  357. .priv_data_size = sizeof(ConcatContext),
  358. .read_probe = concat_probe,
  359. .read_header = concat_read_header,
  360. .read_packet = concat_read_packet,
  361. .read_close = concat_read_close,
  362. .read_seek2 = concat_seek,
  363. .priv_class = &concat_class,
  364. };