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.

499 lines
16KB

  1. /*
  2. * MOV, 3GP, MP4 muxer RTP hinting
  3. * Copyright (c) 2010 Martin Storsjo
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "movenc.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "internal.h"
  24. int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
  25. {
  26. MOVMuxContext *mov = s->priv_data;
  27. MOVTrack *track = &mov->tracks[index];
  28. MOVTrack *src_track = &mov->tracks[src_index];
  29. AVStream *src_st = s->streams[src_index];
  30. int ret = AVERROR(ENOMEM);
  31. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  32. track->tag = MKTAG('r','t','p',' ');
  33. track->src_track = src_index;
  34. if (!rtp_format) {
  35. ret = AVERROR(ENOENT);
  36. goto fail;
  37. }
  38. track->enc = avcodec_alloc_context();
  39. if (!track->enc)
  40. goto fail;
  41. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  42. track->enc->codec_tag = track->tag;
  43. track->rtp_ctx = avformat_alloc_context();
  44. if (!track->rtp_ctx)
  45. goto fail;
  46. track->rtp_ctx->oformat = rtp_format;
  47. if (!av_new_stream(track->rtp_ctx, 0))
  48. goto fail;
  49. /* Copy stream parameters */
  50. track->rtp_ctx->streams[0]->sample_aspect_ratio =
  51. src_st->sample_aspect_ratio;
  52. /* Remove the allocated codec context, link to the original one
  53. * instead, to give the rtp muxer access to codec parameters. */
  54. av_free(track->rtp_ctx->streams[0]->codec);
  55. track->rtp_ctx->streams[0]->codec = src_st->codec;
  56. if ((ret = url_open_dyn_packet_buf(&track->rtp_ctx->pb,
  57. RTP_MAX_PACKET_SIZE)) < 0)
  58. goto fail;
  59. ret = av_write_header(track->rtp_ctx);
  60. if (ret)
  61. goto fail;
  62. /* Copy the RTP AVStream timebase back to the hint AVStream */
  63. track->timescale = track->rtp_ctx->streams[0]->time_base.den;
  64. /* Mark the hinted track that packets written to it should be
  65. * sent to this track for hinting. */
  66. src_track->hint_track = index;
  67. return 0;
  68. fail:
  69. av_log(s, AV_LOG_WARNING,
  70. "Unable to initialize hinting of stream %d\n", src_index);
  71. if (track->rtp_ctx && track->rtp_ctx->pb) {
  72. uint8_t *buf;
  73. url_close_dyn_buf(track->rtp_ctx->pb, &buf);
  74. av_free(buf);
  75. }
  76. if (track->rtp_ctx && track->rtp_ctx->streams[0]) {
  77. av_metadata_free(&track->rtp_ctx->streams[0]->metadata);
  78. av_free(track->rtp_ctx->streams[0]->info);
  79. av_free(track->rtp_ctx->streams[0]);
  80. }
  81. if (track->rtp_ctx) {
  82. av_metadata_free(&track->rtp_ctx->metadata);
  83. av_free(track->rtp_ctx->priv_data);
  84. av_freep(&track->rtp_ctx);
  85. }
  86. av_freep(&track->enc);
  87. /* Set a default timescale, to avoid crashes in dump_format */
  88. track->timescale = 90000;
  89. return ret;
  90. }
  91. /**
  92. * Remove the first sample from the sample queue.
  93. */
  94. static void sample_queue_pop(HintSampleQueue *queue)
  95. {
  96. if (queue->len <= 0)
  97. return;
  98. if (queue->samples[0].own_data)
  99. av_free(queue->samples[0].data);
  100. queue->len--;
  101. memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
  102. }
  103. /**
  104. * Empty the sample queue, releasing all memory.
  105. */
  106. static void sample_queue_free(HintSampleQueue *queue)
  107. {
  108. int i;
  109. for (i = 0; i < queue->len; i++)
  110. if (queue->samples[i].own_data)
  111. av_free(queue->samples[i].data);
  112. av_freep(&queue->samples);
  113. queue->len = 0;
  114. queue->size = 0;
  115. }
  116. /**
  117. * Add a reference to the sample data to the sample queue. The data is
  118. * not copied. sample_queue_retain should be called before pkt->data
  119. * is reused/freed.
  120. */
  121. static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
  122. {
  123. /* No need to keep track of smaller samples, since describing them
  124. * with immediates is more efficient. */
  125. if (pkt->size <= 14)
  126. return;
  127. if (!queue->samples || queue->len >= queue->size) {
  128. HintSample* samples;
  129. queue->size += 10;
  130. samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
  131. if (!samples)
  132. return;
  133. queue->samples = samples;
  134. }
  135. queue->samples[queue->len].data = pkt->data;
  136. queue->samples[queue->len].size = pkt->size;
  137. queue->samples[queue->len].sample_number = sample;
  138. queue->samples[queue->len].offset = 0;
  139. queue->samples[queue->len].own_data = 0;
  140. queue->len++;
  141. }
  142. /**
  143. * Make local copies of all referenced sample data in the queue.
  144. */
  145. static void sample_queue_retain(HintSampleQueue *queue)
  146. {
  147. int i;
  148. for (i = 0; i < queue->len; ) {
  149. HintSample *sample = &queue->samples[i];
  150. if (!sample->own_data) {
  151. uint8_t* ptr = av_malloc(sample->size);
  152. if (!ptr) {
  153. /* Unable to allocate memory for this one, remove it */
  154. memmove(queue->samples + i, queue->samples + i + 1,
  155. sizeof(HintSample)*(queue->len - i - 1));
  156. queue->len--;
  157. continue;
  158. }
  159. memcpy(ptr, sample->data, sample->size);
  160. sample->data = ptr;
  161. sample->own_data = 1;
  162. }
  163. i++;
  164. }
  165. }
  166. /**
  167. * Find matches of needle[n_pos ->] within haystack. If a sufficiently
  168. * large match is found, matching bytes before n_pos are included
  169. * in the match, too (within the limits of the arrays).
  170. *
  171. * @param haystack buffer that may contain parts of needle
  172. * @param h_len length of the haystack buffer
  173. * @param needle buffer containing source data that have been used to
  174. * construct haystack
  175. * @param n_pos start position in needle used for looking for matches
  176. * @param n_len length of the needle buffer
  177. * @param match_h_offset_ptr offset of the first matching byte within haystack
  178. * @param match_n_offset_ptr offset of the first matching byte within needle
  179. * @param match_len_ptr length of the matched segment
  180. * @return 0 if a match was found, < 0 if no match was found
  181. */
  182. static int match_segments(const uint8_t *haystack, int h_len,
  183. const uint8_t *needle, int n_pos, int n_len,
  184. int *match_h_offset_ptr, int *match_n_offset_ptr,
  185. int *match_len_ptr)
  186. {
  187. int h_pos;
  188. for (h_pos = 0; h_pos < h_len; h_pos++) {
  189. int match_len = 0;
  190. int match_h_pos, match_n_pos;
  191. /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
  192. while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
  193. needle[n_pos + match_len] == haystack[h_pos + match_len])
  194. match_len++;
  195. if (match_len <= 8)
  196. continue;
  197. /* If a sufficiently large match was found, try to expand
  198. * the matched segment backwards. */
  199. match_h_pos = h_pos;
  200. match_n_pos = n_pos;
  201. while (match_n_pos > 0 && match_h_pos > 0 &&
  202. needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
  203. match_n_pos--;
  204. match_h_pos--;
  205. match_len++;
  206. }
  207. if (match_len <= 14)
  208. continue;
  209. *match_h_offset_ptr = match_h_pos;
  210. *match_n_offset_ptr = match_n_pos;
  211. *match_len_ptr = match_len;
  212. return 0;
  213. }
  214. return -1;
  215. }
  216. /**
  217. * Look for segments in samples in the sample queue matching the data
  218. * in ptr. Samples not matching are removed from the queue. If a match
  219. * is found, the next time it will look for matches starting from the
  220. * end of the previous matched segment.
  221. *
  222. * @param data data to find matches for in the sample queue
  223. * @param len length of the data buffer
  224. * @param queue samples used for looking for matching segments
  225. * @param pos the offset in data of the matched segment
  226. * @param match_sample the number of the sample that contained the match
  227. * @param match_offset the offset of the matched segment within the sample
  228. * @param match_len the length of the matched segment
  229. * @return 0 if a match was found, < 0 if no match was found
  230. */
  231. static int find_sample_match(const uint8_t *data, int len,
  232. HintSampleQueue *queue, int *pos,
  233. int *match_sample, int *match_offset,
  234. int *match_len)
  235. {
  236. while (queue->len > 0) {
  237. HintSample *sample = &queue->samples[0];
  238. /* If looking for matches in a new sample, skip the first 5 bytes,
  239. * since they often may be modified/removed in the output packet. */
  240. if (sample->offset == 0 && sample->size > 5)
  241. sample->offset = 5;
  242. if (match_segments(data, len, sample->data, sample->offset,
  243. sample->size, pos, match_offset, match_len) == 0) {
  244. *match_sample = sample->sample_number;
  245. /* Next time, look for matches at this offset, with a little
  246. * margin to this match. */
  247. sample->offset = *match_offset + *match_len + 5;
  248. if (sample->offset + 10 >= sample->size)
  249. sample_queue_pop(queue); /* Not enough useful data left */
  250. return 0;
  251. }
  252. if (sample->offset < 10 && sample->size > 20) {
  253. /* No match found from the start of the sample,
  254. * try from the middle of the sample instead. */
  255. sample->offset = sample->size/2;
  256. } else {
  257. /* No match for this sample, remove it */
  258. sample_queue_pop(queue);
  259. }
  260. }
  261. return -1;
  262. }
  263. static void output_immediate(const uint8_t *data, int size,
  264. ByteIOContext *out, int *entries)
  265. {
  266. while (size > 0) {
  267. int len = size;
  268. if (len > 14)
  269. len = 14;
  270. put_byte(out, 1); /* immediate constructor */
  271. put_byte(out, len); /* amount of valid data */
  272. put_buffer(out, data, len);
  273. data += len;
  274. size -= len;
  275. for (; len < 14; len++)
  276. put_byte(out, 0);
  277. (*entries)++;
  278. }
  279. }
  280. static void output_match(ByteIOContext *out, int match_sample,
  281. int match_offset, int match_len, int *entries)
  282. {
  283. put_byte(out, 2); /* sample constructor */
  284. put_byte(out, 0); /* track reference */
  285. put_be16(out, match_len);
  286. put_be32(out, match_sample);
  287. put_be32(out, match_offset);
  288. put_be16(out, 1); /* bytes per block */
  289. put_be16(out, 1); /* samples per block */
  290. (*entries)++;
  291. }
  292. static void describe_payload(const uint8_t *data, int size,
  293. ByteIOContext *out, int *entries,
  294. HintSampleQueue *queue)
  295. {
  296. /* Describe the payload using different constructors */
  297. while (size > 0) {
  298. int match_sample, match_offset, match_len, pos;
  299. if (find_sample_match(data, size, queue, &pos, &match_sample,
  300. &match_offset, &match_len) < 0)
  301. break;
  302. output_immediate(data, pos, out, entries);
  303. data += pos;
  304. size -= pos;
  305. output_match(out, match_sample, match_offset, match_len, entries);
  306. data += match_len;
  307. size -= match_len;
  308. }
  309. output_immediate(data, size, out, entries);
  310. }
  311. /**
  312. * Write an RTP hint (that may contain one or more RTP packets)
  313. * for the packets in data. data contains one or more packets with a
  314. * BE32 size header.
  315. *
  316. * @param out buffer where the hints are written
  317. * @param data buffer containing RTP packets
  318. * @param size the size of the data buffer
  319. * @param trk the MOVTrack for the hint track
  320. * @param pts pointer where the timestamp for the written RTP hint is stored
  321. * @return the number of RTP packets in the written hint
  322. */
  323. static int write_hint_packets(ByteIOContext *out, const uint8_t *data,
  324. int size, MOVTrack *trk, int64_t *pts)
  325. {
  326. int64_t curpos;
  327. int64_t count_pos, entries_pos;
  328. int count = 0, entries;
  329. count_pos = url_ftell(out);
  330. /* RTPsample header */
  331. put_be16(out, 0); /* packet count */
  332. put_be16(out, 0); /* reserved */
  333. while (size > 4) {
  334. uint32_t packet_len = AV_RB32(data);
  335. uint16_t seq;
  336. uint32_t ts;
  337. data += 4;
  338. size -= 4;
  339. if (packet_len > size || packet_len <= 12)
  340. break;
  341. if (data[1] >= 200 && data[1] <= 204) {
  342. /* RTCP packet, just skip */
  343. data += packet_len;
  344. size -= packet_len;
  345. continue;
  346. }
  347. if (packet_len > trk->max_packet_size)
  348. trk->max_packet_size = packet_len;
  349. seq = AV_RB16(&data[2]);
  350. ts = AV_RB32(&data[4]);
  351. if (trk->prev_rtp_ts == 0)
  352. trk->prev_rtp_ts = ts;
  353. /* Unwrap the 32-bit RTP timestamp that wraps around often
  354. * into a not (as often) wrapping 64-bit timestamp. */
  355. trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
  356. trk->prev_rtp_ts = ts;
  357. if (*pts == AV_NOPTS_VALUE)
  358. *pts = trk->cur_rtp_ts_unwrapped;
  359. count++;
  360. /* RTPpacket header */
  361. put_be32(out, 0); /* relative_time */
  362. put_buffer(out, data, 2); /* RTP header */
  363. put_be16(out, seq); /* RTPsequenceseed */
  364. put_be16(out, 0); /* reserved + flags */
  365. entries_pos = url_ftell(out);
  366. put_be16(out, 0); /* entry count */
  367. data += 12;
  368. size -= 12;
  369. packet_len -= 12;
  370. entries = 0;
  371. /* Write one or more constructors describing the payload data */
  372. describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
  373. data += packet_len;
  374. size -= packet_len;
  375. curpos = url_ftell(out);
  376. url_fseek(out, entries_pos, SEEK_SET);
  377. put_be16(out, entries);
  378. url_fseek(out, curpos, SEEK_SET);
  379. }
  380. curpos = url_ftell(out);
  381. url_fseek(out, count_pos, SEEK_SET);
  382. put_be16(out, count);
  383. url_fseek(out, curpos, SEEK_SET);
  384. return count;
  385. }
  386. int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
  387. int track_index, int sample)
  388. {
  389. MOVMuxContext *mov = s->priv_data;
  390. MOVTrack *trk = &mov->tracks[track_index];
  391. AVFormatContext *rtp_ctx = trk->rtp_ctx;
  392. uint8_t *buf = NULL;
  393. int size;
  394. ByteIOContext *hintbuf = NULL;
  395. AVPacket hint_pkt;
  396. int ret = 0, count;
  397. if (!rtp_ctx)
  398. return AVERROR(ENOENT);
  399. if (!rtp_ctx->pb)
  400. return AVERROR(ENOMEM);
  401. sample_queue_push(&trk->sample_queue, pkt, sample);
  402. /* Feed the packet to the RTP muxer */
  403. ff_write_chained(rtp_ctx, 0, pkt, s);
  404. /* Fetch the output from the RTP muxer, open a new output buffer
  405. * for next time. */
  406. size = url_close_dyn_buf(rtp_ctx->pb, &buf);
  407. if ((ret = url_open_dyn_packet_buf(&rtp_ctx->pb,
  408. RTP_MAX_PACKET_SIZE)) < 0)
  409. goto done;
  410. if (size <= 0)
  411. goto done;
  412. /* Open a buffer for writing the hint */
  413. if ((ret = url_open_dyn_buf(&hintbuf)) < 0)
  414. goto done;
  415. av_init_packet(&hint_pkt);
  416. count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
  417. av_freep(&buf);
  418. /* Write the hint data into the hint track */
  419. hint_pkt.size = size = url_close_dyn_buf(hintbuf, &buf);
  420. hint_pkt.data = buf;
  421. hint_pkt.pts = hint_pkt.dts;
  422. hint_pkt.stream_index = track_index;
  423. if (pkt->flags & AV_PKT_FLAG_KEY)
  424. hint_pkt.flags |= AV_PKT_FLAG_KEY;
  425. if (count > 0)
  426. ff_mov_write_packet(s, &hint_pkt);
  427. done:
  428. av_free(buf);
  429. sample_queue_retain(&trk->sample_queue);
  430. return ret;
  431. }
  432. void ff_mov_close_hinting(MOVTrack *track) {
  433. AVFormatContext* rtp_ctx = track->rtp_ctx;
  434. uint8_t *ptr;
  435. av_freep(&track->enc);
  436. sample_queue_free(&track->sample_queue);
  437. if (!rtp_ctx)
  438. return;
  439. if (rtp_ctx->pb) {
  440. av_write_trailer(rtp_ctx);
  441. url_close_dyn_buf(rtp_ctx->pb, &ptr);
  442. av_free(ptr);
  443. }
  444. av_metadata_free(&rtp_ctx->streams[0]->metadata);
  445. av_metadata_free(&rtp_ctx->metadata);
  446. av_free(rtp_ctx->streams[0]->info);
  447. av_free(rtp_ctx->streams[0]);
  448. av_freep(&rtp_ctx);
  449. }