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.

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