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.

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