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.

472 lines
15KB

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