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.

429 lines
13KB

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